Debian Codegraph @

src/core/lib/gprpp/table.h

raw
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_GPRPP_TABLE_H
16 #define GRPC_CORE_LIB_GPRPP_TABLE_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <stddef.h>
21
22 #include <initializer_list>
23 #include <new>
24 #include <utility>
25
26 #include "absl/meta/type_traits.h"
27 #include "absl/utility/utility.h"
28
29 #include "src/core/lib/gprpp/bitset.h"
30
31 namespace grpc_core {
32
33 // Meta-programming detail types to aid in building up a Table
34 namespace table_detail {
35
36 // A tuple-like type that contains manually constructed elements.
37 template <typename... Ts>
38 struct Elements;
39
40 template <typename T, typename... Ts>
41 struct Elements<T, Ts...> : Elements<Ts...> {
42 union U {
43 U() {}
44 ~U() {}
45 GPR_NO_UNIQUE_ADDRESS T x;
46 };
47 U u;
48 };
49 template <>
50 struct Elements<> {};
51
52 // Element accessor for Elements<>
53 // Provides a static method f that returns a pointer to the value of element I
54 // for Elements<Ts...>
55 template <size_t I, typename... Ts>
56 struct GetElem;
57
58 template <typename T, typename... Ts>
59 struct GetElem<0, T, Ts...> {
60 static T* f(Elements<T, Ts...>* e) { return &e->u.x; }
61 static const T* f(const Elements<T, Ts...>* e) { return &e->u.x; }
62 };
63
64 template <size_t I, typename T, typename... Ts>
65 struct GetElem<I, T, Ts...> {
66 static auto f(Elements<T, Ts...>* e)
67 -> decltype(GetElem<I - 1, Ts...>::f(e)) {
68 return GetElem<I - 1, Ts...>::f(e);
69 }
70 static auto f(const Elements<T, Ts...>* e)
71 -> decltype(GetElem<I - 1, Ts...>::f(e)) {
72 return GetElem<I - 1, Ts...>::f(e);
73 }
74 };
75
76 // CountIncludedStruct is the backing for the CountIncluded function below.
77 // Sets a member constant N to the number of times Needle is in Haystack.
78 template <typename Needle, typename... Haystack>
79 struct CountIncludedStruct;
80
81 template <typename Needle, typename Straw, typename... RestOfHaystack>
82 struct CountIncludedStruct<Needle, Straw, RestOfHaystack...> {
83 static constexpr size_t N =
84 static_cast<size_t>(std::is_same<Needle, Straw>::value) +
85 CountIncludedStruct<Needle, RestOfHaystack...>::N;
86 };
87 template <typename Needle>
88 struct CountIncludedStruct<Needle> {
89 static constexpr size_t N = 0;
90 };
91 // Returns the number of times Needle is in Haystack.
92 template <typename Needle, typename... Haystack>
93 constexpr size_t CountIncluded() {
94 return CountIncludedStruct<Needle, Haystack...>::N;
95 }
96
97 // IndexOfStruct is the backing for IndexOf below.
98 // Set a member constant N to the index of Needle in Haystack.
99 // Ignored should be void always, and is used for enable_if_t.
100 template <typename Ignored, typename Needle, typename... Haystack>
101 struct IndexOfStruct;
102
103 template <typename Needle, typename Straw, typename... RestOfHaystack>
104 struct IndexOfStruct<absl::enable_if_t<std::is_same<Needle, Straw>::value>,
105 Needle, Straw, RestOfHaystack...> {
106 // The first element is the one we're looking for. Done.
107 static constexpr size_t N = 0;
108 };
109 template <typename Needle, typename Straw, typename... RestOfHaystack>
110 struct IndexOfStruct<absl::enable_if_t<!std::is_same<Needle, Straw>::value>,
111 Needle, Straw, RestOfHaystack...> {
112 // The first element is not the one we're looking for, recurse looking at the
113 // tail, and sum the number of recursions.
114 static constexpr size_t N =
115 1 + IndexOfStruct<void, Needle, RestOfHaystack...>::N;
116 };
117 // Return the index of Needle in Haystack.
118 // Guarded by CountIncluded to ensure that the return type is unambiguous.
119 // If you got here from a compiler error using Table, it's likely that you've
120 // used the type-based accessor/mutators, but the type you're using is repeated
121 // more than once in the Table type arguments. Consider either using the indexed
122 // accessor/mutator variants, or eliminating the ambiguity in type resolution.
123 template <typename Needle, typename... Haystack>
124 constexpr absl::enable_if_t<CountIncluded<Needle, Haystack...>() == 1, size_t>
125 IndexOf() {
126 return IndexOfStruct<void, Needle, Haystack...>::N;
127 }
128
129 // TypeIndexStruct is the backing for TypeIndex below.
130 // Sets member type Type to the type at index I in Ts.
131 // Implemented as a simple type recursion.
132 template <size_t I, typename... Ts>
133 struct TypeIndexStruct;
134
135 template <typename T, typename... Ts>
136 struct TypeIndexStruct<0, T, Ts...> {
137 using Type = T;
138 };
139 template <size_t I, typename T, typename... Ts>
140 struct TypeIndexStruct<I, T, Ts...> : TypeIndexStruct<I - 1, Ts...> {};
141 // TypeIndex is the type at index I in Ts.
142 template <size_t I, typename... Ts>
143 using TypeIndex = typename TypeIndexStruct<I, Ts...>::Type;
144
145 // Helper to call the destructor of p if p is non-null.
146 template <typename T>
147 void DestructIfNotNull(T* p) {
148 if (p) p->~T();
149 }
150
151 // Helper function... just ignore the initializer list passed into it.
152 // Allows doing 'statements' via parameter pack expansion in C++11 - given
153 // template <typename... Ts>:
154 // do_these_things({(foo<Ts>(), 1)});
155 // will execute foo<T>() for each T in Ts.
156 // In this example we also leverage the comma operator to make the resultant
157 // type of each statement be a consistant int so that C++ type deduction works
158 // as we'd like (note that in the expression (a, 1) in C++, the 'result' of the
159 // expression is the value after the right-most ',' -- in this case 1, with a
160 // executed as a side effect.
161 template <typename T>
162 void do_these_things(std::initializer_list<T>) {}
163
164 } // namespace table_detail
165
166 // A Table<Ts> is much like a tuple<optional<Ts>...> - a set of values that are
167 // optionally present. Table efficiently packs the presence bits for size, and
168 // provides a slightly more convenient interface.
169 template <typename... Ts>
170 class Table {
171 // Helper - TypeIndex<I> is the type at index I in Ts
172 template <size_t I>
173 using TypeIndex = table_detail::TypeIndex<I, Ts...>;
174
175 public:
176 // Construct a table with no values set.
177 Table() = default;
178 // Destruct - forwards to the Destruct member with an integer sequence so we
179 // can destruct field-wise.
180 ~Table() { Destruct(absl::make_index_sequence<sizeof...(Ts)>()); }
181
182 // Copy another table
183 Table(const Table& rhs) {
184 // Since we know all fields are clear initially, pass false for or_clear.
185 Copy<false>(absl::make_index_sequence<sizeof...(Ts)>(), rhs);
186 }
187
188 // Copy another table
189 Table& operator=(const Table& rhs) {
190 // Since we may not be all clear, pass true for or_clear to have Copy()
191 // clear newly emptied fields.
192 Copy<true>(absl::make_index_sequence<sizeof...(Ts)>(), rhs);
193 return *this;
194 }
195
196 // Move from another table
197 Table(Table&& rhs) noexcept {
198 // Since we know all fields are clear initially, pass false for or_clear.
199 Move<false>(absl::make_index_sequence<sizeof...(Ts)>(),
200 std::forward<Table>(rhs));
201 }
202
203 // Move from another table
204 Table& operator=(Table&& rhs) noexcept {
205 // Since we may not be all clear, pass true for or_clear to have Move()
206 // clear newly emptied fields.
207 Move<true>(absl::make_index_sequence<sizeof...(Ts)>(),
208 std::forward<Table>(rhs));
209 return *this;
210 }
211
212 // Check if this table has a value for type T.
213 // Only available if there exists only one T in Ts.
214 template <typename T>
215 bool has() const {
216 return has<index_of<T>()>();
217 }
218
219 // Check if this table has index I.
220 template <size_t I>
221 absl::enable_if_t<(I < sizeof...(Ts)), bool> has() const {
222 return present_bits_.is_set(I);
223 }
224
225 // Return the value for type T, or nullptr if it is un-set.
226 // Only available if there exists only one T in Ts.
227 template <typename T>
228 T* get() {
229 return get<index_of<T>()>();
230 }
231
232 // Return the value for type T, or nullptr if it is un-set.
233 // Only available if there exists only one T in Ts.
234 template <typename T>
235 const T* get() const {
236 return get<index_of<T>()>();
237 }
238
239 // Return the value for index I, or nullptr if it is un-set.
240 template <size_t I>
241 TypeIndex<I>* get() {
242 if (has<I>()) return element_ptr<I>();
243 return nullptr;
244 }
245
246 // Return the value for index I, or nullptr if it is un-set.
247 template <size_t I>
248 const TypeIndex<I>* get() const {
249 if (has<I>()) return element_ptr<I>();
250 return nullptr;
251 }
252
253 // Return the value for type T, default constructing it if it is un-set.
254 template <typename T>
255 T* get_or_create() {
256 return get_or_create<index_of<T>()>();
257 }
258
259 // Return the value for index I, default constructing it if it is un-set.
260 template <size_t I>
261 TypeIndex<I>* get_or_create() {
262 auto* p = element_ptr<I>();
263 if (!set_present<I>(true)) {
264 new (p) TypeIndex<I>();
265 }
266 return element_ptr<I>();
267 }
268
269 // Set the value for type T - using Args as construction arguments.
270 template <typename T, typename... Args>
271 T* set(Args&&... args) {
272 return set<index_of<T>()>(std::forward<Args>(args)...);
273 }
274
275 // Set the value for index I - using Args as construction arguments.
276 template <size_t I, typename... Args>
277 TypeIndex<I>* set(Args&&... args) {
278 auto* p = element_ptr<I>();
279 if (set_present<I>(true)) {
280 TypeIndex<I> replacement(std::forward<Args>(args)...);
281 *p = std::move(replacement);
282 } else {
283 new (p) TypeIndex<I>(std::forward<Args>(args)...);
284 }
285 return p;
286 }
287
288 template <size_t I>
289 TypeIndex<I>* set(TypeIndex<I>&& value) {
290 auto* p = element_ptr<I>();
291 if (set_present<I>(true)) {
292 *p = std::forward<TypeIndex<I>>(value);
293 } else {
294 new (p) TypeIndex<I>(std::forward<TypeIndex<I>>(value));
295 }
296 return p;
297 }
298
299 // Clear the value for type T, leaving it un-set.
300 template <typename T>
301 void clear() {
302 clear<index_of<T>()>();
303 }
304
305 // Clear the value for index I, leaving it un-set.
306 template <size_t I>
307 void clear() {
308 if (set_present<I>(false)) {
309 using T = TypeIndex<I>;
310 element_ptr<I>()->~T();
311 }
312 }
313
314 // Iterate through each set field in the table
315 template <typename F>
316 void ForEach(F f) const {
317 ForEachImpl(std::move(f), absl::make_index_sequence<sizeof...(Ts)>());
318 }
319
320 // Iterate through each set field in the table if it exists in Vs, in the
321 // order of Vs.
322 template <typename F, typename... Vs>
323 void ForEachIn(F f) const {
324 ForEachImpl(std::move(f),
325 absl::index_sequence<table_detail::IndexOf<Vs, Ts...>()...>());
326 }
327
328 // Count the number of set fields in the table
329 size_t count() const { return present_bits_.count(); }
330
331 // Check if the table is completely empty
332 bool empty() const { return present_bits_.none(); }
333
334 // Clear all elements in the table.
335 void ClearAll() { ClearAllImpl(absl::make_index_sequence<sizeof...(Ts)>()); }
336
337 private:
338 // Bit field for which elements of the table are set (true) or un-set (false,
339 // the default) -- one bit for each type in Ts.
340 using PresentBits = BitSet<sizeof...(Ts)>;
341 // The tuple-like backing structure for Table.
342 using Elements = table_detail::Elements<Ts...>;
343 // Extractor from Elements
344 template <size_t I>
345 using GetElem = table_detail::GetElem<I, Ts...>;
346
347 // Given a T, return the unambiguous index of it within Ts.
348 template <typename T>
349 static constexpr size_t index_of() {
350 return table_detail::IndexOf<T, Ts...>();
351 }
352
353 // Given an index, return a point to the (maybe uninitialized!) data value at
354 // index I.
355 template <size_t I>
356 TypeIndex<I>* element_ptr() {
357 return GetElem<I>::f(&elements_);
358 }
359
360 // Given an index, return a point to the (maybe uninitialized!) data value at
361 // index I.
362 template <size_t I>
363 const TypeIndex<I>* element_ptr() const {
364 return GetElem<I>::f(&elements_);
365 }
366
367 // Set the present bit to value (if true - value is present/set, if false,
368 // value is un-set). Returns the old value so that calling code can note
369 // transition edges.
370 template <size_t I>
371 bool set_present(bool value) {
372 bool out = present_bits_.is_set(I);
373 present_bits_.set(I, value);
374 return out;
375 }
376
377 // Set the value of index I to the value held in rhs index I if it is set.
378 // If it is unset, if or_clear is true, then clear our value, otherwise do
379 // nothing.
380 template <bool or_clear, size_t I>
381 void CopyIf(const Table& rhs) {
382 if (auto* p = rhs.get<I>()) {
383 set<I>(*p);
384 } else if (or_clear) {
385 clear<I>();
386 }
387 }
388
389 // Set the value of index I to the value moved from rhs index I if it was set.
390 // If it is unset, if or_clear is true, then clear our value, otherwise do
391 // nothing.
392 template <bool or_clear, size_t I>
393 void MoveIf(Table&& rhs) {
394 if (auto* p = rhs.get<I>()) {
395 set<I>(std::move(*p));
396 } else if (or_clear) {
397 clear<I>();
398 }
399 }
400
401 // Call (*f)(value) if that value is in the table.
402 template <size_t I, typename F>
403 void CallIf(F* f) const {
404 if (auto* p = get<I>()) {
405 (*f)(*p);
406 }
407 }
408
409 // For each field (element I=0, 1, ...) if that field is present, call its
410 // destructor.
411 template <size_t... I>
412 void Destruct(absl::index_sequence<I...>) {
413 table_detail::do_these_things<int>(
414 {(table_detail::DestructIfNotNull(get<I>()), 1)...});
415 }
416
417 // For each field (element I=0, 1, ...) copy that field into this table -
418 // or_clear as per CopyIf().
419 template <bool or_clear, size_t... I>
420 void Copy(absl::index_sequence<I...>, const Table& rhs) {
421 table_detail::do_these_things<int>({(CopyIf<or_clear, I>(rhs), 1)...});
422 }
423
424 // For each field (element I=0, 1, ...) move that field into this table -
425 // or_clear as per MoveIf().
426 template <bool or_clear, size_t... I>
427 void Move(absl::index_sequence<I...>, Table&& rhs) {
428 table_detail::do_these_things<int>(
429 {(MoveIf<or_clear, I>(std::forward<Table>(rhs)), 1)...});
430 }
431
432 // For each field (element I=0, 1, ...) if that field is present, call f.
433 template <typename F, size_t... I>
434 void ForEachImpl(F f, absl::index_sequence<I...>) const {
435 table_detail::do_these_things<int>({(CallIf<I>(&f), 1)...});
436 }
437
438 template <size_t... I>
439 void ClearAllImpl(absl::index_sequence<I...>) {
440 table_detail::do_these_things<int>({(clear<I>(), 1)...});
441 }
442
443 // Bit field indicating which elements are set.
444 GPR_NO_UNIQUE_ADDRESS PresentBits present_bits_;
445 // The memory to store the elements themselves.
446 GPR_NO_UNIQUE_ADDRESS Elements elements_;
447 };
448
449 } // namespace grpc_core
450
451 #endif // GRPC_CORE_LIB_GPRPP_TABLE_H