C/C++ API Reference
Loading...
Searching...
No Matches
first_fit.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 <limits>
17
18#include "pw_allocator/block/detailed_block.h"
19#include "pw_allocator/block_allocator.h"
20#include "pw_allocator/bucket/sequenced.h"
21
22namespace pw::allocator {
23
25
27template <typename OffsetType>
29
40template <typename BlockType = FirstFitBlock<uintptr_t>>
41class FirstFitAllocator : public BlockAllocator<BlockType> {
42 public:
44
46 constexpr FirstFitAllocator() = default;
47
54
61 FirstFitAllocator(ByteSpan region, size_t threshold) {
62 Base::Init(region);
63 bucket_.set_threshold(threshold);
64 }
65
67 void set_threshold(size_t threshold) { bucket_.set_threshold(threshold); }
68
69 private:
71 size_t DoGetMaxAllocatable() override {
72 const BlockType* largest = bucket_.FindLargest();
73 return largest == nullptr ? 0 : largest->InnerSize();
74 }
75
78 BlockType* block = bucket_.RemoveCompatible(layout);
79 if (block == nullptr) {
80 return BlockResult<BlockType>(nullptr, Status::NotFound());
81 }
82 if (layout.size() < bucket_.threshold()) {
83 return BlockType::AllocLast(std::move(block), layout);
84 } else {
85 return BlockType::AllocFirst(std::move(block), layout);
86 }
87 }
88
90 void ReserveBlock(BlockType& block) override {
91 std::ignore = bucket_.Remove(block);
92 }
93
95 void RecycleBlock(BlockType& block) override {
96 std::ignore = bucket_.Add(block);
97 }
98
100};
101
103
104} // namespace pw::allocator
Definition: block_allocator.h:106
void Init(ByteSpan region)
Definition: block_allocator.h:310
Definition: result.h:116
Definition: detailed_block.h:88
Definition: first_fit.h:41
FirstFitAllocator(ByteSpan region)
Definition: first_fit.h:53
void ReserveBlock(BlockType &block) override
Definition: first_fit.h:90
constexpr FirstFitAllocator()=default
Constexpr constructor. Callers must explicitly call Init.
void set_threshold(size_t threshold)
Sets the threshold value for which requests are considered "large".
Definition: first_fit.h:67
size_t DoGetMaxAllocatable() override
Definition: first_fit.h:71
BlockResult< BlockType > ChooseBlock(Layout layout) override
Definition: first_fit.h:77
void RecycleBlock(BlockType &block) override
Definition: first_fit.h:95
FirstFitAllocator(ByteSpan region, size_t threshold)
Definition: first_fit.h:61
Definition: layout.h:58
Definition: sequenced.h:46