1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
20 #include "pw_allocator/block.h"
21 #include "pw_allocator/freelist.h"
23 namespace pw::allocator {
28 friend class FreeListHeapBuffer;
31 size_t bytes_allocated;
32 size_t cumulative_allocated;
33 size_t cumulative_freed;
34 size_t total_allocate_calls;
35 size_t total_free_calls;
37 FreeListHeap(std::span<std::byte> region, FreeList& freelist);
39 void* Allocate(size_t size);
41 void* Realloc(void* ptr, size_t size);
42 void* Calloc(size_t num, size_t size);
47 std::span<std::byte> BlockToSpan(Block* block) {
48 return std::span<std::byte>(block->UsableSpace(), block->InnerSize());
51 void InvalidFreeCrash();
53 std::span<std::byte> region_;
55 HeapStats heap_stats_;
58 template <size_t N = 6>
59 class FreeListHeapBuffer {
61 static constexpr std::array<size_t, N> defaultBuckets{
62 16, 32, 64, 128, 256, 512};
64 FreeListHeapBuffer(std::span<std::byte> region)
65 : freelist_(defaultBuckets), heap_(region, freelist_) {}
67 void* Allocate(size_t size) { return heap_.Allocate(size); }
68 void Free(void* ptr) { heap_.Free(ptr); }
69 void* Realloc(void* ptr, size_t size) { return heap_.Realloc(ptr, size); }
70 void* Calloc(size_t num, size_t size) { return heap_.Calloc(num, size); }
72 const FreeListHeap::HeapStats& heap_stats() const {
73 return heap_.heap_stats_;
76 void LogHeapStats() { heap_.LogHeapStats(); }
79 FreeListBuffer<N> freelist_;
83 } // namespace pw::allocator