userver: userver/utils/any_storage.hpp Source File
Loading...
Searching...
No Matches
any_storage.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/any_storage.hpp
4/// @brief @copybrief utils::AnyStorage
5
6#include <cstddef>
7#include <memory>
8#include <new>
9#include <stdexcept>
10#include <type_traits>
11#include <vector>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace utils {
16
17namespace any_storage::impl {
18
19using Offset = std::size_t;
20
21template <typename StorageTag>
22inline Offset data_offset{0};
23
24template <typename StorageTag>
25inline std::size_t count{0};
26
27template <typename StorageTag>
28Offset RegisterData(std::size_t size, std::size_t alignment) noexcept {
29 data_offset<StorageTag> += (alignment - (data_offset<StorageTag> % alignment)) % alignment;
30 Offset result = data_offset<StorageTag>;
31 data_offset<StorageTag> += size;
32
33 count<StorageTag> ++;
34 return result;
35}
36
37void AssertStaticRegistrationAllowed();
38
39template <typename T>
40void Delete(std::byte* data) noexcept {
41 reinterpret_cast<T*>(data)->~T();
42}
43
44} // namespace any_storage::impl
45
46template <typename StorageTag>
47class AnyStorage;
48
49template <typename StorageTag, typename Data>
50class AnyStorageDataTag final {
51public:
52 AnyStorageDataTag() noexcept
53 : number_(any_storage::impl::count<StorageTag>),
54 offset_(any_storage::impl::RegisterData<StorageTag>(sizeof(Data), alignof(Data))) {
55 static_assert(!std::is_reference_v<Data>);
56 static_assert(!std::is_const_v<Data>);
57 static_assert(
58 __STDCPP_DEFAULT_NEW_ALIGNMENT__ >= alignof(Data),
59 "Overaligned data members are not supported by AnyStorage"
60 );
61
62 any_storage::impl::AssertStaticRegistrationAllowed();
63 }
64
65private:
66 const std::size_t number_;
67 const any_storage::impl::Offset offset_;
68
69 friend class AnyStorage<StorageTag>;
70};
71
72/// @ingroup userver_universal userver_containers
73///
74/// @brief map-like heterogeneous data storage
75///
76/// ## Usage example
77/// @snippet utils/any_storage_test.cpp AnyStorage
78template <typename StorageTag>
79class AnyStorage final {
80public:
81 AnyStorage();
82
83 ~AnyStorage();
84
85 /// @returns Stored data.
86 template <typename Data>
87 const Data& Get(const AnyStorageDataTag<StorageTag, Data>& tag) const;
88
89 /// @returns Stored data.
90 /// @throws std::runtime_error if no data was stored
91 template <typename Data>
92 Data& Get(const AnyStorageDataTag<StorageTag, Data>& tag);
93
94 /// @brief Stores the data.
95 template <typename Data>
96 Data& Set(AnyStorageDataTag<StorageTag, Data> tag, Data data);
97
98 /// @brief Emplaces the data. The data is rewritten if
99 /// already stored.
100 template <typename Data, typename... Args>
101 Data& Emplace(const AnyStorageDataTag<StorageTag, Data>& tag, Args&&... args);
102
103 /// @returns Pointer to stored data or nullptr if
104 /// no data is found.
105 template <typename Data>
106 Data* GetOptional(const AnyStorageDataTag<StorageTag, Data>& tag) noexcept;
107
108 /// @returns Pointer to stored data or nullptr if
109 /// no data found.
110 template <typename Data>
111 const Data* GetOptional(const AnyStorageDataTag<StorageTag, Data>& tag) const noexcept;
112
113 /// @brief Erase data.
114 template <typename Data>
115 void Erase(const AnyStorageDataTag<StorageTag, Data>& tag);
116
117private:
118 struct AllocRecord {
119 void (*deleter)(std::byte*) noexcept;
120 std::size_t offset;
121 };
122
123 AllocRecord* GetRecords() noexcept;
124
125 static any_storage::impl::Offset CalcOffset() noexcept;
126
127 std::unique_ptr<std::byte[]> raw_data_;
128};
129
130template <typename StorageTag>
131any_storage::impl::Offset AnyStorage<StorageTag>::CalcOffset() noexcept {
132 const auto offset = any_storage::impl::data_offset<StorageTag>;
133 return ((offset + alignof(AllocRecord) - 1) / alignof(AllocRecord)) * alignof(AllocRecord);
134}
135
136template <typename StorageTag>
137AnyStorage<StorageTag>::AnyStorage()
138 : raw_data_(new std::byte[CalcOffset() + sizeof(AllocRecord) * any_storage::impl::count<StorageTag>]) {
139 static_assert(std::is_trivial_v<AllocRecord>);
140
141 auto records = GetRecords();
142 for (std::size_t i = 0; i < any_storage::impl::count<StorageTag>; i++) {
143 auto& record = records[i];
144 record.deleter = nullptr;
145 }
146}
147
148template <typename StorageTag>
149AnyStorage<StorageTag>::~AnyStorage() {
150 auto records = GetRecords();
151 for (std::size_t i = 0; i < any_storage::impl::count<StorageTag>; i++) {
152 auto& record = records[i];
153 if (record.deleter) record.deleter(&raw_data_[record.offset]);
154 }
155}
156
157template <typename StorageTag>
158template <typename Data>
159Data& AnyStorage<StorageTag>::Set(const AnyStorageDataTag<StorageTag, Data> tag, Data data) {
160 auto number = tag.number_;
161 if (!GetRecords()[number].deleter) return Emplace(tag, std::move(data));
162
163 auto offset = tag.offset_;
164 return *reinterpret_cast<Data*>(&raw_data_[offset]) = std::move(data);
165}
166
167template <typename StorageTag>
168template <typename Data, typename... Args>
169Data& AnyStorage<StorageTag>::Emplace(const AnyStorageDataTag<StorageTag, Data>& tag, Args&&... args) {
170 auto number = tag.number_;
171 auto& record = GetRecords()[number];
172 if (record.deleter) record.deleter(&raw_data_[tag.offset_]);
173
174 auto offset = tag.offset_;
175 auto ptr = new (&raw_data_[offset]) Data(std::forward<Args>(args)...);
176 record = {&any_storage::impl::Delete<Data>, offset};
177 return *ptr;
178}
179
180template <typename StorageTag>
181template <typename Data>
182Data& AnyStorage<StorageTag>::Get(const AnyStorageDataTag<StorageTag, Data>& tag) {
183 auto ptr = GetOptional(tag);
184 if (ptr) return *ptr;
185 throw std::runtime_error("No data");
186}
187
188template <typename StorageTag>
189template <typename Data>
190const Data& AnyStorage<StorageTag>::Get(const AnyStorageDataTag<StorageTag, Data>& tag) const {
191 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
192 return const_cast<AnyStorage<StorageTag>*>(this)->Get<Data>(tag);
193}
194
195template <typename StorageTag>
196template <typename Data>
197Data* AnyStorage<StorageTag>::GetOptional(const AnyStorageDataTag<StorageTag, Data>& tag) noexcept {
198 auto number = tag.number_;
199 auto offset = tag.offset_;
200 if (!GetRecords()[number].deleter) return nullptr;
201 return reinterpret_cast<Data*>(&raw_data_[offset]);
202}
203
204template <typename StorageTag>
205template <typename Data>
206const Data* AnyStorage<StorageTag>::GetOptional(const AnyStorageDataTag<StorageTag, Data>& tag) const noexcept {
207 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
208 return const_cast<AnyStorage*>(this)->GetOptional<Data>(tag);
209}
210
211template <typename StorageTag>
212typename AnyStorage<StorageTag>::AllocRecord* AnyStorage<StorageTag>::GetRecords() noexcept {
213 return reinterpret_cast<AllocRecord*>(&raw_data_[CalcOffset()]);
214}
215
216} // namespace utils
217
218USERVER_NAMESPACE_END