Pigweed
Loading...
Searching...
No Matches
best_fit_block_allocator.h
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 "pw_allocator/block_allocator.h"
17
18namespace pw::allocator {
19
29template <typename OffsetType = uintptr_t,
30 size_t kPoisonInterval = 0,
31 size_t kAlign = alignof(OffsetType)>
34 public:
36 using BlockType = typename Base::BlockType;
37
39 constexpr BestFitBlockAllocator() : Base() {}
40
47 explicit BestFitBlockAllocator(ByteSpan region) : Base(region) {}
48
49 private:
51 BlockType* ChooseBlock(Layout layout) override {
52 // Search backwards for the smallest block that can hold this allocation.
53 BlockType* best = nullptr;
54 for (auto* block : Base::rblocks()) {
55 if (!block->CanAllocLast(layout).ok()) {
56 continue;
57 }
58 if (best == nullptr || block->OuterSize() < best->OuterSize()) {
59 best = block;
60 }
61 }
62 if (best != nullptr && BlockType::AllocLast(best, layout).ok()) {
63 return best;
64 }
65 return nullptr;
66 }
67};
68
69} // namespace pw::allocator
Definition: best_fit_block_allocator.h:33
constexpr BestFitBlockAllocator()
Constexpr constructor. Callers must explicitly call Init.
Definition: best_fit_block_allocator.h:39
BestFitBlockAllocator(ByteSpan region)
Definition: best_fit_block_allocator.h:47
Definition: block_allocator.h:79
Definition: block.h:108
Definition: layout.h:39