65 lines
1.8 KiB
C
65 lines
1.8 KiB
C
#include <c_PtrArrayBag.h>
|
|||
|
|
#include <c_Memory.h>
|
||
|
|
|
||
|
|
#define DEFAULT_INIT_CAPACITY 4
|
||
|
|
|
||
|
|
c_err_t c_PtrArrayBag_Init(c_PtrArrayBag_t* self, c_size_t capacity) {
|
||
|
|
if (!self) return C_ERR_PARAM;
|
||
|
|
self->capacity = (capacity > 0) ? capacity : DEFAULT_INIT_CAPACITY;
|
||
|
|
self->size = 0;
|
||
|
|
self->array = (void**)C_ALLOC(self->capacity * sizeof(void*));
|
||
|
|
if (!self->array) {
|
||
|
|
self->capacity = 0;
|
||
|
|
return C_ERR_NOMEM;
|
||
|
|
}
|
||
|
|
|
||
|
|
return C_ERR_SUCCESS;
|
||
|
|
}
|
||
|
|
|
||
|
|
void c_PtrArrayBag_Destroy(c_PtrArrayBag_t* self) {
|
||
|
|
if (!self) return;
|
||
|
|
C_FREE(self->array);
|
||
|
|
self->capacity = 0;
|
||
|
|
self->size = 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
c_err_t c_PtrArrayBag_Add(c_PtrArrayBag_t* self, void* item) {
|
||
|
|
if (!self || !self->array) return C_ERR_PARAM;
|
||
|
|
|
||
|
|
// Handle dynamic resizing (doubling capacity)
|
||
|
|
if (self->size >= self->capacity) {
|
||
|
|
const c_size_t new_capacity = self->capacity << 1;
|
||
|
|
void** new_array = (void**)C_REALLOC(self->array, new_capacity * sizeof(void*));
|
||
|
|
if (!new_array) {
|
||
|
|
return C_ERR_NOMEM;
|
||
|
|
}
|
||
|
|
self->array = new_array;
|
||
|
|
self->capacity = new_capacity;
|
||
|
|
}
|
||
|
|
|
||
|
|
self->array[self->size++] = item;
|
||
|
|
return C_ERR_SUCCESS;
|
||
|
|
}
|
||
|
|
|
||
|
|
void* c_PtrArrayBag_Get(c_PtrArrayBag_t* self, c_size_t index) {
|
||
|
|
if (!self || !self->array || index >= self->size) {
|
||
|
|
return NULL;
|
||
|
|
}
|
||
|
|
return self->array[index];
|
||
|
|
}
|
||
|
|
|
||
|
|
c_err_t c_PtrArrayBag_Remove(c_PtrArrayBag_t* self, c_size_t index) {
|
||
|
|
if (!self || !self->array) return C_ERR_PARAM;
|
||
|
|
if (index >= self->size) return C_ERR_INDEX;
|
||
|
|
|
||
|
|
// Shift elements left to fill the gap
|
||
|
|
if (index < self->size - 1) {
|
||
|
|
const c_size_t elements_to_move = self->size - index - 1;
|
||
|
|
memmove(&self->array[index], &self->array[index + 1], elements_to_move * sizeof(void*));
|
||
|
|
}
|
||
|
|
|
||
|
|
self->size--;
|
||
|
|
self->array[self->size] = NULL; // Optional clear for safety
|
||
|
|
return C_ERR_SUCCESS;
|
||
|
|
}
|