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