• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <string_view>
18 
19 #include "examples/named_u32.h"
20 #include "pw_allocator/allocator.h"
21 #include "pw_allocator/block_allocator.h"
22 #include "pw_unit_test/framework.h"
23 
24 namespace examples {
25 
26 // The "real" `PW_PLACE_IN_SECTION` can be found in pw_preprocessor/compiler.h.
27 // For the purposes of keeping this example simple and free of linker-scripts,
28 // the macro is replaced with a no-op version.
29 #ifdef PW_PLACE_IN_SECTION
30 #undef PW_PLACE_IN_SECTION
31 #endif
32 #define PW_PLACE_IN_SECTION(section)
33 
34 // DOCSTAG: [pw_allocator-examples-linker_sections-injection]
35 class NamedU32Factory {
36  public:
NamedU32Factory(pw::Allocator & allocator)37   explicit NamedU32Factory(pw::Allocator& allocator) : allocator_(allocator) {}
38 
MakeNamedU32(std::string_view name,uint32_t value)39   auto MakeNamedU32(std::string_view name, uint32_t value) {
40     return allocator_.MakeUnique<NamedU32>(name, value);
41   }
42 
43  private:
44   pw::Allocator& allocator_;
45 };
46 // DOCSTAG: [pw_allocator-examples-linker_sections-injection]
47 
48 // DOCSTAG: [pw_allocator-examples-linker_sections-placement]
49 // Set up an object that allocates from SRAM memory.
50 PW_PLACE_IN_SECTION(".sram") std::array<std::byte, 0x1000> sram_buffer;
51 pw::allocator::FirstFitBlockAllocator<uint16_t> sram_allocator(sram_buffer);
52 NamedU32Factory sram_factory(sram_allocator);
53 
54 // Set up an object that allocates from PSRAM memory.
55 PW_PLACE_IN_SECTION(".psram") std::array<std::byte, 0x2000> psram_buffer;
56 pw::allocator::WorstFitBlockAllocator<uint32_t> psram_allocator(psram_buffer);
57 NamedU32Factory psram_factory(psram_allocator);
58 // DOCSTAG: [pw_allocator-examples-linker_sections-placement]
59 
60 }  // namespace examples
61 
62 namespace pw::allocator {
63 
TEST(LinkerSectionExample,MakeObjects)64 TEST(LinkerSectionExample, MakeObjects) {
65   auto result1 = examples::sram_factory.MakeNamedU32("1", 1);
66   EXPECT_NE(result1, nullptr);
67 
68   auto result2 = examples::psram_factory.MakeNamedU32("2", 2);
69   EXPECT_NE(result2, nullptr);
70 }
71 
72 }  // namespace pw::allocator
73