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 #pragma once 15 16 #include <cstddef> 17 18 #include "pw_allocator/bucket_allocator.h" 19 #include "pw_assert/assert.h" 20 #include "pw_bytes/span.h" 21 #include "pw_preprocessor/compiler.h" 22 23 namespace pw::allocator { 24 25 /// Legacy interface to BucketAllocator. 26 /// 27 /// This interface is deprecated, and is only maintained for compatibility 28 /// reasons. New projects should use ``BucketAllocator``. 29 template <size_t kNumBuckets = 6> 30 class FreeListHeapBuffer { 31 public: FreeListHeapBuffer(ByteSpan region)32 explicit FreeListHeapBuffer(ByteSpan region) : allocator_(region) {} 33 Allocate(size_t size)34 void* Allocate(size_t size) { return allocator_.Allocate(Layout(size)); } 35 Free(void * ptr)36 void Free(void* ptr) { allocator_.Deallocate(ptr); } 37 Realloc(void * ptr,size_t size)38 void* Realloc(void* ptr, size_t size) { 39 return allocator_.Reallocate(ptr, Layout(size)); 40 } 41 Calloc(size_t num,size_t size)42 void* Calloc(size_t num, size_t size) { 43 PW_ASSERT(!PW_MUL_OVERFLOW(num, size, &size)); 44 void* ptr = allocator_.Allocate(Layout(size)); 45 if (ptr == nullptr) { 46 return nullptr; 47 } 48 std::memset(ptr, 0, size); 49 return ptr; 50 } 51 52 private: 53 using BlockType = BucketBlock<>; 54 static constexpr size_t kMinChunkSize = 16; 55 BucketAllocator<BlockType, kMinChunkSize, kNumBuckets> allocator_; 56 }; 57 58 } // namespace pw::allocator 59