snapraid/tommyds/tommyarray.c

60 lines
1.5 KiB
C
Raw Normal View History

// SPDX-License-Identifier: BSD-2-Clause
// Copyright (C) 2011 Andrea Mazzoleni
2011-03-01 22:21:30 +01:00
#include "tommyarray.h"
/******************************************************************************/
/* array */
2025-12-03 19:10:13 +01:00
TOMMY_API void tommy_array_init(tommy_array* array)
2011-03-01 22:21:30 +01:00
{
2014-10-25 17:28:41 +02:00
tommy_uint_t i;
2014-09-26 23:50:01 +02:00
2011-03-01 22:21:30 +01:00
/* fixed initial size */
array->bucket_bit = TOMMY_ARRAY_BIT;
2018-04-01 22:36:42 +02:00
array->bucket_max = (tommy_size_t)1 << array->bucket_bit;
2014-09-26 23:50:01 +02:00
array->bucket[0] = tommy_cast(void**, tommy_calloc(array->bucket_max, sizeof(void*)));
for (i = 1; i < TOMMY_ARRAY_BIT; ++i)
array->bucket[i] = array->bucket[0];
2013-06-22 17:27:03 +02:00
2014-10-25 17:28:41 +02:00
array->count = 0;
2011-03-01 22:21:30 +01:00
}
2025-12-03 19:10:13 +01:00
TOMMY_API void tommy_array_done(tommy_array* array)
2011-03-01 22:21:30 +01:00
{
2014-10-25 17:28:41 +02:00
tommy_uint_t i;
2014-09-26 23:50:01 +02:00
tommy_free(array->bucket[0]);
2014-10-25 17:28:41 +02:00
for (i = TOMMY_ARRAY_BIT; i < array->bucket_bit; ++i) {
2014-09-26 23:50:01 +02:00
void** segment = array->bucket[i];
2018-04-01 22:36:42 +02:00
tommy_free(&segment[(tommy_ptrdiff_t)1 << i]);
2014-09-26 23:50:01 +02:00
}
2011-03-01 22:21:30 +01:00
}
2025-12-03 19:10:13 +01:00
TOMMY_API void tommy_array_grow(tommy_array* array, tommy_size_t count)
2011-03-01 22:21:30 +01:00
{
2014-10-25 17:28:41 +02:00
if (array->count >= count)
2014-09-26 23:50:01 +02:00
return;
2014-10-25 17:28:41 +02:00
array->count = count;
2014-09-26 23:50:01 +02:00
2014-10-25 17:28:41 +02:00
while (count > array->bucket_max) {
2014-09-26 23:50:01 +02:00
void** segment;
2013-06-22 17:27:03 +02:00
2014-09-26 23:50:01 +02:00
/* allocate one more segment */
segment = tommy_cast(void**, tommy_calloc(array->bucket_max, sizeof(void*)));
/* store it adjusting the offset */
2014-09-30 23:26:32 +02:00
/* cast to ptrdiff_t to ensure to get a negative value */
2014-10-25 17:28:41 +02:00
array->bucket[array->bucket_bit] = &segment[-(tommy_ptrdiff_t)array->bucket_max];
2013-06-22 17:27:03 +02:00
2011-03-01 22:21:30 +01:00
++array->bucket_bit;
2018-04-01 22:36:42 +02:00
array->bucket_max = (tommy_size_t)1 << array->bucket_bit;
2011-03-01 22:21:30 +01:00
}
}
2025-12-03 19:10:13 +01:00
TOMMY_API tommy_size_t tommy_array_memory_usage(tommy_array* array)
2011-03-01 22:21:30 +01:00
{
2013-06-23 21:49:36 +02:00
return array->bucket_max * (tommy_size_t)sizeof(void*);
2011-03-01 22:21:30 +01:00
}