42_malloc/src/chunk_manager.c

63 lines
1.8 KiB
C
Raw Normal View History

2024-07-30 03:28:43 -04:00
#include "chunk.h"
#include "align.h"
int get_unused_chunk(chunk_t *root, size_t size, chunk_t *result)
{
void** current = root->current;
while (current != NULL)
{
if ((bool) current[CHUNK_IS_USED_POS] == true)
continue;
if ((size_t) current[CHUNK_SIZE_POS] >= size)
{
chunk_read(current, result);
return 0;
}
current = current[CHUNK_NEXT_POS];
}
return 1;
}
void chunk_merge(chunk_t *first, chunk_t *second)
{
//if (first->block_id != second->block_id)
first->size = first->size + second->size + CHUNK_SIZE + ALIGN_MARGING - get_align_increment(first->next);
first->next = second->next;
}
int chunk_split(chunk_t *chunk, chunk_t *new_chunk, size_t new_size)
{
// NOT ENOUGH SIZE TO BE SPLITTED
if (chunk->size + 1 < new_size + CHUNK_SIZE + get_align_increment(chunk->current + CHUNK_SIZE))
return 1;
void *new_chunk_pos = chunk->data_start + new_size;
init_chunk(new_chunk, chunk->size - new_size - CHUNK_SIZE - get_align_increment(new_chunk_pos + CHUNK_SIZE), chunk->block_id, chunk->current, new_chunk_pos, chunk->next, true);
init_chunk(chunk, new_size, chunk->block_id, chunk->prev, chunk->current, new_chunk->current, false);
return 0;
}
void destroy_chunk(chunk_t *chunk)
{
chunk_t chunk_next_to;
if (chunk->prev != NULL)
{
chunk_read(chunk->prev, &chunk_next_to);
if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false)
chunk_merge(&chunk_next_to, chunk);
*chunk = chunk_next_to;
}
if (chunk->next != NULL)
{
chunk_read(chunk->next, &chunk_next_to);
if (chunk_next_to.block_id == chunk->block_id && chunk_next_to.is_used == false)
chunk_merge(chunk, &chunk_next_to);
}
chunk->is_used = false;
chunk_write(chunk);
}