CPlay/freelist/freelist.c

123 lines
3.2 KiB
C

#include "freelist.h"
#include "stddef.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct __attribute__((packed)) FreeListBlock {
struct FreeListBlock *next;
};
/* Align to nearest multiple of align */
static inline size_t align_up_to(size_t n, size_t align) {
return (n + align - 1) & ~(align - 1);
}
/* Initialize the FreeList */
int fl_init(FreeList *fl, uintptr_t start, size_t size_bytes, size_t itemsize) {
/* Fiddle around according to your need, (void *) alignment seems to be enough,
* but MAX_ALIGN_T is also an option. Especially for allocator implementation. */
size_t size = align_up_to(itemsize, sizeof(void *));
if (size < sizeof(FreeListBlock) || !fl) {
return 0;
}
fl->start = start;
fl->end = start + size_bytes;
fl->size = size;
fl->allocated = 0;
FreeListBlock *block = (FreeListBlock *)start;
for (size_t i = 0; i < fl_capacity(fl); i++) {
block->next = (FreeListBlock *)((void *)block + size);
block = block->next;
}
block->next = NULL; /* Last block */
fl->free = (FreeListBlock *)start;
return 1;
}
/* Allocate some memory from the FreeList */
void *fl_alloc(FreeList *fl) {
if (!fl->free)
return NULL;
FreeListBlock *m = fl->free;
fl->free = fl->free->next; /* May be null, which is fine */
fl->allocated++;
memset((void *)m, 0, sizeof(FreeListBlock));
return ((void *)m);
}
/* Return some memory to the FreeList */
int fl_free(FreeList *fl, void *ptr) {
if (!fl_is_managed(fl, ptr))
return 0; /* We cant free memory we do not own */
FreeListBlock *block = (FreeListBlock *)ptr;
block->next = fl->free; /* May be null, which is fine */
fl->free = block;
fl->allocated--;
return 1;
}
/* Returns how many slots are occupied */
size_t fl_allocated(FreeList *fl) {
return fl->allocated;
}
/* Returns how many free slots are available (O(1)) */
size_t fl_available(FreeList *fl) {
return fl_capacity(fl) - fl->allocated;
}
/* Returns the total amount of items the freelist will hold */
size_t fl_capacity(FreeList *fl) {
return (fl->end - fl->start) / fl->size;
}
/* Check if a piece of memory is managed by the FreeList */
int fl_is_managed(FreeList *fl, void *ptr) {
uintptr_t p = (uintptr_t)ptr;
if (p < fl->start || p >= fl->end) {
return 0; // outside pool
}
return ((p - fl->start) % fl->size) == 0; // aligned to block
}
/* Returns the ratio of metadata versus data as a scalar in range 0..1 */
float fl_utilization(FreeList *fl, size_t itemsize) {
return (float)itemsize / fl->size;
}
/* Walks the free pages/slots, returns total count (O(n), given no cycles) */
size_t fl_check(FreeList *fl) {
int avail = 0;
FreeListBlock *cursor = fl->free;
while (cursor->next != NULL) {
cursor = cursor->next;
if (!fl_is_managed(fl, cursor)) {
printf("Unused memory at: %zX\n", (size_t)cursor->next);
printf("Min memory at: %zX\n", (size_t)fl->start);
printf("Max memory at: %zX\n", (size_t)fl->end);
return 0;
}
avail++;
}
return avail;
}