1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_allocator/buddy_allocator.h"
16
17 #include <array>
18 #include <cstddef>
19
20 #include "pw_unit_test/framework.h"
21
22 namespace {
23
24 // Test fixtures.
25
26 using BuddyAllocator = ::pw::allocator::BuddyAllocator<>;
27 using ::pw::allocator::Layout;
28
29 class BuddyAllocatorTest : public ::testing::Test {
30 protected:
31 static constexpr size_t kBufferSize = 0x400;
32 std::array<std::byte, kBufferSize> buffer_;
33 };
34
35 // Unit tests.
36
TEST_F(BuddyAllocatorTest,ExplicitlyInit)37 TEST_F(BuddyAllocatorTest, ExplicitlyInit) {
38 BuddyAllocator allocator;
39 allocator.Init(buffer_);
40 }
41
TEST_F(BuddyAllocatorTest,AllocateSmall)42 TEST_F(BuddyAllocatorTest, AllocateSmall) {
43 BuddyAllocator allocator(buffer_);
44 void* ptr = allocator.Allocate(Layout(BuddyAllocator::kMinOuterSize / 2, 1));
45 ASSERT_NE(ptr, nullptr);
46 allocator.Deallocate(ptr);
47 }
48
TEST_F(BuddyAllocatorTest,AllocateAllBlocks)49 TEST_F(BuddyAllocatorTest, AllocateAllBlocks) {
50 BuddyAllocator allocator(buffer_);
51 pw::Vector<void*, kBufferSize / BuddyAllocator::kMinOuterSize> ptrs;
52 while (true) {
53 void* ptr = allocator.Allocate(Layout(1, 1));
54 if (ptr == nullptr) {
55 break;
56 }
57 ptrs.push_back(ptr);
58 }
59 while (!ptrs.empty()) {
60 allocator.Deallocate(ptrs.back());
61 ptrs.pop_back();
62 }
63 }
64
TEST_F(BuddyAllocatorTest,AllocateLarge)65 TEST_F(BuddyAllocatorTest, AllocateLarge) {
66 BuddyAllocator allocator(buffer_);
67 void* ptr = allocator.Allocate(Layout(48, 1));
68 ASSERT_NE(ptr, nullptr);
69 allocator.Deallocate(ptr);
70 }
71
TEST_F(BuddyAllocatorTest,AllocateExcessiveSize)72 TEST_F(BuddyAllocatorTest, AllocateExcessiveSize) {
73 BuddyAllocator allocator(buffer_);
74 void* ptr = allocator.Allocate(Layout(786, 1));
75 EXPECT_EQ(ptr, nullptr);
76 }
77
TEST_F(BuddyAllocatorTest,AllocateExcessiveAlignment)78 TEST_F(BuddyAllocatorTest, AllocateExcessiveAlignment) {
79 BuddyAllocator allocator(buffer_);
80 void* ptr = allocator.Allocate(Layout(48, 32));
81 EXPECT_EQ(ptr, nullptr);
82 }
83
84 } // namespace
85