Debian Codegraph @

mlspp/lib/bytes/include/tls/tls_syntax.h

raw symbols SCIP
1 #pragma once
2
3 #include <algorithm>
4 #include <array>
5 #include <cstdint>
6 #include <limits>
7 #include <map>
8 #include <optional>
9 #include <stdexcept>
10 #include <vector>
11
12 #include <tls/compat.h>
13
14 namespace mlspp::tls {
15
16 // For indicating no min or max in vector definitions
17 const size_t none = std::numeric_limits<size_t>::max();
18
19 class WriteError : public std::invalid_argument
20 {
21 public:
22 using parent = std::invalid_argument;
23 using parent::parent;
24 };
25
26 class ReadError : public std::invalid_argument
27 {
28 public:
29 using parent = std::invalid_argument;
30 using parent::parent;
31 };
32
33 ///
34 /// Declarations of Streams and Traits
35 ///
36
37 class ostream
38 {
39 public:
40 static const size_t none = std::numeric_limits<size_t>::max();
41
42 void write_raw(const std::vector<uint8_t>& bytes);
43
44 const std::vector<uint8_t>& bytes() const { return _buffer; }
45 size_t size() const { return _buffer.size(); }
46 bool empty() const { return _buffer.empty(); }
47
48 private:
49 std::vector<uint8_t> _buffer;
50 ostream& write_uint(uint64_t value, int length);
51
52 friend ostream& operator<<(ostream& out, bool data);
53 friend ostream& operator<<(ostream& out, uint8_t data);
54 friend ostream& operator<<(ostream& out, uint16_t data);
55 friend ostream& operator<<(ostream& out, uint32_t data);
56 friend ostream& operator<<(ostream& out, uint64_t data);
57
58 template<typename T>
59 friend ostream& operator<<(ostream& out, const std::vector<T>& data);
60
61 friend struct varint;
62 };
63
64 class istream
65 {
66 public:
67 istream(const std::vector<uint8_t>& data)
68 : _buffer(data)
69 {
70 // So that we can use the constant-time pop_back
71 std::reverse(_buffer.begin(), _buffer.end());
72 }
73
74 size_t size() const { return _buffer.size(); }
75 bool empty() const { return _buffer.empty(); }
76
77 std::vector<uint8_t> bytes()
78 {
79 auto bytes = _buffer;
80 std::reverse(bytes.begin(), bytes.end());
81 return bytes;
82 }
83
84 private:
85 istream() {}
86 std::vector<uint8_t> _buffer;
87 uint8_t next();
88
89 template<typename T>
90 istream& read_uint(T& data, size_t length)
91 {
92 uint64_t value = 0;
93 for (size_t i = 0; i < length; i += 1) {
94 value = (value << unsigned(8)) + next();
95 }
96 data = static_cast<T>(value);
97 return *this;
98 }
99
100 friend istream& operator>>(istream& in, bool& data);
101 friend istream& operator>>(istream& in, uint8_t& data);
102 friend istream& operator>>(istream& in, uint16_t& data);
103 friend istream& operator>>(istream& in, uint32_t& data);
104 friend istream& operator>>(istream& in, uint64_t& data);
105
106 template<typename T>
107 friend istream& operator>>(istream& in, std::vector<T>& data);
108
109 friend struct varint;
110 };
111
112 // Traits must have static encode and decode methods, of the following form:
113 //
114 // static ostream& encode(ostream& str, const T& val);
115 // static istream& decode(istream& str, T& val);
116 //
117 // Trait types will never be constructed; only these static methods are used.
118 // The value arguments to encode and decode can be as strict or as loose as
119 // desired.
120 //
121 // Ultimately, all interesting encoding should be done through traits.
122 //
123 // * vectors
124 // * variants
125 // * varints
126
127 struct pass
128 {
129 template<typename T>
130 static ostream& encode(ostream& str, const T& val);
131
132 template<typename T>
133 static istream& decode(istream& str, T& val);
134 };
135
136 template<typename Ts>
137 struct variant
138 {
139 template<typename... Tp>
140 static inline Ts type(const var::variant<Tp...>& data);
141
142 template<typename... Tp>
143 static ostream& encode(ostream& str, const var::variant<Tp...>& data);
144
145 template<size_t I = 0, typename Te, typename... Tp>
146 static inline typename std::enable_if<I == sizeof...(Tp), void>::type
147 read_variant(istream&, Te, var::variant<Tp...>&);
148
149 template<size_t I = 0, typename Te, typename... Tp>
150 static inline typename std::enable_if <
151 I<sizeof...(Tp), void>::type read_variant(istream& str,
152 Te target_type,
153 var::variant<Tp...>& v);
154
155 template<typename... Tp>
156 static istream& decode(istream& str, var::variant<Tp...>& data);
157 };
158
159 struct varint
160 {
161 static ostream& encode(ostream& str, const uint64_t& val);
162 static istream& decode(istream& str, uint64_t& val);
163 };
164
165 ///
166 /// Writer implementations
167 ///
168
169 // Primitive writers defined in .cpp file
170
171 // Array writer
172 template<typename T, size_t N>
173 ostream&
174 operator<<(ostream& out, const std::array<T, N>& data)
175 {
176 for (const auto& item : data) {
177 out << item;
178 }
179 return out;
180 }
181
182 // Optional writer
183 template<typename T>
184 ostream&
185 operator<<(ostream& out, const std::optional<T>& opt)
186 {
187 if (!opt) {
188 return out << uint8_t(0);
189 }
190
191 return out << uint8_t(1) << opt::get(opt);
192 }
193
194 // Enum writer
195 template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0>
196 ostream&
197 operator<<(ostream& str, const T& val)
198 {
199 auto u = static_cast<std::underlying_type_t<T>>(val);
200 return str << u;
201 }
202
203 // Vector writer
204 template<typename T>
205 ostream&
206 operator<<(ostream& str, const std::vector<T>& vec)
207 {
208 // Pre-encode contents
209 ostream temp;
210 for (const auto& item : vec) {
211 temp << item;
212 }
213
214 // Write the encoded length, then the pre-encoded data
215 varint::encode(str, temp._buffer.size());
216 str.write_raw(temp.bytes());
217
218 return str;
219 }
220
221 ///
222 /// Reader implementations
223 ///
224
225 // Primitive type readers defined in .cpp file
226
227 // Array reader
228 template<typename T, size_t N>
229 istream&
230 operator>>(istream& in, std::array<T, N>& data)
231 {
232 for (auto& item : data) {
233 in >> item;
234 }
235 return in;
236 }
237
238 // Optional reader
239 template<typename T>
240 istream&
241 operator>>(istream& in, std::optional<T>& opt)
242 {
243 uint8_t present = 0;
244 in >> present;
245
246 switch (present) {
247 case 0:
248 opt.reset();
249 return in;
250
251 case 1:
252 opt.emplace();
253 return in >> opt::get(opt);
254
255 default:
256 throw std::invalid_argument("Malformed optional");
257 }
258 }
259
260 // Enum reader
261 // XXX(rlb): It would be nice if this could enforce that the values are valid,
262 // but C++ doesn't seem to have that ability. When used as a tag for variants,
263 // the variant reader will enforce, at least.
264 template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0>
265 istream&
266 operator>>(istream& str, T& val)
267 {
268 std::underlying_type_t<T> u;
269 str >> u;
270 val = static_cast<T>(u);
271 return str;
272 }
273
274 // Vector reader
275 template<typename T>
276 istream&
277 operator>>(istream& str, std::vector<T>& vec)
278 {
279 // Read the encoded data size
280 auto size = uint64_t(0);
281 varint::decode(str, size);
282 if (size > str._buffer.size()) {
283 throw ReadError("Vector is longer than remaining data");
284 }
285
286 // Read the elements of the vector
287 // NB: Remember that we store the vector in reverse order
288 // NB: This requires that T be default-constructible
289 istream r;
290 r._buffer =
291 std::vector<uint8_t>{ str._buffer.end() - size, str._buffer.end() };
292
293 vec.clear();
294 while (r._buffer.size() > 0) {
295 vec.emplace_back();
296 r >> vec.back();
297 }
298
299 // Truncate the primary buffer
300 str._buffer.erase(str._buffer.end() - size, str._buffer.end());
301
302 return str;
303 }
304
305 // Abbreviations
306 template<typename T>
307 std::vector<uint8_t>
308 marshal(const T& value)
309 {
310 ostream w;
311 w << value;
312 return w.bytes();
313 }
314
315 template<typename T>
316 void
317 unmarshal(const std::vector<uint8_t>& data, T& value)
318 {
319 istream r(data);
320 r >> value;
321 }
322
323 template<typename T, typename... Tp>
324 T
325 get(const std::vector<uint8_t>& data, Tp... args)
326 {
327 T value(args...);
328 unmarshal(data, value);
329 return value;
330 }
331
332 // Use this macro to define struct serialization with minimal boilerplate
333 #define TLS_SERIALIZABLE(...) \
334 static const bool _tls_serializable = true; \
335 auto _tls_fields_r() \
336 { \
337 return std::forward_as_tuple(__VA_ARGS__); \
338 } \
339 auto _tls_fields_w() const \
340 { \
341 return std::forward_as_tuple(__VA_ARGS__); \
342 }
343
344 // If your struct contains nontrivial members (e.g., vectors), use this to
345 // define traits for them.
346 #define TLS_TRAITS(...) \
347 static const bool _tls_has_traits = true; \
348 using _tls_traits = std::tuple<__VA_ARGS__>;
349
350 template<typename T>
351 struct is_serializable
352 {
353 template<typename U>
354 static std::true_type test(decltype(U::_tls_serializable));
355
356 template<typename U>
357 static std::false_type test(...);
358
359 static const bool value = decltype(test<T>(true))::value;
360 };
361
362 template<typename T>
363 struct has_traits
364 {
365 template<typename U>
366 static std::true_type test(decltype(U::_tls_has_traits));
367
368 template<typename U>
369 static std::false_type test(...);
370
371 static const bool value = decltype(test<T>(true))::value;
372 };
373
374 ///
375 /// Trait implementations
376 ///
377
378 // Pass-through (normal encoding/decoding)
379 template<typename T>
380 ostream&
381 pass::encode(ostream& str, const T& val)
382 {
383 return str << val;
384 }
385
386 template<typename T>
387 istream&
388 pass::decode(istream& str, T& val)
389 {
390 return str >> val;
391 }
392
393 // Variant encoding
394 template<typename Ts, typename Tv>
395 constexpr Ts
396 variant_map();
397
398 #define TLS_VARIANT_MAP(EnumType, MappedType, enum_value) \
399 template<> \
400 constexpr EnumType variant_map<EnumType, MappedType>() \
401 { \
402 return EnumType::enum_value; \
403 }
404
405 template<typename Ts>
406 template<typename... Tp>
407 inline Ts
408 variant<Ts>::type(const var::variant<Tp...>& data)
409 {
410 const auto get_type = [](const auto& v) {
411 return variant_map<Ts, std::decay_t<decltype(v)>>();
412 };
413 return var::visit(get_type, data);
414 }
415
416 template<typename Ts>
417 template<typename... Tp>
418 ostream&
419 variant<Ts>::encode(ostream& str, const var::variant<Tp...>& data)
420 {
421 const auto write_variant = [&str](auto&& v) {
422 using Tv = std::decay_t<decltype(v)>;
423 str << variant_map<Ts, Tv>() << v;
424 };
425 var::visit(write_variant, data);
426 return str;
427 }
428
429 template<typename Ts>
430 template<size_t I, typename Te, typename... Tp>
431 inline typename std::enable_if<I == sizeof...(Tp), void>::type
432 variant<Ts>::read_variant(istream&, Te, var::variant<Tp...>&)
433 {
434 throw ReadError("Invalid variant type label");
435 }
436
437 template<typename Ts>
438 template<size_t I, typename Te, typename... Tp>
439 inline
440 typename std::enable_if < I<sizeof...(Tp), void>::type
441 variant<Ts>::read_variant(istream& str,
442 Te target_type,
443 var::variant<Tp...>& v)
444 {
445 using Tc = var::variant_alternative_t<I, var::variant<Tp...>>;
446 if (variant_map<Ts, Tc>() == target_type) {
447 str >> v.template emplace<I>();
448 return;
449 }
450
451 read_variant<I + 1>(str, target_type, v);
452 }
453
454 template<typename Ts>
455 template<typename... Tp>
456 istream&
457 variant<Ts>::decode(istream& str, var::variant<Tp...>& data)
458 {
459 Ts target_type;
460 str >> target_type;
461 read_variant(str, target_type, data);
462 return str;
463 }
464
465 // Struct writer without traits (enabled by macro)
466 template<size_t I = 0, typename... Tp>
467 inline typename std::enable_if<I == sizeof...(Tp), void>::type
468 write_tuple(ostream&, const std::tuple<Tp...>&)
469 {
470 }
471
472 template<size_t I = 0, typename... Tp>
473 inline typename std::enable_if <
474 I<sizeof...(Tp), void>::type
475 write_tuple(ostream& str, const std::tuple<Tp...>& t)
476 {
477 str << std::get<I>(t);
478 write_tuple<I + 1, Tp...>(str, t);
479 }
480
481 template<typename T>
482 inline
483 typename std::enable_if<is_serializable<T>::value && !has_traits<T>::value,
484 ostream&>::type
485 operator<<(ostream& str, const T& obj)
486 {
487 write_tuple(str, obj._tls_fields_w());
488 return str;
489 }
490
491 // Struct writer with traits (enabled by macro)
492 template<typename Tr, size_t I = 0, typename... Tp>
493 inline typename std::enable_if<I == sizeof...(Tp), void>::type
494 write_tuple_traits(ostream&, const std::tuple<Tp...>&)
495 {
496 }
497
498 template<typename Tr, size_t I = 0, typename... Tp>
499 inline typename std::enable_if <
500 I<sizeof...(Tp), void>::type
501 write_tuple_traits(ostream& str, const std::tuple<Tp...>& t)
502 {
503 std::tuple_element_t<I, Tr>::encode(str, std::get<I>(t));
504 write_tuple_traits<Tr, I + 1, Tp...>(str, t);
505 }
506
507 template<typename T>
508 inline
509 typename std::enable_if<is_serializable<T>::value && has_traits<T>::value,
510 ostream&>::type
511 operator<<(ostream& str, const T& obj)
512 {
513 write_tuple_traits<typename T::_tls_traits>(str, obj._tls_fields_w());
514 return str;
515 }
516
517 // Struct reader without traits (enabled by macro)
518 template<size_t I = 0, typename... Tp>
519 inline typename std::enable_if<I == sizeof...(Tp), void>::type
520 read_tuple(istream&, const std::tuple<Tp...>&)
521 {
522 }
523
524 template<size_t I = 0, typename... Tp>
525 inline
526 typename std::enable_if < I<sizeof...(Tp), void>::type
527 read_tuple(istream& str, const std::tuple<Tp...>& t)
528 {
529 str >> std::get<I>(t);
530 read_tuple<I + 1, Tp...>(str, t);
531 }
532
533 template<typename T>
534 inline
535 typename std::enable_if<is_serializable<T>::value && !has_traits<T>::value,
536 istream&>::type
537 operator>>(istream& str, T& obj)
538 {
539 read_tuple(str, obj._tls_fields_r());
540 return str;
541 }
542
543 // Struct reader with traits (enabled by macro)
544 template<typename Tr, size_t I = 0, typename... Tp>
545 inline typename std::enable_if<I == sizeof...(Tp), void>::type
546 read_tuple_traits(istream&, const std::tuple<Tp...>&)
547 {
548 }
549
550 template<typename Tr, size_t I = 0, typename... Tp>
551 inline typename std::enable_if <
552 I<sizeof...(Tp), void>::type
553 read_tuple_traits(istream& str, const std::tuple<Tp...>& t)
554 {
555 std::tuple_element_t<I, Tr>::decode(str, std::get<I>(t));
556 read_tuple_traits<Tr, I + 1, Tp...>(str, t);
557 }
558
559 template<typename T>
560 inline
561 typename std::enable_if<is_serializable<T>::value && has_traits<T>::value,
562 istream&>::type
563 operator>>(istream& str, T& obj)
564 {
565 read_tuple_traits<typename T::_tls_traits>(str, obj._tls_fields_r());
566 return str;
567 }
568
569 } // namespace mlspp::tls