C/C++ API Reference
Loading...
Searching...
No Matches
storage.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 <array>
17
18#include "pw_allocator/unique_ptr.h"
20
21namespace pw::containers {
22
24
36template <size_t kAlignment, size_t kSizeBytes>
37class Storage {
38 public:
39 using value_type = std::byte;
40 using size_type = size_t;
41 using pointer = value_type*;
42 using const_pointer = const value_type*;
43
44 constexpr Storage() : buffer_{} {}
45
46 Storage(const Storage&) = delete;
47 Storage& operator=(const Storage&) = delete;
48
49 Storage(Storage&&) = delete;
50 Storage& operator=(Storage&&) = delete;
51
52 constexpr pointer data() { return buffer_.data(); }
53 constexpr const_pointer data() const { return buffer_.data(); }
54
56 constexpr size_type size() const { return buffer_.size(); }
57
58 [[nodiscard]] constexpr bool empty() const { return buffer_.empty(); }
59
60 constexpr void fill(std::byte value) {
61 pw::fill_n(buffer_.data(), buffer_.size(), value);
62 }
63
64 private:
65 alignas(kAlignment) std::array<std::byte, kSizeBytes> buffer_;
66};
67
73template <typename T, size_t kCount = 1>
74using StorageFor = Storage<alignof(T), sizeof(T) * kCount>;
75
78inline constexpr size_t kAllocatedStorage = static_cast<size_t>(-1);
79
81
82namespace internal {
83
84// Storage wrappers to be used as bases when implementing a container that
85// combines a non-owning container with its buffer. These types have to be the
86// first base so the storage outlives the container using it.
87template <typename T, size_t kCapacity>
89 StorageFor<T, kCapacity> storage_array;
90};
91
93 UniquePtr<std::byte[]> storage_unique_ptr;
94};
95
96} // namespace internal
97} // namespace pw::containers
Definition: unique_ptr.h:43
Definition: storage.h:37
constexpr size_type size() const
The size of the storage in bytes.
Definition: storage.h:56
constexpr size_t kAllocatedStorage
Definition: storage.h:78
constexpr It fill_n(It begin, Size count, const T &value)
constexpr backport of <algorithm>'s std::fill_n for C++17.
Definition: algorithm.h:413