• 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 "pw_allocator/size_report/size_report.h"
16 
17 #include "pw_allocator/layout.h"
18 #include "pw_bytes/alignment.h"
19 
20 namespace pw::allocator::size_report {
21 
GetBuffer()22 ByteSpan GetBuffer() {
23   static std::array<std::byte, 0x400> buffer;
24   return buffer;
25 };
26 
SetBaseline(uint32_t mask)27 int SetBaseline(uint32_t mask) {
28   bloat::BloatThisBinary();
29 
30   ByteSpan bytes = GetAlignedSubspan(GetBuffer(), 32);
31   PW_BLOAT_COND(!bytes.empty(), mask);
32 
33   Layout layout(64, 1);
34   PW_BLOAT_COND(layout.size() < bytes.size(), mask);
35 
36   return mask == bloat::kDefaultMask ? 0 : 1;
37 }
38 
MeasureAllocator(Allocator & allocator,uint32_t mask)39 int MeasureAllocator(Allocator& allocator, uint32_t mask) {
40   if (SetBaseline(mask) != 0) {
41     return 1;
42   }
43 
44   // Measure `Allocate`.
45   void* ptr = allocator.Allocate(Layout::Of<Foo>());
46   if (ptr == nullptr) {
47     return 1;
48   }
49 
50   // Measure `Reallocate`.
51   allocator.Resize(ptr, sizeof(Bar));
52 
53   // Measure `Reallocate`.
54   ptr = allocator.Reallocate(ptr, Layout::Of<Baz>());
55   if (ptr == nullptr) {
56     return 1;
57   }
58 
59   // Measure `Deallocate`.
60   allocator.Deallocate(ptr);
61 
62   // Measure `New`.
63   Foo* foo = allocator.template New<Foo>();
64   if (foo == nullptr) {
65     return 1;
66   }
67 
68   // Measure `Delete`.
69   allocator.Delete(foo);
70 
71   // Measure `MakeUnique`.
72   UniquePtr<Foo> unique_foo = allocator.template MakeUnique<Foo>();
73   unique_foo.Reset();
74 
75   return 0;
76 }
77 
MeasureBlockAllocator(BlockAllocator<BlockType> & allocator,uint32_t mask)78 int MeasureBlockAllocator(BlockAllocator<BlockType>& allocator, uint32_t mask) {
79   if (int rc = MeasureBlock<BlockType>(mask); rc != 0) {
80     return rc;
81   }
82   return MeasureAllocator(allocator, mask);
83 }
84 
85 }  // namespace pw::allocator::size_report
86