• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 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 #pragma once
16 
17 #include <cstddef>
18 
19 #include "pw_allocator/block.h"
20 #include "pw_allocator/freelist.h"
21 #include "pw_span/span.h"
22 
23 namespace pw::allocator {
24 
25 class FreeListHeap {
26  public:
27   using BlockType = Block<>;
28 
29   template <size_t kNumBuckets>
30   friend class FreeListHeapBuffer;
31   struct HeapStats {
32     size_t total_bytes;
33     size_t bytes_allocated;
34     size_t cumulative_allocated;
35     size_t cumulative_freed;
36     size_t total_allocate_calls;
37     size_t total_free_calls;
38   };
39   FreeListHeap(span<std::byte> region, FreeList& freelist);
40 
41   void* Allocate(size_t size);
42   void Free(void* ptr);
43   void* Realloc(void* ptr, size_t size);
44   void* Calloc(size_t num, size_t size);
45 
46   void LogHeapStats();
47 
48  private:
BlockToSpan(BlockType * block)49   span<std::byte> BlockToSpan(BlockType* block) {
50     return span<std::byte>(block->UsableSpace(), block->InnerSize());
51   }
52 
53   void InvalidFreeCrash();
54 
55   span<std::byte> region_;
56   FreeList& freelist_;
57   HeapStats heap_stats_;
58 };
59 
60 template <size_t kNumBuckets = 6>
61 class FreeListHeapBuffer {
62  public:
63   static constexpr std::array<size_t, kNumBuckets> defaultBuckets{
64       16, 32, 64, 128, 256, 512};
65 
FreeListHeapBuffer(span<std::byte> region)66   FreeListHeapBuffer(span<std::byte> region)
67       : freelist_(defaultBuckets), heap_(region, freelist_) {}
68 
Allocate(size_t size)69   void* Allocate(size_t size) { return heap_.Allocate(size); }
Free(void * ptr)70   void Free(void* ptr) { heap_.Free(ptr); }
Realloc(void * ptr,size_t size)71   void* Realloc(void* ptr, size_t size) { return heap_.Realloc(ptr, size); }
Calloc(size_t num,size_t size)72   void* Calloc(size_t num, size_t size) { return heap_.Calloc(num, size); }
73 
heap_stats()74   const FreeListHeap::HeapStats& heap_stats() const {
75     return heap_.heap_stats_;
76   }
77 
LogHeapStats()78   void LogHeapStats() { heap_.LogHeapStats(); }
79 
80  private:
81   FreeListBuffer<kNumBuckets> freelist_;
82   FreeListHeap heap_;
83 };
84 
85 }  // namespace pw::allocator
86