C/C++ API Reference
Loading...
Searching...
No Matches
unordered.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
18#include "pw_allocator/bucket/base.h"
19#include "pw_containers/intrusive_forward_list.h"
20
21namespace pw::allocator {
22
24
32class UnorderedItem : public IntrusiveForwardList<UnorderedItem>::Item {};
33
41template <typename BlockType>
42class UnorderedBucket final
43 : public internal::
44 BucketBase<UnorderedBucket<BlockType>, BlockType, UnorderedItem> {
45 private:
46 using Base = internal::
47 BucketBase<UnorderedBucket<BlockType>, BlockType, UnorderedItem>;
48 friend Base;
49
50 public:
52
53 private:
55 void DoAdd(BlockType& block);
56
58 BlockType* DoRemoveAny();
59
61 const BlockType* DoFindLargest() const;
62
64 bool DoRemove(BlockType& block) {
65 return items_.remove(Base::GetItemFrom(block));
66 }
67
69 BlockType* DoRemoveCompatible(Layout layout);
70
72};
73
75
76// Template method implementations.
77
78template <typename BlockType>
79void UnorderedBucket<BlockType>::DoAdd(BlockType& block) {
80 auto* item = new (block.UsableSpace()) UnorderedItem();
81 items_.push_front(*item);
82}
83
84template <typename BlockType>
85BlockType* UnorderedBucket<BlockType>::DoRemoveAny() {
86 UnorderedItem& item = items_.front();
87 items_.pop_front();
88 return BlockType::FromUsableSpace(&item);
89}
90
91template <typename BlockType>
92const BlockType* UnorderedBucket<BlockType>::DoFindLargest() const {
93 auto iter = std::max_element(items_.begin(), items_.end(), Base::Compare);
94 return BlockType::FromUsableSpace(&(*iter));
95}
96
97template <typename BlockType>
98BlockType* UnorderedBucket<BlockType>::DoRemoveCompatible(Layout layout) {
99 auto prev = Base::FindPrevIf(
100 items_.before_begin(), items_.end(), Base::MakeCanAllocPredicate(layout));
101 auto* block = Base::GetBlockFromPrev(prev, items_.end());
102 if (block != nullptr) {
103 items_.erase_after(prev);
104 }
105 return block;
106}
107
108} // namespace pw::allocator
Definition: intrusive_forward_list.h:99
Definition: layout.h:64
Definition: unordered.h:44
Definition: unordered.h:32
void Clear()
Removes all blocks from this bucket.
Definition: base.h:118
static ItemType & GetItemFrom(BlockType &block)
Definition: base.h:169
SmallBlock BlockType
Default block type to use for tests.
Definition: size_report.h:32