18#include "pw_allocator/block_allocator.h"
19#include "pw_allocator/bucket.h"
20#include "pw_assert/assert.h"
21#include "pw_status/try.h"
23namespace pw::allocator {
50template <
typename OffsetType = uintptr_t,
51 size_t kMinBucketChunkSize = 32,
52 size_t kNumBuckets = 5,
53 size_t kAlign = std::max(
alignof(OffsetType),
alignof(std::byte*))>
57 std::max(kAlign, alignof(std::byte*))> {
60 BlockAllocator<OffsetType, 0, std::max(kAlign,
alignof(std::byte*))>;
83 void Init(BlockType* begin, BlockType* end)
override {
85 internal::Bucket::Init(span(buckets_.data(), buckets_.size() - 1),
87 buckets_.back().Init();
97 BlockType* ChooseBlock(
Layout layout)
override {
101 for (
auto& bucket : buckets_) {
102 if (bucket.chunk_size() < layout.size()) {
105 void* chosen = bucket.RemoveIf([&layout](
const std::byte* chunk) {
106 const BlockType* block = BlockType::FromUsableSpace(chunk);
107 return block->CanAllocLast(layout).ok();
109 if (chosen ==
nullptr) {
112 BlockType* block = BlockType::FromUsableSpace(chosen);
113 BlockType* prev = block;
114 BlockType::AllocLast(block, layout).IgnoreError();
126 void ReserveBlock(BlockType* block)
override {
127 PW_ASSERT(!block->Used());
128 size_t inner_size = block->InnerSize();
129 if (inner_size <
sizeof(internal::Bucket::Chunk)) {
136 void RecycleBlock(BlockType* block)
override {
137 PW_ASSERT(!block->Used());
138 size_t inner_size = block->InnerSize();
139 if (inner_size <
sizeof(internal::Bucket::Chunk)) {
142 for (
auto& bucket : buckets_) {
143 if (inner_size <= bucket.chunk_size()) {
144 bucket.Add(block->UsableSpace());
150 std::array<internal::Bucket, kNumBuckets> buckets_;
Definition: block_allocator.h:79
void Init(ByteSpan region)
Definition: block_allocator.h:251
Range blocks() const
Returns a Range of blocks tracking the memory of this allocator.
Definition: block_allocator.h:237
Definition: bucket_block_allocator.h:57
void Init(BlockType *begin, BlockType *end) override
Definition: bucket_block_allocator.h:83
void Init(BlockType *begin)
Definition: bucket_block_allocator.h:80
constexpr BucketBlockAllocator()
Constexpr constructor. Callers must explicitly call Init.
Definition: bucket_block_allocator.h:64
void Init(ByteSpan region)
Definition: bucket_block_allocator.h:77
BucketBlockAllocator(ByteSpan region)
Definition: bucket_block_allocator.h:72