Pigweed
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/allocator.h"
19#include "pw_allocator/chunk_pool.h"
20#include "pw_bytes/span.h"
21#include "pw_result/result.h"
22
23namespace pw::allocator {
24
34template <typename T>
35class TypedPool : public ChunkPool {
36 public:
38 static constexpr size_t SizeNeeded(size_t num_objects) {
39 size_t needed = std::max(sizeof(T), ChunkPool::kMinSize);
40 PW_ASSERT(!PW_MUL_OVERFLOW(needed, num_objects, &needed));
41 return needed;
42 }
43
45 static constexpr size_t AlignmentNeeded() {
46 return std::max(alignof(T), ChunkPool::kMinAlignment);
47 }
48
50 template <size_t kNumObjects>
51 struct Buffer {
52 static_assert(kNumObjects != 0);
53 alignas(
54 AlignmentNeeded()) std::array<std::byte, SizeNeeded(kNumObjects)> data;
55 };
56
68 template <size_t kNumObjects>
70 : ChunkPool(buffer.data, Layout::Of<T>()) {}
71
84 TypedPool(ByteSpan region) : ChunkPool(region, Layout::Of<T>()) {}
85
92 template <int&... ExplicitGuard, typename... Args>
93 T* New(Args&&... args) {
94 void* ptr = Allocate();
95 return ptr != nullptr ? new (ptr) T(std::forward<Args>(args)...) : nullptr;
96 }
97
104 template <int&... ExplicitGuard, typename... Args>
105 UniquePtr<T> MakeUnique(Args&&... args) {
106 return Deallocator::WrapUnique<T>(New(std::forward<Args>(args)...));
107 }
108};
109
110} // namespace pw::allocator
Definition: unique_ptr.h:47
Definition: chunk_pool.h:30
Definition: layout.h:39
void * Allocate()
Definition: pool.h:44
Definition: typed_pool.h:35
TypedPool(Buffer< kNumObjects > &buffer)
Definition: typed_pool.h:69
T * New(Args &&... args)
Definition: typed_pool.h:93
TypedPool(ByteSpan region)
Definition: typed_pool.h:84
static constexpr size_t SizeNeeded(size_t num_objects)
Returns the amount of memory needed to allocate num_objects.
Definition: typed_pool.h:38
UniquePtr< T > MakeUnique(Args &&... args)
Definition: typed_pool.h:105
static constexpr size_t AlignmentNeeded()
Returns the optimal alignment for the backing memory region.
Definition: typed_pool.h:45
#define PW_MUL_OVERFLOW(a, b, out)
Definition: compiler.h:261
Provides aligned storage for kNumObjects of type T.
Definition: typed_pool.h:51