Pigweed
 
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
25template <typename OffsetType>
26using FirstFitBlock = DetailedBlock<OffsetType, SequencedItem>;
27
38template <typename BlockType = FirstFitBlock<uintptr_t>>
39class FirstFitAllocator : public BlockAllocator<BlockType> {
40 public:
42
44 constexpr FirstFitAllocator() = default;
45
51 FirstFitAllocator(ByteSpan region) { Base::Init(region); }
52
59 FirstFitAllocator(ByteSpan region, size_t threshold) {
60 Base::Init(region);
61 bucket_.set_threshold(threshold);
62 }
63
65 void set_threshold(size_t threshold) { bucket_.set_threshold(threshold); }
66
67 private:
70 BlockType* block = bucket_.RemoveCompatible(layout);
71 if (block == nullptr) {
72 return BlockResult<BlockType>(nullptr, Status::NotFound());
73 }
74 if (layout.size() < bucket_.threshold()) {
75 return BlockType::AllocLast(std::move(block), layout);
76 } else {
77 return BlockType::AllocFirst(std::move(block), layout);
78 }
79 }
80
82 void ReserveBlock(BlockType& block) override {
83 std::ignore = bucket_.Remove(block);
84 }
85
87 void RecycleBlock(BlockType& block) override {
88 std::ignore = bucket_.Add(block);
89 }
90
92};
93
94} // namespace pw::allocator
Definition: block_allocator.h:104
void Init(ByteSpan region)
Definition: block_allocator.h:281
Definition: result.h:114
Definition: first_fit.h:39
FirstFitAllocator(ByteSpan region)
Definition: first_fit.h:51
void ReserveBlock(BlockType &block) override
Definition: first_fit.h:82
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:65
BlockResult< BlockType > ChooseBlock(Layout layout) override
Definition: first_fit.h:69
void RecycleBlock(BlockType &block) override
Definition: first_fit.h:87
FirstFitAllocator(ByteSpan region, size_t threshold)
Definition: first_fit.h:59
Definition: layout.h:56
Definition: sequenced.h:44