#include #include #include namespace libk { #include "linked_list_allocator.c" std::ostream & operator<<(std::ostream &os, const Chunk &b) { for (const Chunk *iter = &b; 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 "test_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(ptr0), reinterpret_cast(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(ptr1), reinterpret_cast(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); }