C/C++ API Reference
Loading...
Searching...
No Matches
typed_pool.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/chunk_pool.h"
19#include "pw_allocator/hardening.h"
20#include "pw_bytes/span.h"
21
22namespace pw::allocator {
23
25
35template <typename T>
36class TypedPool : public ChunkPool {
37 public:
39 static constexpr size_t SizeNeeded(size_t num_objects) {
40 size_t needed = std::max(sizeof(T), ChunkPool::kMinSize);
41 Hardening::Multiply(needed, num_objects);
42 return needed;
43 }
44
46 static constexpr size_t AlignmentNeeded() {
47 return std::max(alignof(T), ChunkPool::kMinAlignment);
48 }
49
51 template <size_t kNumObjects>
52 struct Buffer {
53 static_assert(kNumObjects != 0);
54 alignas(
55 AlignmentNeeded()) std::array<std::byte, SizeNeeded(kNumObjects)> data;
56 };
57
69 template <size_t kNumObjects>
71 : ChunkPool(buffer.data, Layout::Of<T>()) {}
72
85 TypedPool(ByteSpan region) : ChunkPool(region, Layout::Of<T>()) {}
86
93 template <int&... kExplicitGuard, typename... Args>
94 T* New(Args&&... args) {
95 void* ptr = Allocate();
96 return ptr != nullptr ? new (ptr) T(std::forward<Args>(args)...) : nullptr;
97 }
98
105 template <int&... kExplicitGuard, typename... Args>
106 UniquePtr<T> MakeUnique(Args&&... args) {
107 return UniquePtr<T>(New(std::forward<Args>(args)...), *this);
108 }
109};
110
112
113} // namespace pw::allocator
Definition: chunk_pool.h:32
Definition: layout.h:58
void * Allocate()
Definition: pool.h:47
Definition: typed_pool.h:36
TypedPool(Buffer< kNumObjects > &buffer)
Definition: typed_pool.h:70
T * New(Args &&... args)
Definition: typed_pool.h:94
TypedPool(ByteSpan region)
Definition: typed_pool.h:85
static constexpr size_t SizeNeeded(size_t num_objects)
Returns the amount of memory needed to allocate num_objects.
Definition: typed_pool.h:39
UniquePtr< T > MakeUnique(Args &&... args)
Definition: typed_pool.h:106
static constexpr size_t AlignmentNeeded()
Returns the optimal alignment for the backing memory region.
Definition: typed_pool.h:46
Provides aligned storage for kNumObjects of type T.
Definition: typed_pool.h:52