'
This commit is contained in:
parent
7629201717
commit
ed8a843d3d
2 changed files with 69 additions and 2 deletions
|
|
@ -1,4 +1,61 @@
|
|||
#include "helpers.h"
|
||||
|
||||
size_t get_next_2power(size_t n)
|
||||
{}
|
||||
#include <sys/mman.h>
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,16 @@
|
|||
|
||||
#include <stddef.h>
|
||||
|
||||
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue