From 434ddcd907832b1febc7d70e4faa52109c7eb3bd Mon Sep 17 00:00:00 2001 From: Jon Santmyer Date: Wed, 7 Oct 2026 17:37:26 -0400 Subject: add memory region object for better memory managment --- lib/bitmap.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ lib/bitmap.h | 25 +++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 lib/bitmap.c create mode 100644 lib/bitmap.h (limited to 'lib') diff --git a/lib/bitmap.c b/lib/bitmap.c new file mode 100644 index 0000000..bfd6cbc --- /dev/null +++ b/lib/bitmap.c @@ -0,0 +1,51 @@ +#include "bitmap.h" +#include "api/error.h" + +inline bool +bitmap_check(struct bitmap *bitmap, size_t idx) +{ + return bitmap->data[idx / BITMAP_BLOCK_BITS] & (1U << (idx % BITMAP_BLOCK_BITS)); +} + +inline void +bitmap_set(struct bitmap *bitmap, size_t idx) +{ + bitmap->data[idx / BITMAP_BLOCK_BITS] |= (1U << (idx % BITMAP_BLOCK_BITS)); + bitmap->free_bits--; +} + +inline void +bitmap_unset(struct bitmap *bitmap, size_t idx) +{ + bitmap->data[idx / BITMAP_BLOCK_BITS] &= ~(1U << (idx % BITMAP_BLOCK_BITS)); + bitmap->free_bits++; +} + +int +bitmap_findfree(struct bitmap *bitmap) +{ + int cycles = 0; + while(cycles++ < bitmap->total_bits) { + if(bitmap_check(bitmap, bitmap->last_free_bit)) { + bitmap->last_free_bit = (bitmap->last_free_bit + 1) % bitmap->total_bits; + continue; + } + return bitmap->last_free_bit++; + } + return -EFULL; +} + +int +bitmap_findfree_contig(struct bitmap *bitmap, size_t size) +{ + size_t last_contig = 0; + for(size_t i = 0; i < bitmap->total_bits; i++) { + if(bitmap_check(bitmap, i)) { + last_contig = i++; + continue; + } + if(last_contig - i == size - 1) + return last_contig; + } + return -EFULL; +} diff --git a/lib/bitmap.h b/lib/bitmap.h new file mode 100644 index 0000000..db9653a --- /dev/null +++ b/lib/bitmap.h @@ -0,0 +1,25 @@ +#ifndef _JOVE_LIB_BITMAP_H +#define _JOVE_LIB_BITMAP_H 1 + +#include +#include + +typedef unsigned char bitmap_block_t; +#define BITMAP_BLOCK_BITS (sizeof(bitmap_block_t) * 8) + +struct bitmap +{ + unsigned int total_bits; + unsigned int free_bits; + unsigned int last_free_bit; + bitmap_block_t data[]; +}; + +extern bool bitmap_check(struct bitmap *bitmap, size_t idx); +extern void bitmap_set(struct bitmap *bitmap, size_t idx); +extern void bitmap_unset(struct bitmap *bitmap, size_t idx); + +int bitmap_findfree(struct bitmap *bitmap); +int bitmap_findfree_contig(struct bitmap *bitmap, size_t size); + +#endif -- cgit v1.2.3