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
42 static constexpr size_t AlignmentNeeded() {
43 return std::max(alignof(T), ChunkPool::kMinAlignment);
44 }
45
47 template <size_t kNumObjects>
48 struct Buffer {
49 static_assert(kNumObjects != 0);
50 alignas(
51 AlignmentNeeded()) std::array<std::byte, SizeNeeded(kNumObjects)> data;
52 };
53
65 template <size_t kNumObjects>
67 : ChunkPool(buffer.data, Layout::Of<T>()) {}
68
81 TypedPool(ByteSpan region) : ChunkPool(region, Layout::Of<T>()) {}
82
89 template <int&... kExplicitGuard, typename... Args>
90 T* New(Args&&... args);
91
98 template <int&... kExplicitGuard, typename... Args>
99 UniquePtr<T> MakeUnique(Args&&... args) {
100 return UniquePtr<T>(New(std::forward<Args>(args)...), *this);
101 }
102};
103
105
106// Template method implementations.
107
108template <typename T>
109constexpr size_t TypedPool<T>::SizeNeeded(size_t num_objects) {
110 size_t needed = std::max(sizeof(T), ChunkPool::kMinSize);
111 Hardening::Multiply(needed, num_objects);
112 return needed;
113}
114
115template <typename T>
116template <int&... kExplicitGuard, typename... Args>
117T* TypedPool<T>::New(Args&&... args) {
118 void* ptr = Allocate();
119 return ptr != nullptr ? new (ptr) T(std::forward<Args>(args)...) : nullptr;
120}
121
122} // namespace pw::allocator
Definition: unique_ptr.h:44
Definition: chunk_pool.h:32
Definition: layout.h:64
Definition: typed_pool.h:36
TypedPool(Buffer< kNumObjects > &buffer)
Definition: typed_pool.h:66
T * New(Args &&... args)
Definition: typed_pool.h:117
TypedPool(ByteSpan region)
Definition: typed_pool.h:81
static constexpr size_t SizeNeeded(size_t num_objects)
Returns the amount of memory needed to allocate num_objects.
Definition: typed_pool.h:109
UniquePtr< T > MakeUnique(Args &&... args)
Definition: typed_pool.h:99
static constexpr size_t AlignmentNeeded()
Returns the optimal alignment for the backing memory region.
Definition: typed_pool.h:42
Provides aligned storage for kNumObjects of type T.
Definition: typed_pool.h:48