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/chunk_pool.h"
16
17 #include <array>
18 #include <cstddef>
19 #include <cstdint>
20
21 #include "pw_allocator/testing.h"
22 #include "pw_unit_test/framework.h"
23
24 namespace {
25
26 // Test fixtures.
27
28 using ::pw::allocator::Layout;
29
30 struct U64 {
31 std::byte bytes[8];
32 };
33
34 // Unit tests.
35
TEST(ChunkPoolTest,Capabilities)36 TEST(ChunkPoolTest, Capabilities) {
37 std::array<std::byte, 256> buffer;
38 pw::allocator::ChunkPool pool(buffer, Layout::Of<U64>());
39 EXPECT_EQ(pool.capabilities(), pw::allocator::ChunkPool::kCapabilities);
40 }
41
TEST(ChunkPoolTest,AllocateDeallocate)42 TEST(ChunkPoolTest, AllocateDeallocate) {
43 std::array<std::byte, 256> buffer;
44 pw::allocator::ChunkPool pool(buffer, Layout::Of<U64>());
45
46 void* ptr = pool.Allocate();
47 ASSERT_NE(ptr, nullptr);
48 pool.Deallocate(ptr);
49 }
50
TEST(ChunkPoolTest,ExhaustTwice)51 TEST(ChunkPoolTest, ExhaustTwice) {
52 constexpr size_t kNumU64s = 32;
53 constexpr size_t kBufferSize = sizeof(U64) * kNumU64s;
54 std::array<std::byte, kBufferSize> buffer;
55 pw::allocator::ChunkPool pool(buffer, Layout::Of<U64>());
56
57 // Allocate everything.
58 std::array<void*, kNumU64s> ptrs;
59 for (auto& ptr : ptrs) {
60 ptr = pool.Allocate();
61 ASSERT_NE(ptr, nullptr);
62 }
63
64 // At this point, the pool is empty.
65 EXPECT_EQ(pool.Allocate(), nullptr);
66
67 // Now refill the pool, and show it can be emptied again.
68 for (auto& ptr : ptrs) {
69 pool.Deallocate(ptr);
70 ptr = nullptr;
71 }
72 for (auto& ptr : ptrs) {
73 ptr = pool.Allocate();
74 ASSERT_NE(ptr, nullptr);
75 }
76
77 // Release everything.
78 for (auto& ptr : ptrs) {
79 pool.Deallocate(ptr);
80 ptr = nullptr;
81 }
82 }
83
84 } // namespace
85