From ed8a843d3d34c3a7d7158521163032637b28d7d7 Mon Sep 17 00:00:00 2001 From: Guillem George Date: Wed, 5 Nov 2025 21:22:34 +0100 Subject: [PATCH] ' --- malloc/src/helpers/helpers.c | 61 ++++++++++++++++++++++++++++++++++-- malloc/src/helpers/helpers.h | 10 ++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/malloc/src/helpers/helpers.c b/malloc/src/helpers/helpers.c index bba1bc1..52db459 100644 --- a/malloc/src/helpers/helpers.c +++ b/malloc/src/helpers/helpers.c @@ -1,4 +1,61 @@ #include "helpers.h" -size_t get_next_2power(size_t n) -{} +#include + +// Returns the smallest power of 2 greater or equal to s +size_t s2p(size_t s) +{ + // Trick I found on the internet but I don't completely understand it + // Quite amazing + // n--; // 1101 1101 --> 1101 1100 + // n |= n >> 1; // 1101 1100 | 0110 1110 = 1111 1110 + // n |= n >> 2; // 1111 1110 | 0011 1111 = 1111 1111 + // n |= n >> 4; // ... + // n |= n >> 8; + // n |= n >> 16; // 1111 1111 | 1111 1111 = 1111 1111 + // n++; // 1111 1111 --> 1 0000 0000 + + // There is also an x86 assembly instruction to do that in a single cycle: + // lzcnt + // Yeah... This one is definetely wild intel + // Now since asm{} is prohibited in the coding style it won't be useful + // Or maybe there is a builtin to do that ? + // (found __builtin_clzll but not sure of what it does) + + // So here's the good old way + size_t n = 1; + while (n < s) + { + n <<= 1; + } + + return n; +} + +void *find_free_block(struct bucket *buck) +{ + unsigned maplength = buck->block_size / 8; + // for each block + for (unsigned i = 0; i < maplength; i++) + { + unsigned char map_byte = buck->free_list[i]; + unsigned char bit = 1; + // Test byte + for (unsigned j = 0; j < 8; j <<= 1) + { + if (map_byte & bit) // Test if free + return buck->page + (buck->block_size * (i * 8 + j)); + + bit <<= 1; + } + } + + return NULL; +} + +struct bucket *create_bucket(size_t min_alloc_size) +{ + size_t alloc_size = s2p(min_alloc_size); + void *page = + mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, -1, 0); +} diff --git a/malloc/src/helpers/helpers.h b/malloc/src/helpers/helpers.h index 4d5b403..51477f5 100644 --- a/malloc/src/helpers/helpers.h +++ b/malloc/src/helpers/helpers.h @@ -3,6 +3,16 @@ #include +struct bucket +{ + unsigned block_size; + unsigned char free_list[64]; // 4096 / MIN_BLOCK_SIZE / + // sizeof(unsigned char) (in bits) + char *page; +}; + size_t get_next_2power(size_t n); +void *find_free_block(struct bucket *buck); +struct bucket *create_bucket(size_t min_alloc_size); #endif // ! HELPERS_H