xref: /aosp_15_r20/external/pigweed/pw_allocator/examples/custom_allocator.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 // DOCSTAG: [pw_allocator-examples-custom_allocator]
16 #include "examples/custom_allocator.h"
17 
18 #include <cstdint>
19 
20 #include "pw_allocator/capability.h"
21 #include "pw_log/log.h"
22 #include "pw_result/result.h"
23 
24 namespace examples {
25 
CustomAllocator(Allocator & allocator,size_t threshold)26 CustomAllocator::CustomAllocator(Allocator& allocator, size_t threshold)
27     : Allocator(pw::allocator::Capabilities()),
28       allocator_(allocator),
29       threshold_(threshold) {}
30 
31 // Allocates, and reports if allocated memory exceeds its threshold.
DoAllocate(Layout layout)32 void* CustomAllocator::DoAllocate(Layout layout) {
33   void* ptr = allocator_.Allocate(layout);
34   if (ptr == nullptr) {
35     return nullptr;
36   }
37   size_t prev = used_;
38   pw::Result<Layout> allocated = GetAllocatedLayout(allocator_, ptr);
39   if (allocated.ok()) {
40     used_ += allocated->size();
41   }
42   if (prev <= threshold_ && threshold_ < used_) {
43     PW_LOG_INFO("more than %zu bytes allocated.", threshold_);
44   }
45   return ptr;
46 }
47 
DoDeallocate(void * ptr)48 void CustomAllocator::DoDeallocate(void* ptr) {
49   if (ptr == nullptr) {
50     return;
51   }
52   pw::Result<Layout> allocated = GetAllocatedLayout(allocator_, ptr);
53   if (allocated.ok()) {
54     used_ -= allocated->size();
55   }
56   allocator_.Deallocate(ptr);
57 }
58 
59 }  // namespace examples
60