65 lines
1.5 KiB
C++
65 lines
1.5 KiB
C++
// Copyright (c) Vitaliy Filippov, 2023+
|
|
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdexcept>
|
|
#include "freelist.cpp"
|
|
|
|
inline bool operator == (const freelist_item_t & a, const freelist_item_t & b)
|
|
{
|
|
return a.start == b.start && a.size == b.size;
|
|
}
|
|
|
|
void dump(std::vector<freelist_item_t> & freelist)
|
|
{
|
|
printf("free: ");
|
|
for (auto & item: freelist)
|
|
{
|
|
printf("%lx+%lx ", item.start, item.size);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
void dump(freelist_allocator_t &alloc)
|
|
{
|
|
dump(alloc.freelist);
|
|
}
|
|
|
|
uint64_t test_alloc(freelist_allocator_t &alloc, uint64_t size)
|
|
{
|
|
uint64_t r = alloc.alloc(size);
|
|
printf("alloc %lx: %lx\n", size, r);
|
|
return r;
|
|
}
|
|
|
|
void assert_eq(freelist_allocator_t &alloc, std::vector<freelist_item_t> v)
|
|
{
|
|
if (alloc.freelist != v)
|
|
{
|
|
printf("expected ");
|
|
dump(v);
|
|
printf("got ");
|
|
dump(alloc);
|
|
throw std::runtime_error("test failed");
|
|
}
|
|
dump(alloc);
|
|
}
|
|
|
|
int main(int narg, char *args[])
|
|
{
|
|
freelist_allocator_t alloc;
|
|
alloc.free(0, 0x1000000);
|
|
assert_eq(alloc, { { 0, 0x1000000 } });
|
|
assert(test_alloc(alloc, 0x1000) == 0);
|
|
assert_eq(alloc, { { 0x1000, 0xfff000 } });
|
|
assert(test_alloc(alloc, 0x4000) == 0x1000);
|
|
alloc.free(0x1000000, 0x4000);
|
|
assert_eq(alloc, { { 0x5000, 0xfff000 } });
|
|
alloc.free(0, 0x1000);
|
|
assert_eq(alloc, { { 0, 0x1000 }, { 0x5000, 0xfff000 } });
|
|
alloc.free(0x1000, 0x4000);
|
|
assert_eq(alloc, { { 0, 0x1004000 } });
|
|
return 0;
|
|
}
|