• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
15 #include "pw_allocator/bucket.h"
16 
17 #include <new>
18 
19 #include "pw_assert/check.h"
20 #include "pw_assert/internal/check_impl.h"
21 
22 namespace pw::allocator::internal {
23 
Bucket(size_t chunk_size)24 Bucket::Bucket(size_t chunk_size) : chunk_size_(chunk_size) {
25   PW_CHECK_UINT_GE(chunk_size_, sizeof(std::byte*));
26 }
27 
operator =(Bucket && other)28 Bucket& Bucket::operator=(Bucket&& other) {
29   chunks_ = std::exchange(other.chunks_, nullptr);
30   chunk_size_ =
31       std::exchange(other.chunk_size_, std::numeric_limits<size_t>::max());
32   return *this;
33 }
34 
Init(span<Bucket> buckets,size_t min_chunk_size)35 void Bucket::Init(span<Bucket> buckets, size_t min_chunk_size) {
36   size_t chunk_size = min_chunk_size;
37   for (auto& bucket : buckets) {
38     bucket = Bucket(chunk_size);
39     PW_CHECK_MUL(chunk_size, 2, &chunk_size);
40   }
41 }
42 
count() const43 size_t Bucket::count() const {
44   size_t n = 0;
45   Visit([&n](const std::byte*) { ++n; });
46   return n;
47 }
48 
Add(std::byte * ptr)49 void Bucket::Add(std::byte* ptr) {
50   std::byte** next = std::launder(reinterpret_cast<std::byte**>(ptr));
51   *next = chunks_;
52   chunks_ = ptr;
53 }
54 
Visit(const Function<void (const std::byte *)> & visitor) const55 void Bucket::Visit(const Function<void(const std::byte*)>& visitor) const {
56   std::byte** next = nullptr;
57   for (std::byte* chunk = chunks_; chunk != nullptr; chunk = *next) {
58     visitor(chunk);
59     next = std::launder(reinterpret_cast<std::byte**>(chunk));
60   }
61 }
62 
Remove()63 std::byte* Bucket::Remove() {
64   return RemoveIf([](void*) { return true; });
65 }
66 
RemoveIf(const Function<bool (void *)> & cond)67 std::byte* Bucket::RemoveIf(const Function<bool(void*)>& cond) {
68   std::byte** prev = &chunks_;
69   std::byte** next = nullptr;
70   for (std::byte* chunk = chunks_; chunk != nullptr; chunk = *next) {
71     next = std::launder(reinterpret_cast<std::byte**>(chunk));
72     if (cond(chunk)) {
73       *prev = *next;
74       *next = nullptr;
75       return chunk;
76     }
77     prev = next;
78   }
79   return nullptr;
80 }
81 
82 }  // namespace pw::allocator::internal
83