Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct s_free_list_node
- {
- b8 used;
- size_t size;
- s_free_list_node* next;
- };
- struct s_free_list
- {
- size_t capacity;
- u8* memory;
- s_free_list_node* first;
- void* alloc(size_t in_size);
- void* realloc(void* ptr, size_t in_size);
- void free(void* ptr);
- };
- void* s_free_list::alloc(size_t in_size)
- {
- assert(in_size > 0);
- size_t aligned_size = (in_size + 7) & ~7;
- void* result = null;
- for(s_free_list_node* node = first; node; node = node->next)
- {
- if(!node->used && node->size >= aligned_size)
- {
- node->used = true;
- result = (u8*)node + sizeof(s_free_list_node);
- if(!node->next)
- {
- s_free_list_node* new_node = (s_free_list_node*)((u8*)result + aligned_size);
- *new_node = zero;
- new_node->size = node->size - aligned_size - sizeof(s_free_list_node);
- node->next = new_node;
- node->size = aligned_size;
- }
- break;
- }
- }
- assert(result);
- return result;
- }
- void* s_free_list::realloc(void* ptr, size_t in_size)
- {
- s_free_list_node* node = (s_free_list_node*)((u8*)ptr - sizeof(s_free_list_node));
- size_t aligned_size = (in_size + 7) & ~7;
- assert(in_size > 0);
- assert(node->used);
- assert(node->size > 0);
- assert(node->size <= capacity - sizeof(s_free_list_node));
- if(aligned_size <= node->size)
- {
- return ptr;
- }
- free(ptr);
- return alloc(aligned_size);
- }
- void s_free_list::free(void* ptr)
- {
- s_free_list_node* node = (s_free_list_node*)((u8*)ptr - sizeof(s_free_list_node));
- s_free_list_node* temp = node;
- assert(node->used);
- assert(node->size > 0);
- assert(node->size <= capacity - sizeof(s_free_list_node));
- node->used = false;
- // @Note(tkap, 15/07/2023): Merge the following nodes if possible
- while(true)
- {
- temp = temp->next;
- if(!temp) { break; }
- if(temp->used) { break; }
- node->size += temp->size + sizeof(s_free_list_node);
- node->next = temp->next;
- }
- }
- func s_free_list make_free_list(void* memory, size_t capacity)
- {
- assert(capacity >= 1024);
- s_free_list result = zero;
- result.capacity = capacity;
- result.memory = (u8*)memory;
- s_free_list_node first = zero;
- first.size = capacity - sizeof(s_free_list_node);
- result.first = (s_free_list_node*)result.memory;
- *result.first = first;
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement