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#include <cstddef>
18
20
21namespace pw::containers {
22
24
38template <size_t kAlignment, size_t kSizeBytes>
39class Storage final {
40 public:
41 using value_type = std::byte;
42 using size_type = size_t;
43 using pointer = value_type*;
44 using const_pointer = const value_type*;
45
46 constexpr Storage() : buffer_{} {}
47
48 Storage(const Storage&) = delete;
49 Storage& operator=(const Storage&) = delete;
50
51 Storage(Storage&&) = delete;
52 Storage& operator=(Storage&&) = delete;
53
54 constexpr pointer data() { return buffer_.data(); }
55 constexpr const_pointer data() const { return buffer_.data(); }
56
58 constexpr size_type size() const { return buffer_.size(); }
59
60 [[nodiscard]] constexpr bool empty() const { return buffer_.empty(); }
61
62 constexpr void fill(std::byte value) {
63 pw::fill_n(buffer_.data(), buffer_.size(), value);
64 }
65
66 private:
67 alignas(kAlignment) std::array<std::byte, kSizeBytes> buffer_;
68};
69
75template <typename T, size_t kCount = 1>
76using StorageFor = Storage<alignof(T), sizeof(T) * kCount>;
77
79inline constexpr size_t kExternalStorage = static_cast<size_t>(-1);
80
85template <size_t kAlignment, size_t kSizeBytes>
87 protected:
88 constexpr StorageBase() = default;
89
90 Storage<kAlignment, kSizeBytes>& storage() { return storage_; }
91 const Storage<kAlignment, kSizeBytes>& storage() const { return storage_; }
92
93 private:
95};
96
99template <typename T, size_t kCount = 1>
100using StorageBaseFor = StorageBase<alignof(T), sizeof(T) * kCount>;
101
102} // namespace pw::containers
Definition: storage.h:86
Definition: storage.h:39
constexpr size_type size() const
The size of the storage in bytes.
Definition: storage.h:58
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:420
constexpr size_t kExternalStorage
Reserved capacity value for container specializations with external storage.
Definition: storage.h:79