Line data Source code
1 : // SPDX-License-Identifier: BSD-2-Clause 2 : // Copyright (C) 2011 Andrea Mazzoleni 3 : 4 : #include "tommyarray.h" 5 : 6 : /******************************************************************************/ 7 : /* array */ 8 : 9 614 : TOMMY_API void tommy_array_init(tommy_array* array) 10 : { 11 : tommy_uint_t i; 12 : 13 : /* fixed initial size */ 14 614 : array->bucket_bit = TOMMY_ARRAY_BIT; 15 614 : array->bucket_max = (tommy_size_t)1 << array->bucket_bit; 16 614 : array->bucket[0] = tommy_cast(void**, tommy_calloc(array->bucket_max, sizeof(void*))); 17 3684 : for (i = 1; i < TOMMY_ARRAY_BIT; ++i) 18 3070 : array->bucket[i] = array->bucket[0]; 19 : 20 614 : array->count = 0; 21 614 : } 22 : 23 588 : TOMMY_API void tommy_array_done(tommy_array* array) 24 : { 25 : tommy_uint_t i; 26 : 27 588 : tommy_free(array->bucket[0]); 28 590 : for (i = TOMMY_ARRAY_BIT; i < array->bucket_bit; ++i) { 29 2 : void** segment = array->bucket[i]; 30 2 : tommy_free(&segment[(tommy_ptrdiff_t)1 << i]); 31 : } 32 588 : } 33 : 34 2455 : TOMMY_API void tommy_array_grow(tommy_array* array, tommy_size_t count) 35 : { 36 2455 : if (array->count >= count) 37 1 : return; 38 2454 : array->count = count; 39 : 40 2456 : while (count > array->bucket_max) { 41 : void** segment; 42 : 43 : /* allocate one more segment */ 44 2 : segment = tommy_cast(void**, tommy_calloc(array->bucket_max, sizeof(void*))); 45 : 46 : /* store it adjusting the offset */ 47 : /* cast to ptrdiff_t to ensure to get a negative value */ 48 2 : array->bucket[array->bucket_bit] = &segment[-(tommy_ptrdiff_t)array->bucket_max]; 49 : 50 2 : ++array->bucket_bit; 51 2 : array->bucket_max = (tommy_size_t)1 << array->bucket_bit; 52 : } 53 : } 54 : 55 2 : TOMMY_API tommy_size_t tommy_array_memory_usage(tommy_array* array) 56 : { 57 2 : return array->bucket_max * (tommy_size_t)sizeof(void*); 58 : } 59 :