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/block_allocator.h"
16
17 #include <array>
18 #include <cstdint>
19
20 #include "examples/named_u32.h"
21 #include "pw_unit_test/framework.h"
22
23 namespace examples {
24
25 std::array<std::byte, 0x1000> buffer;
26
27 // DOCSTAG: [pw_allocator-examples-block_allocator-poison]
28 // Poisons every third deallocation.
29 pw::allocator::LastFitBlockAllocator<uint16_t, 3> allocator(buffer);
30 // DOCSTAG: [pw_allocator-examples-block_allocator-poison]
31
32 // DOCSTAG: [pw_allocator-examples-block_allocator-layout_of]
33 template <typename T, typename... Args>
my_new(Args...args)34 T* my_new(Args... args) {
35 void* ptr = allocator.Allocate(pw::allocator::Layout::Of<T>());
36 return ptr == nullptr ? nullptr : new (ptr) T(std::forward<Args>(args)...);
37 }
38 // DOCSTAG: [pw_allocator-examples-block_allocator-layout_of]
39
40 template <typename T>
my_delete(T * t)41 void my_delete(T* t) {
42 if (t != nullptr) {
43 std::destroy_at(t);
44 allocator.Deallocate(t);
45 }
46 }
47
48 // DOCSTAG: [pw_allocator-examples-block_allocator-malloc_free]
my_malloc(size_t size)49 void* my_malloc(size_t size) {
50 return allocator.Allocate(
51 pw::allocator::Layout(size, alignof(std::max_align_t)));
52 }
53
my_free(void * ptr)54 void my_free(void* ptr) { allocator.Deallocate(ptr); }
55 // DOCSTAG: [pw_allocator-examples-block_allocator-malloc_free]
56
57 } // namespace examples
58
59 namespace {
60
TEST(BlockAllocatorExample,NewDelete)61 TEST(BlockAllocatorExample, NewDelete) {
62 auto* named_u32 = examples::my_new<examples::NamedU32>("test", 111);
63 ASSERT_NE(named_u32, nullptr);
64 EXPECT_STREQ(named_u32->name().data(), "test");
65 EXPECT_EQ(named_u32->value(), 111U);
66 examples::my_delete(named_u32);
67 }
68
TEST(BlockAllocatorExample,MallocFree)69 TEST(BlockAllocatorExample, MallocFree) {
70 void* ptr = examples::my_malloc(sizeof(examples::NamedU32));
71 ASSERT_NE(ptr, nullptr);
72 examples::my_free(ptr);
73 }
74
75 } // namespace
76