summaryrefslogtreecommitdiff
path: root/source/slang/slang-serialize.h
blob: 261f3f2d634e463aba0fd5a9caf09a407585954b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
// slang-serialize.h
#ifndef SLANG_SERIALIZE_H
#define SLANG_SERIALIZE_H

// This file defines an API for serialization.
//
// The API is intended to support multiple serialization formats,
// and to work with complicated object graphs that may include
// shared pointers, circular references, and so on.
//
// For anybody who don't want to dig into the details, the short
// version is that if you have a user-defined type like:
//
//      // my-thing.h
//      ...
//
//      struct MyThing
//      {
//          float a;
//          List<OtherThing> otherThings;
//          SomeObject* object;
//      };
//
// then you can declare serialization support for your type
// with something like:
//
//      // my-thing.h
//      ...
//      #include "slang-serialize.h"
//      ...
//
//      struct MyThing { ... }
//
//      void serialize(Serializer const& serializer, MyThing& value);
//
// and then implement that support with something like:
//
//      // my-thing.cpp
//      #include "my-thing.h"
//
//      ...
//
//      void serialize(Serializer const& serializer, MyThing& value)
//      {
//          SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
//          serialize(serializer, value.a);
//          serialize(serializer, value.otherThings);
//          serialize(serializer, value.object);
//      }
//
// That's it. So long as the `OtherThing` and `SomeObject` types used
// in the declaration of `MyType` already implemented serialization
// support, your new type should be fully serializable.
//

#include "../core/slang-basic.h"

#include <optional>

namespace Slang
{

//
// A central design choice of this serialization system is that
// both reading and writing of serialized data for a type are
// implemented using a single function. This choice makes it
// easier for a developer to be certain that the reading and
// writing code for a type are consistent with one another.
//
// In some cases, however, a serialization function may need
// to know whether it is reading or writing serialized data.
// For that reason, we define a simple `enum` to represent
// the different modes of operation.
//

/// Whether serialized data is being read or written.
enum class SerializationMode
{
    Read,
    Write,
};

//
// In order to support different serialized formats, and to
// abstract over the difference between reading and writing,
// we define a base interface for serialization. This interface
// is somewhat user-unfriendly, and is *not* intended for
// ordinary code to interface with directly.
//

/// Base interface for serialization.
///
/// Can be used for both reading and writing of serialized data.
///
struct ISerializerImpl
{
    /// Get the mode that this serializer is operating in (reading or writing).
    virtual SerializationMode getMode() = 0;

    /// Handle a boolean value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleBool(bool& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleInt8(int8_t& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleInt16(int16_t& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleInt32(Int32& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleInt64(Int64& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleUInt8(uint8_t& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleUInt16(uint16_t& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleUInt32(UInt32& value) = 0;

    /// Handle an integer value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleUInt64(UInt64& value) = 0;

    /// Handle a floating-point value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleFloat32(float& value) = 0;

    /// Handle a floating-point value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleFloat64(double& value) = 0;

    /// Handle a string value.
    ///
    /// If the serializer is writing, then `value` will be
    /// written to the serialized format.
    ///
    /// If the serializer is reading, then `value` will be
    /// set to the value read from the serialized format.
    ///
    virtual void handleString(String& value) = 0;

    /// Begin serializing an array value.
    ///
    /// An array should be used to serialize an
    /// unkeyed homogeneous collection of a varying
    /// number of elements.
    ///
    /// This operation must be properly paired with a
    /// call to `endArray()`.
    ///
    /// When writing, the values serialized between `beginArray()`
    /// and `endArray()` will be written as the elements of a
    /// serialized array.
    ///
    /// When reading, the user should call `hasElements()` to
    /// test whether there are elements remaining to be read,
    /// and serialize values in a loop until `hasElements()`
    /// returns `false`.
    ///
    virtual void beginArray() = 0;

    /// End serializing an array value.
    virtual void endArray() = 0;

    /// Begin serializing an optional value.
    ///
    /// An optional should be used to serialize a
    /// collection that logically has either zero
    /// or one element.
    ///
    /// This operation must be properly paired with a
    /// call to `endOptional()`.
    ///
    /// When writing, a value serialized between `beginOptional()`
    /// and `endOptional()` will be written as the value of
    /// the serialized optional. If no value is serialized,
    /// then the optional will be empty.
    ///
    /// When reading, the user should call `hasElements()` to
    /// test whether the serialized optional has a value and,
    /// if it does, read the value before calling `endOptional()`.
    ///
    virtual void beginOptional() = 0;

    /// End serializing an optional value.
    virtual void endOptional() = 0;

    /// Begin serializing a dictionary value.
    ///
    /// A dictionary should be used to serialize a
    /// keyed homogeneous collection of a varying
    /// number of elements. The elements of a dictioanry
    /// are key-value pairs (that is, two-element tuples).
    ///
    /// Formats are required to support dictionaries with
    /// any serializable type as the key, not just strings.
    ///
    /// This operation must be properly paired with a
    /// call to `endDictionary()`.
    ///
    /// When writing, the values serialized between `beginDictionary()`
    /// and `endDictionary()` will be written as the elements of a
    /// serialized dictionary.
    ///
    /// When reading, the user should call `hasElements()` to
    /// test whether there are elements remaining to be read,
    /// and serialize values in a loop until `hasElements()`
    /// returns `false`.
    ///
    virtual void beginDictionary() = 0;

    /// End serializing a dictionary value.
    virtual void endDictionary() = 0;

    /// Check whether there are elements remaining to be read
    /// from a serialized container.
    ///
    /// It is invalid to call this function except between paired
    /// `beginArray()`/`endArray()`, beginDictionary()`/`endDictionary()`,
    /// or `beginOptional()`/`endOptional()` calls.
    ///
    virtual bool hasElements() = 0;

    /// Begin serializing a tuple value.
    ///
    /// A tuple should be used to serialize an
    /// unkeyed heterogeneous collection of a fixed
    /// number of elements.
    ///
    /// It is up to the concrete implementation whether calls
    /// to `hasElements()` are allowed between `beginTuple()`
    /// and `endTuple()`.
    ///
    virtual void beginTuple() = 0;

    /// End serializing a tuple value.
    virtual void endTuple() = 0;


    /// Begin serializing a struct value.
    ///
    /// A struct should be used to serialize an
    /// keyed heterogeneous collection of a fixed
    /// number of elements.
    ///
    /// The value of each struct field should be
    /// preceded by a call to `handleFieldKey()`,
    /// which specifies the field being serialized.
    ///
    /// It is up to the concrete implementation whether
    /// a fields can be read in a different order than
    /// they were written, and how to handle attempts
    /// to read a field that was not written.
    ///
    virtual void beginStruct() = 0;

    /// End serializing a struct value.
    virtual void endStruct() = 0;

    /// Begin serializing a variant value.
    ///
    /// A variant should be used to serialize any type
    /// that behaves like a "tagged union," where different
    /// instances may have different sequences of members,
    /// of different types.
    ///
    /// User code reading from a variant must be able to
    /// use the members read so far to determine what
    /// members it should read next (e.g., by serializing
    /// a tag enumerant first, followed by the tag-dependent
    /// members).
    ///
    /// A variant is otherwise like a struct. Some serializer
    /// implementations may treat variants just like structs,
    /// while others may rely on any type serialized as a
    /// struct always including the same members in the same
    /// order.
    ///
    virtual void beginVariant() = 0;

    /// End serializing a variant value.
    virtual void endVariant() = 0;

    /// Set the key for the next struct field to be serialized.
    ///
    /// If no name is available for the field, `name` may be `nullptr`.
    ///
    /// If no index is available for the field, `index` may be `-1`.
    ///
    /// A user must pass either a valid `name` or `index.
    ///
    virtual void handleFieldKey(char const* name, Int index) = 0;

    /// A callback function used to handle serialization of pointers.
    typedef void (*Callback)(void* valuePtr, void* impl, void* context);

    /// Handle a pointer value that is expected to be unique.
    ///
    /// A unique pointer is logically similar to an optional value.
    ///
    /// If the pointer value being read/written is null, then
    /// the function returns without invoking `callback`.
    ///
    /// When reading, if the serialized value is non-null,
    /// then the callback will be invoked as `callback(&value, userData)`.
    /// The callback is expected to read the members of the pointed-to
    /// type and set `value` to some object (whether newly constructed
    /// or looked up).
    ///
    /// When writing, if the `value` is non-null, then the callback
    /// will be invoked, either immediately or at some later point,
    /// as `callback(&ptr, this, context)` where `ptr` is a variable
    /// holding a copy of the `value` that was passed in. The callback
    /// is expected to write the members of the pointed-to type.
    ///
    /// If the `callback` is invoked at some later point, rather than
    /// immediately, the concrete serializer implementation is responsible
    /// for ensuring that its internal state has been restored to
    /// be compatible with what it was when `handleUniquePtr` was called.
    ///
    virtual void handleUniquePtr(void*& value, Callback callback, void* context) = 0;

    /// Handle a pointer value that may have multiple references.
    ///
    /// This operation is similar to `handleUniquePtr` with the following
    /// differences:
    ///
    /// * When writing, if the same pointer value has been seen before,
    ///   the `callback` will not be invoked, and instead an additional
    ///   reference to the previously-serialized value will be written.
    ///
    /// * When reading, if the serialized value has been read before,
    ///   the `callback` will not be invoked, and instead `value` will
    ///   be set to the pointer that was previously read.
    ///
    virtual void handleSharedPtr(void*& value, Callback callback, void* context) = 0;

    /// Defer serialization of the contents of an object.
    ///
    /// Used to delay serialization of members of an object that
    /// could cause infinite recursion if serialized eagerly.
    ///
    /// This operation should only be used in the body of a callback
    /// passed to `handleUniquePtr()` or `handleSharedPtr()`.
    ///
    /// This operation schedules the given `callback` to be called
    /// at some later point a `callback(value, this, context)`, with
    /// the state of the serializer implementation restored to what
    /// it was when `handleDeferredObjectContents()` was called.
    ///
    /// Some concrete serializer implementations might implement
    /// this operation by invoking `callback` immediately.
    ///
    virtual void handleDeferredObjectContents(void* value, Callback callback, void* context) = 0;
};

//
// Rather than interact with instances of `ISerializerImpl` directly,
// most client code will use a wrapper type that amounts to a kind
// of smart pointer.
//
// While the `ISerializerImpl` interface can cover a wide range of
// types that need to be serialized, it is common for types to require
// more specific *context* to be available in order to perform serialization.
// For example, code might need access to a factory object in order
// to construct objects of a type being read.
//
// To support more specialized serializer implementations, the smart
// pointer type used for a serializer actually wraps *two* pointers:
// one for an `ISerializerImpl`-derived type, and one for a context
// type. The smart pointer is templated on both of these types.
//

/// Base type for serialization contexts.
///
/// The type parameter `Impl` should be a type that derives from
/// `ISerializerImpl`, and the `Context` type parameter can be any
/// type that passes along additional context information needed.
///
template<typename Impl, typename Context>
struct SerializerBase
{
public:
    SerializerBase() = default;
    SerializerBase(Impl* impl, Context* context = nullptr)
        : _impl(impl), _context(context)
    {
    }

    template<typename I, typename C>
    SerializerBase(
        SerializerBase<I, C> const& serializer,
        std::enable_if_t<
            std::is_convertible_v<I*, Impl*> && std::is_convertible_v<C*, Context*>,
            void>* = nullptr)
        : _impl(serializer.getImpl()), _context(serializer.getContext())
    {
    }

    Impl* getImpl() const { return _impl; }
    Context* getContext() const { return _context; }

    Impl* get() const { return _impl; }
    Impl* operator->() const { return get(); }


private:
    Impl* _impl = nullptr;
    Context* _context = nullptr;
};

/// A serialization context.
///
/// The type parameter `Impl` should be a type that derives from
/// `ISerializerImpl`, and the `Context` type parameter can be any
/// type that passes along additional context information needed.
///
template<typename Impl, typename Context>
struct Serializer_ : SerializerBase<Impl, Context>
{
    using SerializerBase<Impl, Context>::SerializerBase;
};

/// Default serialization context.
using Serializer = Serializer_<ISerializerImpl, void>;

//
// We define namespace-scope functions that mirror some
// of the operations of `ISerializerImpl`, so that they
// can be invoked on any type that is contextually
// convertible to a `Serializer`. This allows users
// to define their own serialization context types while
// still being able to take advantage of the utility
// operations in this file for serializing basic types,
// arrays, dictionaries, etc.
//


/// Get the mode of `serializer`.
inline SerializationMode getMode(Serializer const& serializer)
{
    return serializer->getMode();
}

/// Check if `serializer` is reading serialized data.
inline bool isReading(Serializer const& serializer)
{
    return getMode(serializer) == SerializationMode::Read;
}

/// Check if `serializer` is writing serialized data.
inline bool isWriting(Serializer const& serializer)
{
    return getMode(serializer) == SerializationMode::Write;
}

/// Check if `serializer` has more container elements.
inline bool hasElements(Serializer const& serializer)
{
    return serializer->hasElements();
}

inline void serialize(Serializer const& serializer, bool& value)
{
    serializer->handleBool(value);
}

inline void serialize(Serializer const& serializer, int8_t& value)
{
    serializer->handleInt8(value);
}

inline void serialize(Serializer const& serializer, int16_t& value)
{
    serializer->handleInt16(value);
}

inline void serialize(Serializer const& serializer, Int32& value)
{
    serializer->handleInt32(value);
}

inline void serialize(Serializer const& serializer, Int64& value)
{
    serializer->handleInt64(value);
}

inline void serialize(Serializer const& serializer, uint8_t& value)
{
    serializer->handleUInt8(value);
}

inline void serialize(Serializer const& serializer, uint16_t& value)
{
    serializer->handleUInt16(value);
}

inline void serialize(Serializer const& serializer, UInt32& value)
{
    serializer->handleUInt32(value);
}

inline void serialize(Serializer const& serializer, UInt64& value)
{
    serializer->handleUInt64(value);
}

inline void serialize(Serializer const& serializer, float& value)
{
    serializer->handleFloat32(value);
}

inline void serialize(Serializer const& serializer, double& value)
{
    serializer->handleFloat64(value);
}

inline void serialize(Serializer const& serializer, String& value)
{
    serializer->handleString(value);
}

/// Serialize an `enum` value via an intermediate integer type.
///
/// This function serializes a value of `EnumType`, by
/// converting it to/from the given `RawType` for storage
/// in the serialized format.
///
template<typename RawType = Int32, typename EnumType>
void serializeEnum(Serializer const& serializer, EnumType& value)
{
    auto raw = RawType(value);
    serialize(serializer, raw);
    value = EnumType(raw);
}

//
// We define a suite of simple RAII types to help users
// maintain the proper pairing of begin/end operations
// when interacting with an `ISerializerImpl`, and for
// each of those types we define a macro to simplify
// introducing a coresponding scope.
//

struct ScopedSerializerArray
{
public:
    ScopedSerializerArray(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginArray();
    }

    ~ScopedSerializerArray() { _serializer->endArray(); }

private:
    Serializer _serializer;
};

struct ScopedSerializerDictionary
{
public:
    ScopedSerializerDictionary(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginDictionary();
    }

    ~ScopedSerializerDictionary() { _serializer->endDictionary(); }

private:
    Serializer _serializer;
};

struct ScopedSerializerStruct
{
public:
    ScopedSerializerStruct(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginStruct();
    }

    ~ScopedSerializerStruct() { _serializer->endStruct(); }

private:
    Serializer _serializer;
};

struct ScopedSerializerVariant
{
public:
    ScopedSerializerVariant(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginVariant();
    }

    ~ScopedSerializerVariant() { _serializer->endVariant(); }

private:
    Serializer _serializer;
};

struct ScopedSerializerTuple
{
public:
    ScopedSerializerTuple(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginTuple();
    }

    ~ScopedSerializerTuple() { _serializer->endTuple(); }

private:
    Serializer _serializer;
};

struct ScopedSerializerOptional
{
public:
    ScopedSerializerOptional(Serializer const& serializer)
        : _serializer(serializer)
    {
        serializer->beginOptional();
    }

    ~ScopedSerializerOptional() { _serializer->endOptional(); }

private:
    Serializer _serializer;
};


#define SLANG_SCOPED_SERIALIZER_ARRAY(SERIALIZER) \
    ::Slang::ScopedSerializerArray SLANG_CONCAT(_scopedSerializerArray, __LINE__)(SERIALIZER)

#define SLANG_SCOPED_SERIALIZER_DICTIONARY(SERIALIZER)                                       \
    ::Slang::ScopedSerializerDictionary SLANG_CONCAT(_scopedSerializerDictionary, __LINE__)( \
        SERIALIZER)

#define SLANG_SCOPED_SERIALIZER_OPTIONAL(SERIALIZER) \
    ::Slang::ScopedSerializerOptional SLANG_CONCAT(_scopedSerializerOptional, __LINE__)(SERIALIZER)

#define SLANG_SCOPED_SERIALIZER_STRUCT(SERIALIZER) \
    ::Slang::ScopedSerializerStruct SLANG_CONCAT(_scopedSerializerStruct, __LINE__)(SERIALIZER)

#define SLANG_SCOPED_SERIALIZER_VARIANT(SERIALIZER) \
    ::Slang::ScopedSerializerVariant SLANG_CONCAT(_scopedSerializerVariant, __LINE__)(SERIALIZER)

#define SLANG_SCOPED_SERIALIZER_TUPLE(SERIALIZER) \
    ::Slang::ScopedSerializerTuple SLANG_CONCAT(_scopedSerializerTuple, __LINE__)(SERIALIZER)

//
// Containers like arrays and dictionaries are more
// difficult to serialize than typical user-defined
// types for a few reasons:
//
// * They typically need to have distinct code paths
//   for reading and writing, so they don't benefit
//   much from having a unified read/write abstraction.
//
// * They need to be written as templates, to abstract
//   over the element type, and thus need to be
//   defined in headers.
//
// * Because the element type might require a more
//   specialized type of serialization context, they
//   also need to be templated on the type of the
//   serializer itself.
//
// With all that said, the definitions themselves
// are fairly straightforward. All we have to do is
// branch on whether we are reading or writing and
// either iterate over the serialized data to fill
// the collection (when reading), or iterate over
// the collection to serialize its elements (when
// writing).
//

template<typename S, typename T>
void serialize(S const& serializer, List<T>& value)
{
    SLANG_SCOPED_SERIALIZER_ARRAY(serializer);
    if (isWriting(serializer))
    {
        for (auto element : value)
            serialize(serializer, element);
    }
    else
    {
        value.clear();
        while (hasElements(serializer))
        {
            T element;
            serialize(serializer, element);
            value.add(element);
        }
    }
}

template<typename S, typename T, size_t N>
void serialize(S const& serializer, T (&value)[N])
{
    SLANG_SCOPED_SERIALIZER_ARRAY(serializer);
    if (isWriting(serializer))
    {
        for (auto element : value)
            serialize(serializer, element);
    }
    else
    {
        size_t index = 0;
        while (hasElements(serializer))
        {
            T element;
            serialize(serializer, element);

            if (index >= N)
            {
                SLANG_UNEXPECTED("serialized array too large");
            }
            value[index++] = element;
        }
    }
}

template<typename S, typename T, int N>
void serialize(S const& serializer, ShortList<T, N>& value)
{
    SLANG_SCOPED_SERIALIZER_ARRAY(serializer);
    if (isWriting(serializer))
    {
        for (auto element : value)
            serialize(serializer, element);
    }
    else
    {
        value.clear();
        while (hasElements(serializer))
        {
            T element;
            serialize(serializer, element);
            value.add(element);
        }
    }
}

template<typename S, typename T>
void serialize(S const& serializer, std::optional<T>& value)
{
    SLANG_SCOPED_SERIALIZER_OPTIONAL(serializer);
    if (isWriting(serializer))
    {
        if (value.has_value())
        {
            serialize(serializer, *value);
        }
    }
    else
    {
        value.reset();
        if (hasElements(serializer))
        {
            value.emplace();
            serialize(serializer, *value);
        }
    }
}

template<typename S, typename K, typename V>
void serialize(S const& serializer, KeyValuePair<K, V>& value)
{
    SLANG_SCOPED_SERIALIZER_TUPLE(serializer);
    serialize(serializer, value.key);
    serialize(serializer, value.value);
}

template<typename S, typename K, typename V>
void serialize(S const& serializer, std::pair<K, V>& value)
{
    SLANG_SCOPED_SERIALIZER_TUPLE(serializer);
    serialize(serializer, value.first);
    serialize(serializer, value.second);
}

template<typename S, typename K, typename V>
void serialize(S const& serializer, Dictionary<K, V>& value)
{
    SLANG_SCOPED_SERIALIZER_DICTIONARY(serializer);
    if (isWriting(serializer))
    {
        for (auto pair : value)
            serialize(serializer, pair);
    }
    else
    {
        value.clear();
        while (hasElements(serializer))
        {
            KeyValuePair<K, V> pair{K(), V()};
            serialize(serializer, pair);
            value.add(pair.key, pair.value);
        }
    }
}

template<typename S, typename K, typename V>
void serialize(S const& serializer, OrderedDictionary<K, V>& value)
{
    SLANG_SCOPED_SERIALIZER_DICTIONARY(serializer);
    if (isWriting(serializer))
    {
        for (auto pair : value)
            serialize(serializer, pair);
    }
    else
    {
        value.clear();
        while (hasElements(serializer))
        {
            KeyValuePair<K, V> pair{K(), V()};
            serialize(serializer, pair);
            value.add(pair.key, pair.value);
        }
    }
}

//
// Serialization of pointers is the most complicated part of
// the whole system. Dealing with pointers means contending with:
//
// * Multiply-referenced objects, or even cycles in the object graph.
//
// * Polymoprhic types, where a `Derived*` might get serialized
//   through a `Base*` pointer.
//
// * Types that require going through a factory function of
//   some kind as part of their creation (perhaps to implement
//   deduplication/caching).
//
// Our handling of pointers is thus broken down into several
// different steps/layers:
//
// * An ordinary overload of `serialize(s,v)` is used to intercept
//   pointer types `T*` and dispatched out to `serializePtr(s,v,(T*)nullptr)`.
//   Passing the additional `T*` argument allows different overloads
//   of `serializePtr` to intercept entire type hierarchies, while
//   still allowing for a fallback case.
//
// * Implementations of `serializePtr` are typically expected to
//   invoke either `serializeUniquePtr` or `serializeSharedPtr`, which
//   handle calling into the `ISerializerImpl` methods with appropriate
//   callbacks.
//
// * The `handleUniquePtr()` or `handleSharedPtr()` operation on
//   `ISerializerImpl` is expected to handle null pointers, or previously-
//   encountered pointers in the shared case, and then invoke the
//   callback to handle things when it can't early-out.
//
// * The callbacks will end up calling `serializeObject(s,v,(T*)nullptr)`,
//   which is another customization point. The default implementation
//   will call `new T()` when reading, so types that need more complicated
//   creation logic should intercept this specialization point.
//
// * An implementation of `serializeObject()` should strive to serialize
//   the bare minimum of members required to actually allocate the object
//   (in the case where serialized data is being read), and then call
//   `deferSerializeObjectContents()` to schedule the remainder of
//   the data to be serialized. Maintaining that policy helps ensure
//   that cycles in the object graph don't create problems.
//
// * `serializeObjectContents()` is the final customization point. By
//   default it simply takes a `T* value` and does `serialize(..., *value)`
//   to serialize the pointed-to `T` value. A custom implementation
//   should serialize whatever members of the object weren't handled
//   as part of the corresponding `serializeObject()` implementation.
//

template<typename S, typename T>
void serializeObjectContents(S const& serializer, T* value, void*)
{
    serialize(serializer, *value);
}

template<typename I, typename C, typename T>
void _serializeObjectContentsCallback(void* valuePtr, void* impl, void* context)
{
    Serializer_<I, C> serializer((I*)impl, (C*)context);
    auto value = (T*)valuePtr;
    serializeObjectContents(serializer, value, (T*)nullptr);
}

template<typename I, typename C, typename T>
void deferSerializeObjectContents(Serializer_<I, C> const& serializer, T* value)
{
    ((Serializer)serializer)
        ->handleDeferredObjectContents(
            value,
            _serializeObjectContentsCallback<I, C, T>,
            serializer.getContext());
}

template<typename S, typename T>
void serializeObject(S const& serializer, T*& value, void*)
{
    if (isReading(serializer))
    {
        value = new T();
    }
    deferSerializeObjectContents(serializer, value);
}

template<typename I, typename C, typename T>
void _serializeObjectCallback(void* valuePtr, void* impl, void* context)
{
    Serializer_<I, C> serializer((I*)impl, (C*)context);
    auto& value = *(T**)valuePtr;
    serializeObject(serializer, value, (T*)nullptr);
}

template<typename I, typename C, typename T>
void serializeSharedPtr(Serializer_<I, C> const& serializer, T*& value)
{
    ((Serializer)serializer)
        ->handleSharedPtr(
            *(void**)&value,
            _serializeObjectCallback<I, C, T>,
            serializer.getContext());
}

template<typename I, typename C, typename T>
void serializeUniquePtr(Serializer_<I, C> const& serializer, T*& value)
{
    ((Serializer)serializer)
        ->handleUniquePtr(
            *(void**)&value,
            _serializeObjectCallback<I, C, T>,
            serializer.getContext());
}

template<typename S, typename T>
void serializePtr(S const& serializer, T*& value, void*)
{
    serializeSharedPtr(serializer, value);
}

template<typename S, typename T>
void serialize(S const& serializer, T*& value)
{
    serializePtr(serializer, value, (T*)nullptr);
}

template<typename S, typename T>
void serialize(S const& serializer, RefPtr<T>& value)
{
    T* raw = value;
    serialize(serializer, raw);
    value = raw;
}

} // namespace Slang

#endif