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
19
20namespace pw::containers {
21
23
35template <size_t kAlignment, size_t kSizeBytes>
36class Storage {
37 public:
38 using value_type = std::byte;
39 using size_type = size_t;
40 using pointer = value_type*;
41 using const_pointer = const value_type*;
42
43 constexpr Storage() : buffer_{} {}
44
45 Storage(const Storage&) = delete;
46 Storage& operator=(const Storage&) = delete;
47
48 Storage(Storage&&) = delete;
49 Storage& operator=(Storage&&) = delete;
50
51 constexpr pointer data() { return buffer_.data(); }
52 constexpr const_pointer data() const { return buffer_.data(); }
53
55 constexpr size_type size() const { return buffer_.size(); }
56
57 [[nodiscard]] constexpr bool empty() const { return buffer_.empty(); }
58
59 constexpr void fill(std::byte value) {
60 pw::fill_n(buffer_.data(), buffer_.size(), value);
61 }
62
63 private:
64 alignas(kAlignment) std::array<std::byte, kSizeBytes> buffer_;
65};
66
72template <typename T, size_t kCount = 1>
73using StorageFor = Storage<alignof(T), sizeof(T) * kCount>;
74
76inline constexpr size_t kExternalStorage = static_cast<size_t>(-1);
77
79
80namespace internal {
81
82// Storage wrappers to be used as bases when implementing a container that
83// combines a non-owning container with its buffer. These types have to be the
84// first base so the storage outlives the container using it.
85template <typename T, size_t kCapacity>
87 StorageFor<T, kCapacity> storage_array;
88};
89
90} // namespace internal
91} // namespace pw::containers
Definition: storage.h:36
constexpr size_type size() const
The size of the storage in bytes.
Definition: storage.h:55
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
constexpr size_t kExternalStorage
Reserved capacity value for container specializations with external storage.
Definition: storage.h:76