C/C++ API Reference
Loading...
Searching...
No Matches
simple_allocator.h
1// Copyright 2025 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 <optional>
18
19#include "pw_bytes/span.h"
20#include "pw_multibuf/v1_adapter/allocator.h"
21#include "pw_multibuf/v1_adapter/internal/chunk_allocator.h"
22#include "pw_multibuf/v1_adapter/multibuf.h"
23#include "pw_sync/lock_annotations.h"
24#include "pw_sync/mutex.h"
25
26namespace pw::multibuf::v1_adapter {
27
36 public:
38 Allocator& metadata_allocator,
39 size_t alignment = 1)
40 : chunk_allocator_(region, metadata_allocator, alignment) {}
41
50 [[nodiscard]] bool TryReserveRegions(size_t num_regions)
51 PW_LOCKS_EXCLUDED(mutex_);
52
53 private:
55 class SimpleChunkAllocator : public internal::ChunkAllocator {
56 public:
57 SimpleChunkAllocator(ByteSpan region,
58 Allocator& metadata_allocator,
59 size_t alignment);
60
61 ~SimpleChunkAllocator() override;
62
67 [[nodiscard]] bool Init();
68
71 size_t CountChunks(size_t desired_size);
72
74 [[nodiscard]] bool TryReserveRegions(size_t num_regions);
75
76 private:
77 using iterator = DynamicVector<Region>::iterator;
78
80 Region* AllocateRegion(size_t min_size, size_t desired_size) override;
81
83 size_t TryDeallocateRegion(void* ptr) override;
84
87 std::tuple<iterator, iterator> Split(iterator iter, size_t offset);
88
91 iterator Merge(iterator left, iterator right);
92
93 size_t available_;
94
97 DynamicVector<Region> subregions_;
98 };
99
101 std::optional<MultiBuf> DoAllocate(size_t min_size,
102 size_t desired_size,
103 bool contiguous) override
104 PW_LOCKS_EXCLUDED(mutex_);
105
107 std::optional<size_t> DoGetBackingCapacity() override
108 PW_LOCKS_EXCLUDED(mutex_);
109
110 pw::sync::Mutex mutex_;
111
112 SimpleChunkAllocator chunk_allocator_ PW_GUARDED_BY(mutex_);
113};
114
116
117} // namespace pw::multibuf::v1_adapter
Definition: allocator.h:45
Definition: dynamic_vector.h:53
Definition: ptr_iterator.h:142
Definition: simple_allocator.h:35
std::optional< MultiBuf > DoAllocate(size_t min_size, size_t desired_size, bool contiguous) override
std::optional< size_t > DoGetBackingCapacity() override
bool TryReserveRegions(size_t num_regions)
#define PW_GUARDED_BY(x)
Definition: lock_annotations.h:60
#define PW_LOCKS_EXCLUDED(...)
Definition: lock_annotations.h:176
The Pigweed namespace.
Definition: alignment.h:27