OXYGENHUB
◆ main openmsx / src / unittest / monotonic_allocator_test.cc
1.8 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
e8555c89 Andy McCall 1
#include "catch.hpp"
2
3
#include "monotonic_allocator.hh"
4
5
#include <algorithm>
6
#include <bit>
7
#include <span>
8
9
[[nodiscard]] static char* alloc(monotonic_allocator& a, size_t size, size_t alignment)
10
{
11
	auto* result = static_cast<char*>(a.allocate(size, alignment));
12
	CHECK(result != nullptr);
13
	CHECK((std::bit_cast<uintptr_t>(result) & (alignment - 1)) == 0);
14
	std::ranges::fill(std::span{result, size}, 0xab); // this shouldn't crash
15
	return result;
16
}
17
18
TEST_CASE("monotonic_allocator")
19
{
20
	SECTION("default") {
21
		monotonic_allocator a;
22
		char* p1 = alloc(a, 300, 4);
23
24
		char* p2 = alloc(a, 600, 4);
25
		CHECK(p1 + 300 == p2); // adjacent
26
27
		char* p3 = alloc(a, 600, 4);
28
		CHECK(p2 + 600 != p3); // not adjacent, doesn't fit in initial 1kB block
29
30
		char* p4 = alloc(a, 600, 4);
31
		CHECK(p3 + 600 == p4); // adjacent again because 2nd block is 2kB
32
33
		char* p5 = alloc(a, 10'000, 4);
34
		CHECK(p4 + 600 != p5); // not adjacent
35
	}
36
	SECTION("initial size") {
37
		monotonic_allocator a(100);
38
		char* p1 = alloc(a, 32, 4);
39
40
		char* p2 = alloc(a, 32, 4);
41
		CHECK(p1 + 32 == p2); // adjacent
42
43
		char* p3 = alloc(a, 32, 4);
44
		CHECK(p1 + 64 == p3); // adjacent
45
46
		char* p4 = alloc(a, 32, 4);
47
		CHECK(p1 + 96 != p4); // not adjacent
48
	}
49
	SECTION("initial buffer") {
50
		std::array<char, 100> buf;
51
		monotonic_allocator a(buf.data(), buf.size());
52
53
		char* p1 = alloc(a, 40, 1);
54
		CHECK(p1 == buf.data());
55
56
		char* p2 = alloc(a, 40, 1);
57
		CHECK(p2 == &buf[40]);
58
59
		char* p3 = alloc(a, 40, 1);
60
		CHECK(p3 != &buf[80]);
61
62
		char* p4 = alloc(a, 40, 1);
63
		CHECK(p4 == p3 + 40);
64
65
		char* p5 = alloc(a, 40, 1);
66
		CHECK(p5 == p3 + 80);
67
	}
68
	SECTION("alignment") {
69
		monotonic_allocator a;
70
		char* p1 = alloc(a, 13, 1);
71
72
		char* p2 = alloc(a, 4, 4);
73
		CHECK(p2 == p1 + 16);
74
75
		char* p3 = alloc(a, 3, 2);
76
		CHECK(p3 == p2 + 4);
77
78
		char* p4 = alloc(a, 3, 2);
79
		CHECK(p4 == p3 + 4);
80
	}
81
}