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 #pragma once 15 16 #include <cstdint> 17 18 #include "pw_allocator/capability.h" 19 #include "pw_allocator/layout.h" 20 #include "pw_allocator/pool.h" 21 #include "pw_bytes/span.h" 22 #include "pw_status/status.h" 23 24 namespace pw::allocator { 25 26 /// Implementation of ``Pool`` that uses a list of free chunks. 27 /// 28 /// The first ``sizeof(void*)`` bytes of each free chunk is used to store a 29 /// pointer to the next free chunk, or null for the last free chunk. 30 class ChunkPool : public Pool { 31 public: 32 static constexpr Capabilities kCapabilities = 33 kImplementsGetRequestedLayout | kImplementsGetUsableLayout | 34 kImplementsGetAllocatedLayout | kImplementsGetCapacity | 35 kImplementsRecognizes; 36 static constexpr size_t kMinSize = sizeof(void*); 37 static constexpr size_t kMinAlignment = alignof(void*); 38 39 /// Construct a `Pool` that allocates from a region of memory. 40 /// 41 /// @param region The memory to allocate from. Must be large enough to 42 /// allocate at least one chunk with the given layout. 43 /// @param layout The size and alignment of the memory to be returned 44 /// from this pool. 45 ChunkPool(ByteSpan region, const Layout& layout); 46 47 private: 48 /// @copydoc Pool::Allocate 49 void* DoAllocate() override; 50 51 /// @copydoc Deallocator::Deallocate 52 void DoDeallocate(void* ptr) override; 53 54 /// @copydoc Deallocator::GetInfo 55 Result<Layout> DoGetInfo(InfoType info_type, const void* ptr) const override; 56 57 const Layout allocated_layout_; 58 uintptr_t start_; 59 uintptr_t end_; 60 std::byte* next_; 61 }; 62 63 } // namespace pw::allocator 64