Pigweed
Loading...
Searching...
No Matches
bucket.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_function/function.h"
20#include "pw_span/span.h"
21
22namespace pw::allocator::internal {
23
26class Bucket final {
27 public:
30 struct Chunk {
31 private:
32 friend class Bucket;
33
34 static Chunk* FromBytes(std::byte* ptr) {
35 return std::launder(reinterpret_cast<Chunk*>(ptr));
36 }
37
38 const std::byte* AsBytes() const {
39 return std::launder(reinterpret_cast<const std::byte*>(this));
40 }
41
42 std::byte* AsBytes() {
43 return std::launder(reinterpret_cast<std::byte*>(this));
44 }
45
46 Chunk* prev;
47 Chunk* next;
48 };
49
52
57 explicit Bucket(size_t chunk_size);
58
59 Bucket(const Bucket& other) = delete;
60 Bucket& operator=(const Bucket& other) = delete;
61
62 Bucket(Bucket&& other) { *this = std::move(other); }
63 Bucket& operator=(Bucket&& other);
64
65 ~Bucket() = default;
66
67 void Init(size_t chunk_size = std::numeric_limits<size_t>::max());
68
70 static void Init(span<Bucket> buckets, size_t min_chunk_size);
71
72 size_t chunk_size() const { return chunk_size_; }
73
74 bool empty() const { return sentinel_.next == &sentinel_; }
75
79 size_t count() const;
80
84 void Add(std::byte* ptr);
85
87 void Visit(const Function<void(const std::byte*)>& visitor) const;
88
92 std::byte* Remove();
93
101 std::byte* RemoveIf(const Function<bool(const std::byte*)>& cond);
102
107 static std::byte* Remove(std::byte* ptr);
108
109 private:
114 static std::byte* Remove(Chunk* chunk);
115
118 Chunk sentinel_;
119
121 size_t chunk_size_;
122};
123
124} // namespace pw::allocator::internal
Definition: bucket.h:26
Bucket()
Constructs a bucket with an unbounded chunk size.
std::byte * RemoveIf(const Function< bool(const std::byte *)> &cond)
void Visit(const Function< void(const std::byte *)> &visitor) const
Applies the given function to each chunk in the bucket.
static std::byte * Remove(std::byte *ptr)
static void Init(span< Bucket > buckets, size_t min_chunk_size)
Creates a list of buckets, with each twice as large as the one before it.
void Add(std::byte *ptr)
fit::function_impl< inline_target_size, !function_internal::config::kEnableDynamicAllocation, FunctionType, Allocator > Function
Definition: function.h:63