implemented List_increaseCapacity_size

This commit is contained in:
Timerix 2025-11-10 10:29:50 +05:00
parent 958cb269b2
commit 2de044711f
4 changed files with 29 additions and 14 deletions

View File

@ -21,6 +21,8 @@ List_ List_alloc_size(u32 initial_size);
List_ List_copy(List_ src);
// alloc bigger buffer if size + size_to_add won't fit in current
void List_increaseCapacity_size(List_* self, u32 size_to_add);
void* List_expand_size(List_* self, u32 size_to_add);
#define List_push(SELF, T, VALUE) *(T*)(List_expand_size(SELF, sizeof(T))) = VALUE
#define List_pushMany(SELF, T, VALUES_PTR, COUNT) List_push_size(SELF, VALUES_PTR, (COUNT) * sizeof(T))
@ -30,4 +32,6 @@ void List_push_size(List_* self, void* values, u32 size);
bool List_removeAt_size(List_* self, u32 i, u32 remove_size);
#define List_len(SELF, T) (SELF.size / sizeof(T))
#define List_index(SELF, T, I) ((T*)SELF.data)[I]
#define List_castTo_Array(SELF) Array_construct_size(SELF.data, SELF.size)

View File

@ -16,8 +16,10 @@ void StringBuilder_destroy(StringBuilder* b);
static inline StringBuilder StringBuilder_copy(const StringBuilder* b){
return (StringBuilder) { .buffer = List_copy(b->buffer) };
}
static inline void StringBuilder_expand(StringBuilder* b, u32 size_to_add){
List_expand_size(&b->buffer, size_to_add);
// alloc bigger buffer if size + size_to_add won't fit in current
static inline void StringBuilder_increaseCapacity(StringBuilder* b, u32 size_to_add){
List_increaseCapacity_size(&b->buffer, size_to_add);
}

View File

@ -14,19 +14,28 @@ List_ List_copy(const List_ src){
return copy;
}
void* List_expand_size(List_* self, u32 size_to_add){
void List_increaseCapacity_size(List_* self, u32 size_to_add){
u32 occupied_size = self->size;
u32 expanded_size = occupied_size + size_to_add;
if(self->allocated_size < expanded_size) {
u32 expanded_alloc_size = self->allocated_size;
if(expanded_alloc_size == 0)
expanded_alloc_size = 64;
self->size += size_to_add;
while(self->size > expanded_alloc_size){
expanded_alloc_size = 32;
while(expanded_alloc_size < expanded_size){
expanded_alloc_size *= 2;
}
// if self->data is null, realloc acts like malloc
self->data = realloc(self->data, expanded_alloc_size);
self->allocated_size = expanded_alloc_size;
return (u8*)(self->data) + occupied_size;
}
}
void* List_expand_size(List_* self, u32 size_to_add){
List_increaseCapacity_size(self, size_to_add);
u8* empty_cell_ptr = (u8*)self->data + self->size;
self->size += size_to_add;
return empty_cell_ptr;
}
void List_push_size(List_* self, void* values, u32 size){

View File

@ -8,7 +8,7 @@ Error* Error_create(const char* msg, bool is_msg_on_heap, ErrorCallPos p){
e->msg = str_construct((char*)(void*)msg, strlen(msg), true);
e->is_msg_on_heap = is_msg_on_heap;
e->call_stack = List_alloc(ErrorCallPos, 16);
List_push(&e->call_stack, ErrorCallPos, p);
Error_addCallPos(e, p);
return e;
}