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