1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#include <gtest/gtest.h>
#include <iomanip>
#include <iostream>
namespace libk {
#include "../stdlib/linked_list_allocator.c"
std::ostream &
operator<<(std::ostream &os, const Chunk &begin)
{
for (const Chunk *iter = &begin; iter != nullptr; iter = iter->next) {
os << iter << " used=" << iter->used << " size=" << std::setw(4) << iter->size << " next=" << iter->next
<< std::endl;
}
return os;
}
}; // namespace libk
#include "allocator.hh"
TEST(UninitializedAllocator, malloc) { EXPECT_EQ(libk::malloc(1024), nullptr); }
TEST_F(TestAllocator, mallocMoreThanAvialable)
{
void *ptr = libk::malloc(memory_size);
EXPECT_EQ(ptr, nullptr) << *libk::begin;
}
TEST_F(TestAllocator, mallocExactlyAvialable)
{
void *ptr = libk::malloc(memory_size - sizeof(libk::Chunk));
EXPECT_NE(ptr, nullptr) << *libk::begin;
}
TEST_F(TestAllocator, malloc)
{
libk::Chunk *begin = libk::begin;
void *ptr0 = libk::malloc(1024);
EXPECT_NE(ptr0, nullptr) << *libk::begin;
EXPECT_EQ(reinterpret_cast<std::uintptr_t>(ptr0),
reinterpret_cast<std::uintptr_t>(libk::begin) + sizeof(libk::Chunk));
EXPECT_EQ(begin->used, 1);
EXPECT_EQ(begin->size, 1024);
ASSERT_NE(begin->next, nullptr);
begin = begin->next;
void *ptr1 = libk::malloc(512);
EXPECT_NE(ptr1, nullptr) << *libk::begin;
EXPECT_EQ(reinterpret_cast<std::uintptr_t>(ptr1),
reinterpret_cast<std::uintptr_t>(libk::begin) + 2 * sizeof(libk::Chunk) + 1024);
EXPECT_EQ(begin->used, 1);
EXPECT_EQ(begin->size, 512);
ASSERT_NE(begin->next, nullptr);
}
TEST_F(TestAllocator, freeNullptr)
{
void *ptr0 = libk::malloc(1024);
EXPECT_NE(ptr0, nullptr) << *libk::begin;
void *ptr1 = libk::malloc(512);
EXPECT_NE(ptr1, nullptr) << *libk::begin;
libk::free(nullptr);
libk::Chunk *begin = libk::begin;
EXPECT_EQ(begin->used, 1);
EXPECT_NE(begin->next, nullptr);
begin = begin->next;
EXPECT_EQ(begin->used, 1);
EXPECT_NE(begin->next, nullptr);
begin = begin->next;
EXPECT_EQ(begin->used, 0);
EXPECT_EQ(begin->next, nullptr);
}
TEST_F(TestAllocator, free)
{
void *ptr0 = libk::malloc(1024);
EXPECT_NE(ptr0, nullptr) << *libk::begin;
void *ptr1 = libk::malloc(512);
EXPECT_NE(ptr1, nullptr) << *libk::begin;
libk::free(ptr0);
libk::Chunk *begin = libk::begin;
EXPECT_EQ(begin->used, 0) << ptr0 << ": ptr0" << std::endl << *libk::begin;
EXPECT_NE(begin->next, nullptr);
begin = begin->next;
EXPECT_EQ(begin->used, 1);
EXPECT_NE(begin->next, nullptr);
begin = begin->next;
EXPECT_EQ(begin->used, 0);
EXPECT_EQ(begin->next, nullptr);
libk::free(ptr1);
begin = libk::begin;
EXPECT_EQ(begin->used, 0) << ptr0 << ": ptr0" << std::endl << *libk::begin;
EXPECT_EQ(begin->next, nullptr);
}
|