Freelist implementation
This commit is contained in:
parent
aa013fa349
commit
293e790573
4 changed files with 252 additions and 0 deletions
85
freelist/main.c
Normal file
85
freelist/main.c
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
#include "freelist.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
int x, y, z;
|
||||
} Vec3;
|
||||
|
||||
Vec3 vec3_new(int a, int b, int c) {
|
||||
return (Vec3){a, b, c};
|
||||
}
|
||||
|
||||
// Print function
|
||||
void printvec(const Vec3 *v) {
|
||||
printf("Vec3: (%d, %d, %d)\n", v->x, v->y, v->z);
|
||||
}
|
||||
|
||||
int main() {
|
||||
FreeList fl;
|
||||
char *mem = malloc(4096);
|
||||
|
||||
fl_init(&fl, (uintptr_t)mem, (uintptr_t)mem + 4096, sizeof(Vec3));
|
||||
size_t cap = fl_capacity(&fl);
|
||||
assert(fl_available(&fl) == cap);
|
||||
|
||||
printf("Space utilization: %.2f%%\n", 100.0 * fl_utilization(&fl, sizeof(Vec3)));
|
||||
|
||||
Vec3 *a = fl_alloc(&fl);
|
||||
Vec3 *b = fl_alloc(&fl);
|
||||
Vec3 *c = fl_alloc(&fl);
|
||||
|
||||
memset(a, 0x23, sizeof(Vec3));
|
||||
memset(b, 0x24, sizeof(Vec3));
|
||||
memset(c, 0x25, sizeof(Vec3));
|
||||
|
||||
*a = vec3_new(12, 13, 435);
|
||||
*b = vec3_new(192, 199, 435);
|
||||
*c = vec3_new(432, 11, 435);
|
||||
|
||||
printvec(a);
|
||||
printvec(b);
|
||||
printvec(c);
|
||||
|
||||
assert(fl_check(&fl) == cap - 3);
|
||||
assert(fl_capacity(&fl) == fl_available(&fl) + 3);
|
||||
|
||||
printf("Available: %zu of %zu\n", fl_available(&fl), fl_capacity(&fl));
|
||||
|
||||
assert(fl_free(&fl, a) == EXIT_SUCCESS);
|
||||
assert(fl_free(&fl, b) == EXIT_SUCCESS);
|
||||
assert(fl_free(&fl, c) == EXIT_SUCCESS);
|
||||
assert(fl_free(&fl, a) == EXIT_FAILURE); // Double free
|
||||
|
||||
printf("Available: %zu of %zu\n", fl_available(&fl), fl_capacity(&fl));
|
||||
|
||||
assert(fl_check(&fl) == fl_capacity(&fl) - fl_allocated(&fl));
|
||||
assert(fl_allocated(&fl) == 0);
|
||||
|
||||
/* All memory is free here */
|
||||
|
||||
uintptr_t *ptr_buf = malloc(sizeof(uintptr_t) * fl_capacity(&fl));
|
||||
|
||||
/* Fill it up */
|
||||
for (int i = 0; i < fl_capacity(&fl); i++) {
|
||||
ptr_buf[i] = (uintptr_t)fl_alloc(&fl);
|
||||
}
|
||||
|
||||
assert(0 == fl_available(&fl));
|
||||
assert(fl_allocated(&fl) == fl_capacity(&fl));
|
||||
assert(fl_check(&fl) == 0);
|
||||
|
||||
/* Return it all */
|
||||
for (int i = 0; i < fl_capacity(&fl); i++) {
|
||||
fl_free(&fl, (void *)ptr_buf[i]);
|
||||
}
|
||||
|
||||
assert(cap == fl_available(&fl));
|
||||
assert(fl_allocated(&fl) == 0);
|
||||
assert(fl_check(&fl) == cap);
|
||||
|
||||
printf("All tests passed!\n");
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue