-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserialize.hpp
1055 lines (929 loc) · 31.8 KB
/
serialize.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// This header is distributed under MIT license.
///
/// Author: Marcin Poloczek (aka. RedSkittleFox)
/// Contact: [email protected]
/// Copyright: Marcin Poloczek
/// License: MIT
/// Version: 1.0.0
///
#ifndef FOX_SERIALIZE_H_
#define FOX_SERIALIZE_H_
#pragma once
#include <version>
#if !defined(__cpp_lib_ranges_to_container)
#error "RedSkittleFox::Serialize requires STL to implement std::ranges::to for it's container serialization specializations."
#endif
#include <tuple>
#include <utility>
#include <iterator>
#include <span>
#include <ranges>
#include <vector>
#include <format>
#include <variant>
#include <cstring>
#include <memory_resource>
#ifdef FOX_SERIALIZE_HAS_REFLEXPR
#include <fox/reflexpr.hpp>
#endif
#ifdef FOX_SERIALIZE_INLINE
#pragma message "FOX_SERIALIZE_INLINE macro is internally used by redskittlefox/serialize library"
#undef FOX_SERIALIZE_INLINE
#endif
#ifdef FOX_SERIALIZE_CONSTEXPR_LAMBDA
#pragma message "FOX_SERIALIZE_CONSTEXPR_LAMBDA macro is internally used by redskittlefox/serialize library"
#undef FOX_SERIALIZE_CONSTEXPR_LAMBDA
#endif
#ifdef __clang__
#define FOX_SERIALIZE_INLINE __attribute__((always_inline))
#define FOX_SERIALIZE_CONSTEXPR_LAMBDA __attribute__((always_inline)) constexpr
#endif
#if __GNUC__
#define FOX_SERIALIZE_INLINE __attribute__((always_inline))
#define FOX_SERIALIZE_CONSTEXPR_LAMBDA constexpr
#endif
#if defined(_MSC_VER) && !defined(__clang__)
#define FOX_SERIALIZE_INLINE __forceinline
#define FOX_SERIALIZE_CONSTEXPR_LAMBDA constexpr
#endif
namespace fox::serialize
{
#pragma region streams
class bit_writer;
class bit_reader;
/**
* \brief Implements raw byte buffer that can be written to.
*/
class bit_writer
{
std::pmr::vector<std::byte> buffer_;
public:
/**
* \brief Default constructor. Constructs empty bit_writer.
*/
bit_writer() = default;
/**
* \brief Constructs an empty bit_writer with the given memory resource.
* \param mr Memory resource to construct bit_writer with.
*/
bit_writer(std::pmr::memory_resource* mr)
: buffer_(std::pmr::polymorphic_allocator{mr}) {}
/**
* \brief Copy constructor. Constructs bit_writer with the copy of the contents of the other.
*/
bit_writer(const bit_writer&) = default;
/**
* \brief Move constructor. Constructs bit_writer with the contents of other using move semantics.
*/
bit_writer(bit_writer&&) noexcept = default;
/**
* \brief Copy assignment operator. Replaces the contents with a copy of the contents of other.
* \return *this
*/
bit_writer& operator=(const bit_writer&) = default;
/**
* \brief Move assignment operator. Replaces the contents with those of other using move semantics.
* \return *this
*/
bit_writer& operator=(bit_writer&&) noexcept = default;
/**
* \brief Destructor of the bit_writer.
*/
~bit_writer() noexcept = default;
public:
/**
* \brief Returns the allocator associated with the bit_writer.
* \return The associated allocator.
*/
auto get_allocator() const noexcept -> decltype(buffer_)::allocator_type
{
return buffer_.get_allocator();
}
public:
/**
* \brief Erases previously serialized data. Resets bit_writer.
*/
void clear()
{
buffer_.clear();
}
public:
/**
* \brief Allocates memory to write num_bytes in the bit_writer.
* \param num_bytes Number of bytes requested to be written.
* \return Pointer to memory, to populate with serialized data. Returned pointer is invalidated on the next call to write_bytes.
*/
[[nodiscard]] FOX_SERIALIZE_INLINE void* write_bytes(std::size_t num_bytes)
{
const std::size_t offset = std::size(buffer_);
buffer_.resize(offset + num_bytes);
return static_cast<void*>(std::data(buffer_) + offset);
}
/**
* \brief Allocates memory to write NumBytes in the bit_writer.
* \tparam NumBytes Number of bytes requested to be written.
* \return Pointer to memory, to populate with serialized data. Returned pointer is invalidated on the next call to write_bytes.
*/
template<std::size_t NumBytes>
[[nodiscard]] FOX_SERIALIZE_INLINE void* write_bytes()
{
const std::size_t offset = std::size(buffer_);
buffer_.resize(offset + NumBytes);
return static_cast<void*>(std::data(buffer_) + offset);
}
public:
/**
* \brief Direct access to the underlying contiguous storage.
* \return Span of bytes to serialized data.
*/
[[nodiscard]] std::span<const std::byte> data() const noexcept
{
return buffer_;
}
};
/**
* \brief Tag type used for the constructor disambiguation.
* Refer to samples/sample_custom_3.cpp
*/
struct from_bit_reader_t {};
/**
* \brief Tag used for the constructor disambiguation.
* Refer to samples/sample_custom_3.cpp
*/
constexpr from_bit_reader_t from_bit_reader;
/**
* \brief Implements raw byte buffer that can be read from.
*/
class bit_reader
{
std::pmr::vector<std::byte> buffer_;
std::size_t offset_{};
public:
/**
* \brief Default constructor. Constructs empty bit_reader.
*/
bit_reader() = default;
/**
* \brief Constructs an empty bit_reader with the given memory resource.
* \param mr Memory resource to construct bit_reader with.
*/
bit_reader(std::pmr::memory_resource* mr)
: buffer_(std::pmr::polymorphic_allocator{ mr }), offset_(static_cast<std::size_t>(0)) {}
/**
* \brief Copy constructor. Constructs bit_reader with the copy of the contents of the other.
* \param other bit_reader to copy contents from
*/
bit_reader(const bit_reader& other) : buffer_(other.buffer_), offset_(other.offset_) {}
/**
* \brief Move constructor. Constructs bit_reader with the contents of other using move semantics.
* \param other bit_reader to move contents from
*/
bit_reader(bit_reader&& other) noexcept
: buffer_(std::exchange(other.buffer_, {})), offset_(std::exchange(other.offset_, {}))
{}
/**
* \brief Copy assignment operator. Replaces the contents with a copy of the contents of other.
* \param other bit_reader to copy contents from
* \return *this
*/
bit_reader& operator=(const bit_reader& other)
{
buffer_ = other.buffer_;
offset_ = other.offset_;
return *this;
}
/**
* \brief Move assignment operator. Replaces the contents with those of other using move semantics.
* \param other bit_reader to move contents from
* \return *this
*/
bit_reader& operator=(bit_reader&& other) noexcept
{
buffer_ = std::exchange(other.buffer_, {});
offset_ = std::exchange(other.offset_, {});
return *this;
}
/**
* \brief Constructs bit_reader with the contents of the range.
* \tparam Range Range of trivial types convertible to the range of bytes.
* \param range Range of trivial types convertible to the range of bytes.
*/
template<std::ranges::range Range>
bit_reader(std::from_range_t, Range && range)
requires std::is_trivial_v<std::ranges::range_value_t<Range>>
{
using value_type = std::ranges::range_value_t<Range>;
if constexpr (std::ranges::contiguous_range<Range>)
{
auto span = std::as_bytes(std::span(range));
buffer_ = span | std::ranges::to<std::pmr::vector<std::byte>>();
}
else
{
auto it = std::begin(range);
auto end = std::end(range);
buffer_ = std::ranges::subrange(it, end)
| std::transform(
[](const value_type& v) -> std::array<std::byte, sizeof(value_type)>
{ return std::bit_cast<std::array<std::byte, sizeof(value_type)>>(v); })
| std::views::join
| std::ranges::to<std::vector<std::byte>>();
}
}
/**
* \brief Destructor of the bit_reader.
*/
~bit_reader() noexcept = default;
public:
/**
* \brief Returns the allocator associated with the bit_writer.
* \return The associated allocator.
*/
auto get_allocator() const noexcept -> decltype(buffer_)::allocator_type
{
return buffer_.get_allocator();
}
public:
/**
* \brief Erases previously serialized data. Resets bit_writer.
*/
void clear()
{
buffer_.clear();
offset_ = {};
}
public:
/**
* \brief Acquires pointer to the data that is to be deserialized.
* \param num_bytes Number of bytes requested to be read.
* \return Pointer to memory, that contains serialized object.
*/
[[nodiscard]] FOX_SERIALIZE_INLINE const void* read_bytes(std::size_t num_bytes)
{
if (offset_ + num_bytes > std::size(buffer_))
throw std::out_of_range("Trying to serialize data that is out of range.");
const void* ptr = static_cast<const void*>(std::data(buffer_) + offset_);
offset_ += num_bytes;
return ptr;
}
/**
* \brief Acquires pointer to the data that is to be deserialized.
* \tparam NumBytes Number of bytes requested to be read.
* \return Pointer to memory, that contains serialized object.
*/
template<std::size_t NumBytes>
[[nodiscard]] FOX_SERIALIZE_INLINE const void* read_bytes()
{
if (offset_ + NumBytes > std::size(buffer_))
throw std::out_of_range("Trying to serialize data that is out of range.");
const void* ptr = static_cast<const void*>(std::data(buffer_) + offset_);
offset_ += NumBytes;
return ptr;
}
};
#pragma endregion streams
#pragma region traits
/**
* \brief Trait class used to provide serialization methods for a given type.
* \tparam T Serialized type.
*/
template<class T> struct serialize_traits;
namespace details
{
// Internal serialization trait, selected if no public serialize_traits is available
template<class T> struct builtin_serialize_traits;
template<class T>
concept builtin_serializable = requires (bit_writer & writer, const T & a)
{
{ ::fox::serialize::details::builtin_serialize_traits<T>::serialize(writer, a) } -> std::same_as<void>;
};
template<class T>
concept builtin_deserializable = requires (bit_reader & reader, T & b)
{
{ ::fox::serialize::details::builtin_serialize_traits<T>::deserialize(reader, b) } -> std::same_as<void>;
};
template<class T>
concept custom_serializable_serialize_trait = requires (bit_writer & writer, const T & a)
{
serialize_traits<T>::serialize(writer, a);
};
template<class T>
concept custom_serializable_member_function = requires (bit_writer & writer, const T & a)
{
a.serialize(writer);
};
template<class T>
concept custom_serializable_static_member_function = requires (bit_writer & writer, const T & a)
{
T::serialize(writer, a);
};
template<class T>
concept custom_serializable_member_serialize_trait = requires (bit_writer & writer, const T & a)
{
T::serialize_trait::serialize(writer, a);
};
template<class T>
concept custom_serializable =
custom_serializable_serialize_trait<T> ||
custom_serializable_member_function<T> ||
custom_serializable_static_member_function<T> ||
custom_serializable_member_serialize_trait<T>;
template<class T>
concept custom_deserializable_serializable_trait = requires (bit_reader & reader, T & b)
{
serialize_traits<T>::deserialize(reader, b);
};
template<class T>
concept custom_deserializable_member_function = requires (bit_reader & reader, T& a)
{
a.deserialize(reader);
};
template<class T>
concept custom_deserializable_static_member_function = requires (bit_reader & reader, T& a)
{
T::deserialize(reader, a);
};
template<class T>
concept custom_deserializable_member_serialize_trait = requires (bit_reader & reader, T& a)
{
T::serialize_trait::deserialize(reader, a);
};
template<class T>
concept custom_deserializable_construct = requires (bit_reader & reader, T & a)
{
a = T(from_bit_reader, reader);
};
template<class T>
concept custom_deserializable =
custom_deserializable_serializable_trait<T> ||
custom_deserializable_member_function<T> ||
custom_deserializable_static_member_function<T> ||
custom_deserializable_member_serialize_trait<T> ||
custom_deserializable_construct<T>;
}
/**
* \brief Check, if type is serializable.
* \tparam T a type to check
*/
template<class T>
concept serializable = ::fox::serialize::details::builtin_serializable<T> || ::fox::serialize::details::custom_serializable<T>;
/**
* \brief Check, if type is deserializable.
* \tparam T a type to check
*/
template<class T>
concept deserializable = ::fox::serialize::details::builtin_deserializable<T> || ::fox::serialize::details::custom_deserializable<T>;
/**
* \brief Check, if type is serializable.
* \tparam T a type to check
*/
template<class T>
static constexpr bool is_serializable_v = serializable<T>;
/**
* \brief Check, if type is serializable.
* \tparam T a type to check
*/
template<class T>
struct is_serializable : std::bool_constant<is_serializable_v<T>> {};
/**
* \brief Check, if type is deserializable.
* \tparam T a type to check
*/
template<class T>
static constexpr bool is_deserializable_v = deserializable<T>;
/**
* \brief Check, if type is deserializable.
* \tparam T a type to check
*/
template<class T>
struct is_deserializable : std::bool_constant<is_deserializable_v<T>> {};
namespace details
{
template<::fox::serialize::serializable T>
FOX_SERIALIZE_INLINE void do_serialize(bit_writer& lhs, const T& rhs)
{
if constexpr (::fox::serialize::details::custom_serializable<T>)
{
if constexpr (custom_serializable_serialize_trait<T>)
{
serialize_traits<T>::serialize(lhs, rhs);
}
else if constexpr (custom_serializable_member_function<T>)
{
rhs.serialize(lhs);
}
else if constexpr(custom_serializable_static_member_function<T>)
{
T::serialize(lhs, rhs);
}
else if constexpr(custom_serializable_member_serialize_trait<T>)
{
T::serialize_trait::serialize(lhs, rhs);
}
}
else
{
return ::fox::serialize::details::builtin_serialize_traits<T>::serialize(lhs, rhs);
}
}
template<::fox::serialize::deserializable T>
FOX_SERIALIZE_INLINE void do_deserialize(bit_reader& lhs, T& rhs)
{
if constexpr (::fox::serialize::details::custom_deserializable<T>)
{
if constexpr(custom_deserializable_serializable_trait<T>)
{
serialize_traits<T>::deserialize(lhs, rhs);
}
else if constexpr(custom_deserializable_member_function<T>)
{
rhs.deserialize(lhs);
}
else if constexpr(custom_deserializable_static_member_function<T>)
{
T::deserialize(lhs, rhs);
}
else if constexpr(custom_deserializable_member_serialize_trait<T>)
{
T::serialize_trait::deserialize(lhs, rhs);
}
else if constexpr(custom_deserializable_construct<T>)
{
rhs = T(from_bit_reader, lhs);
}
}
else
{
return ::fox::serialize::details::builtin_serialize_traits<T>::deserialize(lhs, rhs);
}
}
}
/**
* \brief Serializes object into bit_writer
* \tparam T Type of the object to serialize
* \param lhs bit_writer
* \param rhs object to serialize
* \return lhs
*/
template<serializable T>
FOX_SERIALIZE_INLINE bit_writer& operator|(bit_writer& lhs, const T& rhs)
{
::fox::serialize::details::do_serialize<T>(lhs, rhs);
return lhs;
}
/**
* \brief Deserializes object from bit_reader
* \tparam T Type of the object to deserialize
* \param lhs bit_reader
* \param rhs object to deserialize
* \return lhs
*/
template<deserializable T>
FOX_SERIALIZE_INLINE bit_reader& operator|(bit_reader& lhs, T& rhs)
{
::fox::serialize::details::do_deserialize<T>(lhs, rhs);
return lhs;
}
/**
* \brief Serializes object into bit_writer
* \tparam T Type of the object to serialize
* \param lhs bit_writer
* \param rhs object to serialize
*/
template<serializable T>
FOX_SERIALIZE_INLINE void serialize(bit_writer& lhs, const T& rhs)
{
::fox::serialize::details::do_serialize<T>(lhs, rhs);
}
/**
* \brief Deserializes object from bit_reader
* \tparam T Type of the object to deserialize
* \param lhs bit_reader
* \param rhs object to deserialize
*/
template<serializable T>
FOX_SERIALIZE_INLINE void deserialize(bit_reader& lhs, const T& rhs)
{
::fox::serialize::details::do_deserialize<T>(lhs, rhs);
}
/**
* \brief Deserializes object from bit_reader
* \tparam T Type of the object to deserialize
* \param lhs bit_reader
* \return deserialized object
*/
template<serializable T>
[[nodiscard]] FOX_SERIALIZE_INLINE T deserialize(bit_reader& lhs)
{
if constexpr(::fox::serialize::details::custom_deserializable_construct<T>)
{
return T(from_bit_reader, lhs);
}
else
{
static_assert(std::is_default_constructible_v<T>, "[T] is not default constructible.");
T v;
::fox::serialize::details::do_deserialize<T>(lhs, v);
return v;
}
}
#pragma endregion traits
namespace details
{
// This section provides implementation of default serialization functions for most common cases.
// Serializations are divided into sections and then later bunched together, this simplifies SFINAE-compatible implementation later
#pragma region builtin_serialize_const_types
// Implementation for const-types
template<class T> requires builtin_serializable<T>
struct builtin_serialize_traits<const T>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& value)
{
do_serialize<T>(writer, value);
}
};
#pragma endregion builtin_serialize_const_types
#pragma region builtin_serialize_reference_types
// Implementation for const-types
template<class T> requires builtin_serializable<T>
struct builtin_serialize_traits<T&>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& value)
{
do_serialize<T>(writer, value);
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, T& value)
{
do_deserialize<T>(reader, value);
}
};
#pragma endregion builtin_serialize_reference_types
#pragma region builtin_serialize_trivially_copyable
// Implementation for trivially copyable types
template<class T> requires ( !std::ranges::range<T> && std::is_trivially_copyable_v<T> )
struct builtin_serialize_traits<T>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& value)
{
auto ptr = writer.write_bytes<sizeof(T)>();
*static_cast<T*>(ptr) = value;
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, T& value)
{
auto ptr = reader.read_bytes<sizeof(T)>();
value = *static_cast<const T*>(ptr);
}
};
#pragma endregion builtin_serialize_trivially_copyable
#pragma region builtin_serialize_ranges
template<class T>
struct is_array : std::false_type {};
template<class T, std::size_t Size>
struct is_array<std::array<T, Size>> : std::true_type {};
// Helper traits for std::ranges::to - concept
template<class Container>
constexpr bool reservable_container =
std::ranges::sized_range<Container> &&
requires(Container& c, std::ranges::range_size_t<Container> n)
{
c.reserve(n);
{ c.capacity() } -> std::same_as<decltype(n)>;
{ c.max_size() } -> std::same_as<decltype(n)>;
};
template<class Container, class Ref>
constexpr bool container_insertable =
requires(Container& c, Ref&& ref)
{
requires(requires {c.push_back(std::forward<Ref>(ref)); } ||
requires {c.insert(c.end(), std::forward<Ref>(ref)); });
};
// std::ranges::to concept, std::ranges::to isn't SFINAE compatible - it uses static_assert
template<class C, std::ranges::input_range R, class... Args>
constexpr bool is_ranges_to_convertible =
// Mandates: C is a cv-unqualified class type
std::is_const_v<C> == false &&
std::is_volatile_v<C> == false &&
std::is_class_v<C> == true &&
(
(
(std::ranges::input_range<C> == false || std::convertible_to<std::ranges::range_reference_t<R>, std::ranges::range_value_t<R>> == true) &&
(
std::constructible_from<C, R, Args...> == true ||
std::constructible_from<C, std::from_range_t, R, Args...> == true ||
(
std::ranges::common_range<R> &&
std::derived_from<typename std::iterator_traits<std::ranges::iterator_t<R>>::iterator_category, std::input_iterator_tag> &&
std::constructible_from<C, std::ranges::iterator_t<R>, std::ranges::sentinel_t<R>, Args...> == true
) ||
(
std::constructible_from<C, Args...> == true &&
container_insertable<C, std::ranges::range_reference_t<R>> == true
)
)
) ||
( std::ranges::input_range<std::ranges::range_reference_t<R>> && std::convertible_to<std::ranges::range_reference_t<R>, C> )
);
#pragma region tuple_like
template<template <std::size_t, class> class Trait, class T, class>
struct indexed_conjunction_proxy : std::false_type {};
template<template <std::size_t, class> class Trait, class T, std::size_t... Idx>
struct indexed_conjunction_proxy<Trait, T, std::index_sequence<Idx...>> : std::conjunction<Trait<Idx, T>...> {};
template<template <std::size_t, class> class Trait, class T, std::size_t Size>
struct indexed_conjunction : indexed_conjunction_proxy < Trait, T, std::make_index_sequence<Size>> {};
template<template <std::size_t, class> class Trait, class T>
struct indexed_conjunction<Trait, T, static_cast<std::size_t>(0)> : std::true_type {};
template<std::size_t Idx, class T>
constexpr bool has_tuple_element_v =
requires(T tuple)
{
typename std::tuple_element_t<Idx, std::remove_cvref_t<T>>;
{ std::get<Idx>(tuple) } -> std::convertible_to<const std::tuple_element_t<Idx, T>&>;
};
template<std::size_t Idx, class T>
struct has_tuple_element : std::bool_constant<has_tuple_element_v<Idx, T>> {};
template<class T>
constexpr bool is_tuple_like_v =
std::is_reference_v<T> == false &&
requires
{
typename std::tuple_size<T>::type;
requires std::derived_from<std::tuple_size<T>, std::integral_constant<std::size_t, std::tuple_size_v<T>>>;
requires indexed_conjunction<has_tuple_element, T, std::tuple_size_v<T>>::value;
};
template<class T>
concept tuple_like = is_tuple_like_v<T>;
#pragma endregion tuple_like
template<class T>
struct tuple_like_remove_const
{
using type = T;
};
template<template<class...> class Tuple, class... Ts> requires
is_tuple_like_v<Tuple<Ts...>> && std::is_constructible_v<Tuple<Ts...>, Tuple<std::remove_const_t<Ts>...>>
struct tuple_like_remove_const<Tuple<Ts...>>
{
using type = Tuple<std::remove_const_t<Ts>...>;
};
template<std::ranges::range T>
struct builtin_serialize_traits<T>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& range) requires
serializable<std::ranges::range_value_t<T>>
{
using value_type = std::ranges::range_value_t<T>;
const std::size_t range_size = std::size(range);
writer | range_size;
// Check if we can memcpy the range
constexpr bool memcpy_compatible =
std::ranges::contiguous_range<T> &&
static_cast<bool>(fox::serialize::details::custom_serializable<value_type>) == false &&
static_cast<bool>(fox::serialize::details::custom_deserializable<value_type>) == false &&
std::is_trivially_copyable_v<value_type>;
if constexpr (memcpy_compatible)
{
auto dest = static_cast<std::remove_const_t<T>*>(writer.write_bytes(sizeof(value_type) * range_size));
(void)std::memcpy(dest, std::data(range), sizeof(value_type) * range_size);
}
else // We iterate over the range
{
for (auto&& e : range)
{
writer | e;
}
}
}
static constexpr bool is_deserializable =
!std::ranges::borrowed_range<T> &&
deserializable<tuple_like_remove_const<std::ranges::range_value_t<T>>> && // In case we are tuple with const member, remove const if constructible from it
(::fox::serialize::details::is_array<T>::value ||
(
::fox::serialize::details::is_ranges_to_convertible<T, std::span<const std::ranges::range_value_t<T>>> &&
(std::is_default_constructible_v<std::ranges::range_value_t<T>> || details::custom_deserializable_construct<T>)));
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, T& value) requires is_deserializable
{
using value_type = typename tuple_like_remove_const<std::ranges::range_value_t<T>>::type;
using const_value_type = std::add_const_t<std::ranges::range_value_t<T>>;
std::size_t size{};
reader | size;
// Check if we can memcpy the range
constexpr bool memcpy_compatible =
static_cast<bool>(fox::serialize::details::custom_serializable<value_type>) == false &&
static_cast<bool>(fox::serialize::details::custom_deserializable<value_type>) == false &&
std::is_trivially_copyable_v<value_type>;
if constexpr (::fox::serialize::details::is_ranges_to_convertible<T, std::span<const value_type>> && memcpy_compatible)
{
const value_type* ptr = static_cast<const value_type*>(reader.read_bytes(sizeof(value_type) * size));
value = std::span<const_value_type >{ ptr, size } | std::ranges::to<T>();
}
else if constexpr (::fox::serialize::details::is_array<T>::value)
{
if (size != std::size(value))
{
throw std::out_of_range(std::format("Trying to read ranges ({} elements) of a different size than the array ({} elements).",
size, std::size(value))
);
}
// Memcpy array
if constexpr (memcpy_compatible)
{
auto ptr = static_cast<const value_type*>(reader.read_bytes(sizeof(value_type) * size));
std::memcpy(static_cast<void*>(std::data(value)), static_cast<const void*>(ptr), sizeof(value_type) * size);
}
else // Or iterate over elements and serialize them
{
for (auto&& e : value)
{
reader | e;
}
}
}
else // Iterate over elements, serialize them and then convert them into the range
{
value = std::views::iota(static_cast<std::size_t>(0), size)
| std::views::transform([&](auto) FOX_SERIALIZE_CONSTEXPR_LAMBDA -> value_type
{
if constexpr(custom_deserializable_construct<value_type>)
{
// Construct with reader if possible
value_type v(from_bit_reader, reader);
return v;
}
else
{
value_type v;
reader | v;
return v;
}
})
| std::views::as_rvalue
| std::ranges::to<T>();
}
}
};
#pragma endregion builtin_serialize_ranges
#pragma region builtin_tuple_like
template<class T>
requires ( !std::ranges::range<T> && !std::is_trivially_copyable_v<T> && ::fox::serialize::details::tuple_like<T> )
struct builtin_serialize_traits<T>
{
template<std::size_t Idx, class U>
struct tuple_element_serializable : is_serializable<std::tuple_element_t<Idx, U>> {};
template<std::size_t Idx, class U>
struct tuple_element_deserializable : is_deserializable<std::tuple_element_t<Idx, U>> {};
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& tuple)
requires details::indexed_conjunction<tuple_element_serializable, T, std::tuple_size_v<T>>::value
{
[&] <std::size_t... Idx>(std::index_sequence<Idx...>) FOX_SERIALIZE_CONSTEXPR_LAMBDA
{
(::fox::serialize::details::do_serialize<std::tuple_element_t<Idx, T>>(writer, std::get<Idx>(tuple)), ...);
}(std::make_index_sequence<std::tuple_size_v<T>>{});
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, T& tuple) requires
::fox::serialize::details::indexed_conjunction<tuple_element_deserializable, T, std::tuple_size_v<T>>::value
{
[&] <std::size_t... Idx>(std::index_sequence<Idx...>) FOX_SERIALIZE_CONSTEXPR_LAMBDA
{
(::fox::serialize::details::do_deserialize<std::tuple_element_t<Idx, T>>(reader, std::get<Idx>(tuple)), ...);
}(std::make_index_sequence<std::tuple_size_v<T>>{});
}
};
#pragma endregion builtin_tuple_like
#pragma region builtin_aggregate_types
#ifdef FOX_SERIALIZE_HAS_REFLEXPR
template<::fox::reflexpr::aggregate T>
requires ( !std::ranges::range<T> && !std::is_trivially_copyable_v<T> && !::fox::serialize::details::tuple_like<T> )
struct builtin_serialize_traits<T>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const T& aggregate)
requires serializable<decltype(fox::reflexpr::tie(std::declval<T&>()))>
{
auto tie = fox::reflexpr::tie(aggregate);
::fox::serialize::details::do_serialize<decltype(tie)>(writer, tie);
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, T& aggregate)
requires deserializable<decltype(fox::reflexpr::tie(std::declval<T&>()))>
{
auto tie = fox::reflexpr::tie(aggregate);
::fox::serialize::details::do_deserialize<decltype(tie)>(reader, tie);
}
};
#endif
#pragma endregion builtin_aggregate_types
#pragma region builtin_variant
template<class... Args>
struct builtin_serialize_traits<std::variant<Args...>>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const std::variant<Args...>& variant)
requires std::conjunction_v<is_serializable<Args>...>
{
const std::size_t idx = variant.index();
writer | idx;
if(idx != std::variant_npos)
{
std::visit([&](auto&& v) { writer | v; }, variant);
}
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, std::variant<Args...>& variant)
requires std::conjunction_v<is_deserializable<Args>...>
{
std::size_t idx;
reader | idx;
if (idx != std::variant_npos)
{
if (idx >= std::variant_size_v<std::variant<Args...>>)
throw std::invalid_argument("Invalid variant index."); // TODO: Custom exception type
[&]<std::size_t... Is>(std::index_sequence<Is...>) FOX_SERIALIZE_CONSTEXPR_LAMBDA
{
([&]<std::size_t I>(std::in_place_index_t<I>) FOX_SERIALIZE_CONSTEXPR_LAMBDA
{
if(I == idx)
{
using c_alternative = std::variant_alternative_t<I, std::variant<Args...>>;
using alternative = std::remove_const_t<c_alternative>;
if constexpr (custom_deserializable_construct<alternative>)
{
// Construct with reader if possible
variant.template emplace<c_alternative>(from_bit_reader, reader);
}
else
{
reader | variant.template emplace<c_alternative>();
}
}
}(std::in_place_index<Is>), ...);
}(std::index_sequence_for<Args...>{});
}
}
};
#pragma endregion builtin_variant
#pragma region builtin_optional
template<class T>
struct builtin_serialize_traits<std::optional<T>>
{
FOX_SERIALIZE_INLINE static void serialize(bit_writer& writer, const std::optional<T>& optional)
requires is_serializable_v<T>
{
writer | optional.has_value();
if(optional.has_value())
{
writer | optional.value();
}
}
FOX_SERIALIZE_INLINE static void deserialize(bit_reader& reader, std::optional<T>& optional)
requires is_deserializable_v<T>
{
bool has_value = false;
reader | has_value;
if(has_value)
{
if constexpr (custom_deserializable_construct<T>)
{
// Construct with reader if possible
optional.emplace(from_bit_reader, reader);
}