Line data Source code
1 : // SPDX-License-Identifier: BSD-2-Clause 2 : // Copyright (C) 2013 Andrea Mazzoleni 3 : 4 : /** \file 5 : * Dynamic array based on blocks of fixed size. 6 : * 7 : * This array is able to grow dynamically upon request, without any reallocation. 8 : * 9 : * This is very similar to ::tommy_arrayblk, but it allows to store elements of any 10 : * size and not just pointers. 11 : * 12 : * Note that in this case tommy_arrayblkof_ref() returns a pointer to the element, 13 : * that should be used for getting and setting elements in the array, 14 : * as generic getter and setter are not available. 15 : */ 16 : 17 : #ifndef __TOMMYARRAYBLKOF_H 18 : #define __TOMMYARRAYBLKOF_H 19 : 20 : #include "tommytypes.h" 21 : #include "tommyarray.h" 22 : 23 : #include <assert.h> /* for assert */ 24 : 25 : /******************************************************************************/ 26 : /* array */ 27 : 28 : /** 29 : * Elements for each block. 30 : */ 31 : #define TOMMY_ARRAYBLKOF_SIZE (4 * 1024) 32 : 33 : /** 34 : * Array container type. 35 : * \note Don't use internal fields directly, but access the container only using functions. 36 : */ 37 : typedef struct tommy_arrayblkof_struct { 38 : tommy_array block; /**< Array of blocks. */ 39 : tommy_size_t element_size; /**< Size of the stored element in bytes. */ 40 : tommy_size_t count; /**< Number of initialized elements in the array. */ 41 : } tommy_arrayblkof; 42 : 43 : /** 44 : * Initializes the array. 45 : * \param element_size Size in byte of the element to store in the array. 46 : */ 47 : TOMMY_API void tommy_arrayblkof_init(tommy_arrayblkof* array, tommy_size_t element_size); 48 : 49 : /** 50 : * Deinitializes the array. 51 : */ 52 : TOMMY_API void tommy_arrayblkof_done(tommy_arrayblkof* array); 53 : 54 : /** 55 : * Grows the size up to the specified value. 56 : * All the new elements in the array are initialized with the 0 value. 57 : */ 58 : TOMMY_API void tommy_arrayblkof_grow(tommy_arrayblkof* array, tommy_size_t size); 59 : 60 : /** 61 : * Gets a reference of the element at the specified position. 62 : * You must be sure that space for this position is already 63 : * allocated calling tommy_arrayblkof_grow(). 64 : */ 65 4910388 : tommy_inline void* tommy_arrayblkof_ref(tommy_arrayblkof* array, tommy_size_t pos) 66 : { 67 : unsigned char* base; 68 : 69 4910388 : assert(pos < array->count); 70 : 71 4910388 : base = tommy_cast(unsigned char*, tommy_array_get(&array->block, pos / TOMMY_ARRAYBLKOF_SIZE)); 72 : 73 4910388 : return base + (pos % TOMMY_ARRAYBLKOF_SIZE) * array->element_size; 74 : } 75 : 76 : /** 77 : * Gets the initialized size of the array. 78 : */ 79 3329040 : tommy_inline tommy_size_t tommy_arrayblkof_size(tommy_arrayblkof* array) 80 : { 81 3329040 : return array->count; 82 : } 83 : 84 : /** 85 : * Gets the size of allocated memory. 86 : */ 87 : TOMMY_API tommy_size_t tommy_arrayblkof_memory_usage(tommy_arrayblkof* array); 88 : 89 : #endif