tlibc/src/collections/List.c

56 lines
1.7 KiB
C
Executable File

#include "tlibc/collections/List.h"
List_ List_alloc_size(u32 initial_size){
if(initial_size == 0)
return List_construct_size(NULL, 0, 0);
u32 allocated_size = ALIGN_TO(initial_size, sizeof(void*));
return List_construct_size(malloc(allocated_size), 0, allocated_size);
}
List_ List_copy(const List_ src){
List_ copy = List_alloc_size(src.allocated_size);
if(copy.data != NULL)
memcpy(copy.data, src.data, src.size);
return copy;
}
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 = 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;
}
}
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){
void* empty_cell_ptr = List_expand_size(self, size);
memcpy(empty_cell_ptr, values, size);
}
bool List_removeAt_size(List_* self, u32 i, u32 remove_size){
if(i + remove_size >= self->size)
return false;
self->size -= remove_size;
u8* src = (u8*)self->data + i + remove_size;
u8* dst = (u8*)self->data + i;
memmove(dst, src, self->size - i - remove_size);
return true;
}