Pigweed
 
Loading...
Searching...
No Matches
worst_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 <cstddef>
17#include <limits>
18
19#include "pw_allocator/block/detailed_block.h"
20#include "pw_allocator/block_allocator.h"
21#include "pw_allocator/bucket/fast_sorted.h"
22#include "pw_allocator/bucket/sorted.h"
23#include "pw_allocator/config.h"
24
25namespace pw::allocator {
26
28template <typename OffsetType>
29using WorstFitBlock = DetailedBlock<OffsetType, GenericFastSortedItem>;
30
40template <typename BlockType = WorstFitBlock<uintptr_t>>
41class WorstFitAllocator : public BlockAllocator<BlockType> {
42 public:
44
46 constexpr WorstFitAllocator() = default;
47
53 WorstFitAllocator(ByteSpan region) { Base::Init(region); }
54
55 private:
58 BlockType* block = large_bucket_.RemoveCompatible(layout);
59 if (block != nullptr) {
60 return BlockType::AllocFirst(std::move(block), layout);
61 }
62 block = small_bucket_.RemoveCompatible(layout);
63 if (block != nullptr) {
64 return BlockType::AllocFirst(std::move(block), layout);
65 }
66 return BlockResult<BlockType>(nullptr, Status::NotFound());
67 }
68
70 void ReserveBlock(BlockType& block) override {
71 // The small bucket is slower; skip it if we can.
72 if (!large_bucket_.Remove(block)) {
73 std::ignore = small_bucket_.Remove(block);
74 }
75 }
76
78 void RecycleBlock(BlockType& block) override {
79 if (block.InnerSize() <= sizeof(SortedItem)) {
80 std::ignore = small_bucket_.Add(block);
81 } else {
82 std::ignore = large_bucket_.Add(block);
83 }
84 }
85
88};
89
90} // namespace pw::allocator
Definition: block_allocator.h:104
void Init(ByteSpan region)
Definition: block_allocator.h:281
Definition: result.h:114
Definition: layout.h:56
Definition: fast_sorted.h:142
Definition: sorted.h:127
Definition: sorted.h:30
Definition: worst_fit.h:41
constexpr WorstFitAllocator()=default
Constexpr constructor. Callers must explicitly call Init.
WorstFitAllocator(ByteSpan region)
Definition: worst_fit.h:53
BlockResult< BlockType > ChooseBlock(Layout layout) override
Definition: worst_fit.h:57
void ReserveBlock(BlockType &block) override
Definition: worst_fit.h:70
void RecycleBlock(BlockType &block) override
Definition: worst_fit.h:78