• 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 // 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   used_ = allocator_.GetAllocated();
39   if (prev <= threshold_ && threshold_ < used_) {
40     PW_LOG_INFO("more than %zu bytes allocated.", threshold_);
41   }
42   return ptr;
43 }
44 
DoDeallocate(void * ptr)45 void CustomAllocator::DoDeallocate(void* ptr) {
46   if (ptr == nullptr) {
47     return;
48   }
49   allocator_.Deallocate(ptr);
50   used_ = allocator_.GetAllocated();
51 }
52 
53 }  // namespace examples
54