forked from vibe-d/vibe.d
/
serialization.d
1981 lines (1731 loc) · 62.8 KB
/
serialization.d
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
/**
Generic serialization framework.
This module provides general means for implementing (de-)serialization with
a standardized behavior.
Supported_types:
The following rules are applied in order when serializing or
deserializing a certain type:
$(OL
$(LI An `enum` type is serialized as its raw value, except if
`@byName` is used, in which case the name of the enum value
is serialized.)
$(LI Any type that is specifically supported by the serializer
is directly serialized. For example, the BSON serializer
supports `BsonObjectID` directly.)
$(LI Arrays and tuples (`std.typecons.Tuple`) are serialized
using the array serialization functions where each element is
serialized again according to these rules.)
$(LI Associative arrays are serialized similar to arrays. The key
type of the AA must satisfy the `isStringSerializable` trait
and will always be serialized as a string.)
$(LI Any `Nullable!T` will be serialized as either `null`, or
as the contained value (subject to these rules again).)
$(LI Any `Typedef!T` will be serialized as if it were just `T`.)
$(LI Any `BitFlags!T` value will be serialized as `T[]`)
$(LI Types satisfying the `isPolicySerializable` trait for the
supplied `Policy` will be serialized as the value returned
by the policy `toRepresentation` function (again subject to
these rules).)
$(LI Types satisfying the `isCustomSerializable` trait will be
serialized as the value returned by their `toRepresentation`
method (again subject to these rules).)
$(LI Types satisfying the `isISOExtStringSerializable` trait will be
serialized as a string, as returned by their `toISOExtString`
method. This causes types such as `SysTime` to be serialized
as strings.)
$(LI Types satisfying the `isStringSerializable` trait will be
serialized as a string, as returned by their `toString`
method.)
$(LI Struct and class types by default will be serialized as
associative arrays, where the key is the name of the
corresponding field (can be overridden using the `@name`
attribute). If the struct/class is annotated with `@asArray`,
it will instead be serialized as a flat array of values in the
order of declaration. Null class references will be serialized
as `null`.)
$(LI Pointer types will be serialized as either `null`, or as
the value they point to.)
$(LI Built-in integers and floating point values, as well as
boolean values will be converted to strings, if the serializer
doesn't support them directly.)
)
Note that no aliasing detection is performed, so that pointers, class
references and arrays referencing the same memory will be serialized
as multiple copies. When in turn deserializing the data, they will also
end up as separate copies in memory.
Field_names:
By default, the field name of the serialized D type (for `struct` and
`class` aggregates) is represented as-is in the serialized result. To
circumvent name clashes with D's keywords, a single trailing underscore of
any field name is stipped, so that a field name of `version_` results in
just `"version"` as the serialized value. Names can also be freely
customized using the `@name` annotation.
Associative array keys are always represented using their direct string
representation.
Serializer_implementation:
Serializers are implemented in terms of a struct with template methods that
get called by the serialization framework:
---
struct ExampleSerializer {
enum isSupportedValueType(T) = is(T == string) || is(T == typeof(null));
// serialization
auto getSerializedResult();
void beginWriteDocument(TypeTraits)();
void endWriteDocument(TypeTraits)();
void beginWriteDictionary(TypeTraits)();
void endWriteDictionary(TypeTraits)();
void beginWriteDictionaryEntry(ElementTypeTraits)(string name);
void endWriteDictionaryEntry(ElementTypeTraits)(string name);
void beginWriteArray(TypeTraits)(size_t length);
void endWriteArray(TypeTraits)();
void beginWriteArrayEntry(ElementTypeTraits)(size_t index);
void endWriteArrayEntry(ElementTypeTraits)(size_t index);
void writeValue(TypeTraits, T)(T value);
// deserialization
void readDictionary(TypeTraits)(scope void delegate(string) entry_callback);
void beginReadDictionaryEntry(ElementTypeTraits)(string);
void endReadDictionaryEntry(ElementTypeTraits)(string);
void readArray(TypeTraits)(scope void delegate(size_t) size_callback, scope void delegate() entry_callback);
void beginReadArrayEntry(ElementTypeTraits)(size_t index);
void endReadArrayEntry(ElementTypeTraits)(size_t index);
T readValue(TypeTraits, T)();
bool tryReadNull(TypeTraits)();
}
---
The `TypeTraits` type passed to the individual methods has the following members:
$(UL
$(LI `Type`: The original type of the field to serialize)
$(LI `Attributes`: User defined attributes attached to the field)
$(LI `Policy`: An alias to the policy used for the serialization process)
)
`ElementTypeTraits` have the following additional members:
$(UL
$(LI `ContainerType`: The original type of the enclosing container type)
$(LI `ContainerAttributes`: User defined attributes attached to the enclosing container)
)
Copyright: © 2013-2016 rejectedsoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.data.serialization;
import vibe.internal.meta.traits;
import vibe.internal.meta.uda;
import std.array : Appender, appender;
import std.conv : to;
import std.exception : enforce;
import std.traits;
import std.typetuple;
/**
Serializes a value with the given serializer.
The serializer must have a value result for the first form
to work. Otherwise, use the range based form.
See_Also: `vibe.data.json.JsonSerializer`, `vibe.data.json.JsonStringSerializer`, `vibe.data.bson.BsonSerializer`
*/
auto serialize(Serializer, T, ARGS...)(T value, ARGS args)
{
auto serializer = Serializer(args);
serialize(serializer, value);
return serializer.getSerializedResult();
}
/// ditto
void serialize(Serializer, T)(ref Serializer serializer, T value)
{
serializeWithPolicy!(Serializer, DefaultPolicy)(serializer, value);
}
/** Note that there is a convenience function `vibe.data.json.serializeToJson`
that can be used instead of manually invoking `serialize`.
*/
unittest {
import vibe.data.json;
struct Test {
int value;
string text;
}
Test test;
test.value = 12;
test.text = "Hello";
Json serialized = serialize!JsonSerializer(test);
assert(serialized["value"].get!int == 12);
assert(serialized["text"].get!string == "Hello");
}
unittest {
import vibe.data.json;
// Make sure that immutable(char[]) works just like string
// (i.e., immutable(char)[]).
immutable key = "answer";
auto ints = [key: 42];
auto serialized = serialize!JsonSerializer(ints);
assert(serialized[key].get!int == 42);
}
/**
Serializes a value with the given serializer, representing values according to `Policy` when possible.
The serializer must have a value result for the first form
to work. Otherwise, use the range based form.
See_Also: `vibe.data.json.JsonSerializer`, `vibe.data.json.JsonStringSerializer`, `vibe.data.bson.BsonSerializer`
*/
auto serializeWithPolicy(Serializer, alias Policy, T, ARGS...)(T value, ARGS args)
{
auto serializer = Serializer(args);
serializeWithPolicy!(Serializer, Policy)(serializer, value);
return serializer.getSerializedResult();
}
/// ditto
void serializeWithPolicy(Serializer, alias Policy, T)(ref Serializer serializer, T value)
{
static if (is(typeof(serializer.beginWriteDocument!T())))
serializer.beginWriteDocument!T();
serializeValueImpl!(Serializer, Policy).serializeValue!T(serializer, value);
static if (is(typeof(serializer.endWriteDocument!T())))
serializer.endWriteDocument!T();
}
///
version (unittest)
{
}
///
unittest {
import vibe.data.json;
template SizePol(T)
if (__traits(allMembers, T) == TypeTuple!("x", "y"))
{
import std.conv;
import std.array;
static string toRepresentation(T value) @safe {
return to!string(value.x) ~ "x" ~ to!string(value.y);
}
static T fromRepresentation(string value) {
string[] fields = value.split('x');
alias fieldT = typeof(T.x);
auto x = to!fieldT(fields[0]);
auto y = to!fieldT(fields[1]);
return T(x, y);
}
}
static struct SizeI {
int x;
int y;
}
SizeI sizeI = SizeI(1,2);
Json serializedI = serializeWithPolicy!(JsonSerializer, SizePol)(sizeI);
assert(serializedI.get!string == "1x2");
static struct SizeF {
float x;
float y;
}
SizeF sizeF = SizeF(0.1f,0.2f);
Json serializedF = serializeWithPolicy!(JsonSerializer, SizePol)(sizeF);
assert(serializedF.get!string == "0.1x0.2");
}
/**
Deserializes and returns a serialized value.
serialized_data can be either an input range or a value containing
the serialized data, depending on the type of serializer used.
See_Also: `vibe.data.json.JsonSerializer`, `vibe.data.json.JsonStringSerializer`, `vibe.data.bson.BsonSerializer`
*/
T deserialize(Serializer, T, ARGS...)(ARGS args)
{
return deserializeWithPolicy!(Serializer, DefaultPolicy, T)(args);
}
/** Note that there is a convenience function `vibe.data.json.deserializeJson`
that can be used instead of manually invoking `deserialize`.
*/
unittest {
import vibe.data.json;
struct Test {
int value;
string text;
}
Json serialized = Json.emptyObject;
serialized["value"] = 12;
serialized["text"] = "Hello";
Test test = deserialize!(JsonSerializer, Test)(serialized);
assert(test.value == 12);
assert(test.text == "Hello");
}
/**
Deserializes and returns a serialized value, interpreting values according to `Policy` when possible.
serialized_data can be either an input range or a value containing
the serialized data, depending on the type of serializer used.
See_Also: `vibe.data.json.JsonSerializer`, `vibe.data.json.JsonStringSerializer`, `vibe.data.bson.BsonSerializer`
*/
T deserializeWithPolicy(Serializer, alias Policy, T, ARGS...)(ARGS args)
{
auto deserializer = Serializer(args);
return deserializeValueImpl!(Serializer, Policy).deserializeValue!T(deserializer);
}
///
unittest {
import vibe.data.json;
template SizePol(T)
if (__traits(allMembers, T) == TypeTuple!("x", "y"))
{
import std.conv;
import std.array;
static string toRepresentation(T value)
@safe {
return to!string(value.x) ~ "x" ~ to!string(value.y);
}
static T fromRepresentation(string value)
@safe {
string[] fields = value.split('x');
alias fieldT = typeof(T.x);
auto x = to!fieldT(fields[0]);
auto y = to!fieldT(fields[1]);
return T(x, y);
}
}
static struct SizeI {
int x;
int y;
}
Json serializedI = "1x2";
SizeI sizeI = deserializeWithPolicy!(JsonSerializer, SizePol, SizeI)(serializedI);
assert(sizeI.x == 1);
assert(sizeI.y == 2);
static struct SizeF {
float x;
float y;
}
Json serializedF = "0.1x0.2";
SizeF sizeF = deserializeWithPolicy!(JsonSerializer, SizePol, SizeF)(serializedF);
assert(sizeF.x == 0.1f);
assert(sizeF.y == 0.2f);
}
private template serializeValueImpl(Serializer, alias Policy) {
alias _Policy = Policy;
static assert(Serializer.isSupportedValueType!string, "All serializers must support string values.");
static assert(Serializer.isSupportedValueType!(typeof(null)), "All serializers must support null values.");
// work around https://issues.dlang.org/show_bug.cgi?id=16528
static if (isSafeSerializer!Serializer) {
void serializeValue(T, ATTRIBUTES...)(ref Serializer ser, T value) @safe { serializeValueDeduced!(T, ATTRIBUTES)(ser, value); }
} else {
void serializeValue(T, ATTRIBUTES...)(ref Serializer ser, T value) { serializeValueDeduced!(T, ATTRIBUTES)(ser, value); }
}
private void serializeValueDeduced(T, ATTRIBUTES...)(ref Serializer ser, T value)
{
import std.typecons : BitFlags, Nullable, Tuple, Typedef, TypedefType, tuple;
alias TU = Unqual!T;
alias Traits = .Traits!(TU, _Policy, ATTRIBUTES);
static if (isPolicySerializable!(Policy, TU)) {
alias CustomType = typeof(Policy!TU.toRepresentation(TU.init));
ser.serializeValue!(CustomType, ATTRIBUTES)(Policy!TU.toRepresentation(value));
} else static if (is(TU == enum)) {
static if (hasPolicyAttributeL!(ByNameAttribute, Policy, ATTRIBUTES)) {
ser.serializeValue!(string)(value.to!string());
} else {
ser.serializeValue!(OriginalType!TU)(cast(OriginalType!TU)value);
}
} else static if (Serializer.isSupportedValueType!TU) {
static if (is(TU == typeof(null))) ser.writeValue!Traits(null);
else ser.writeValue!(Traits, TU)(value);
} else static if (/*isInstanceOf!(Tuple, TU)*/is(T == Tuple!TPS, TPS...)) {
import std.algorithm.searching: all;
static if (all!"!a.empty"([TU.fieldNames]) &&
!hasPolicyAttributeL!(AsArrayAttribute, Policy, ATTRIBUTES)) {
static if (__traits(compiles, ser.beginWriteDictionary!TU(0))) {
auto nfields = value.length;
ser.beginWriteDictionary!Traits(nfields);
} else {
ser.beginWriteDictionary!Traits();
}
foreach (i, TV; TU.Types) {
alias STraits = SubTraits!(Traits, TV);
ser.beginWriteDictionaryEntry!STraits(underscoreStrip(TU.fieldNames[i]));
ser.serializeValue!(TV, ATTRIBUTES)(value[i]);
ser.endWriteDictionaryEntry!STraits(underscoreStrip(TU.fieldNames[i]));
}
static if (__traits(compiles, ser.endWriteDictionary!TU(0))) {
ser.endWriteDictionary!Traits(nfields);
} else {
ser.endWriteDictionary!Traits();
}
} else static if (TU.Types.length == 1) {
ser.serializeValue!(typeof(value[0]), ATTRIBUTES)(value[0]);
} else {
ser.beginWriteArray!Traits(value.length);
foreach (i, TV; T.Types) {
alias STraits = SubTraits!(Traits, TV);
ser.beginWriteArrayEntry!STraits(i);
ser.serializeValue!(TV, ATTRIBUTES)(value[i]);
ser.endWriteArrayEntry!STraits(i);
}
ser.endWriteArray!Traits();
}
} else static if (isArray!TU) {
alias TV = typeof(value[0]);
alias STraits = SubTraits!(Traits, TV);
ser.beginWriteArray!Traits(value.length);
foreach (i, ref el; value) {
ser.beginWriteArrayEntry!STraits(i);
ser.serializeValue!(TV, ATTRIBUTES)(el);
ser.endWriteArrayEntry!STraits(i);
}
ser.endWriteArray!Traits();
} else static if (isAssociativeArray!TU) {
alias TK = KeyType!TU;
alias TV = ValueType!TU;
alias STraits = SubTraits!(Traits, TV);
static if (__traits(compiles, ser.beginWriteDictionary!TU(0))) {
auto nfields = value.length;
ser.beginWriteDictionary!Traits(nfields);
} else {
ser.beginWriteDictionary!Traits();
}
foreach (key, ref el; value) {
string keyname;
static if (is(TK : string)) keyname = key;
else static if (is(TK : real) || is(TK : long) || is(TK == enum)) keyname = key.to!string;
else static if (isStringSerializable!TK) keyname = key.toString();
else static assert(false, "Associative array keys must be strings, numbers, enums, or have toString/fromString methods.");
ser.beginWriteDictionaryEntry!STraits(keyname);
ser.serializeValue!(TV, ATTRIBUTES)(el);
ser.endWriteDictionaryEntry!STraits(keyname);
}
static if (__traits(compiles, ser.endWriteDictionary!TU(0))) {
ser.endWriteDictionary!Traits(nfields);
} else {
ser.endWriteDictionary!Traits();
}
} else static if (/*isInstanceOf!(Nullable, TU)*/is(T == Nullable!TPS, TPS...)) {
if (value.isNull()) ser.serializeValue!(typeof(null))(null);
else ser.serializeValue!(typeof(value.get()), ATTRIBUTES)(value.get());
} else static if (isInstanceOf!(Typedef, TU)) {
ser.serializeValue!(TypedefType!TU, ATTRIBUTES)(cast(TypedefType!TU)value);
} else static if (is(TU == BitFlags!E, E)) {
alias STraits = SubTraits!(Traits, E);
size_t cnt = 0;
foreach (v; EnumMembers!E)
if (value & v)
cnt++;
ser.beginWriteArray!Traits(cnt);
cnt = 0;
foreach (v; EnumMembers!E)
if (value & v) {
ser.beginWriteArrayEntry!STraits(cnt);
ser.serializeValue!(E, ATTRIBUTES)(v);
ser.endWriteArrayEntry!STraits(cnt);
cnt++;
}
ser.endWriteArray!Traits();
} else static if (isCustomSerializable!TU) {
alias CustomType = typeof(T.init.toRepresentation());
ser.serializeValue!(CustomType, ATTRIBUTES)(value.toRepresentation());
} else static if (isISOExtStringSerializable!TU) {
ser.serializeValue!(string, ATTRIBUTES)(value.toISOExtString());
} else static if (isStringSerializable!TU) {
ser.serializeValue!(string, ATTRIBUTES)(value.toString());
} else static if (is(TU == struct) || is(TU == class)) {
static if (!hasSerializableFields!(TU, Policy))
pragma(msg, "Serializing composite type "~T.stringof~" which has no serializable fields");
static if (is(TU == class)) {
if (value is null) {
ser.serializeValue!(typeof(null))(null);
return;
}
}
static auto safeGetMember(string mname)(ref T val) @safe {
static if (__traits(compiles, __traits(getMember, val, mname))) {
return __traits(getMember, val, mname);
} else {
pragma(msg, "Warning: Getter for "~fullyQualifiedName!T~"."~mname~" is not @safe");
return () @trusted { return __traits(getMember, val, mname); } ();
}
}
static if (hasPolicyAttributeL!(AsArrayAttribute, Policy, ATTRIBUTES)) {
enum nfields = getExpandedFieldCount!(TU, SerializableFields!(TU, Policy));
ser.beginWriteArray!Traits(nfields);
size_t fcount = 0;
foreach (mname; SerializableFields!(TU, Policy)) {
alias TMS = TypeTuple!(typeof(__traits(getMember, value, mname)));
foreach (j, TM; TMS) {
alias TA = TypeTuple!(__traits(getAttributes, TypeTuple!(__traits(getMember, T, mname))[j]));
alias STraits = SubTraits!(Traits, TM, TA);
ser.beginWriteArrayEntry!STraits(fcount);
static if (!isBuiltinTuple!(T, mname))
ser.serializeValue!(TM, TA)(safeGetMember!mname(value));
else
ser.serializeValue!(TM, TA)(tuple(__traits(getMember, value, mname))[j]);
ser.endWriteArrayEntry!STraits(fcount);
fcount++;
}
}
ser.endWriteArray!Traits();
} else {
static if (__traits(compiles, ser.beginWriteDictionary!Traits(0))) {
enum nfields = getExpandedFieldCount!(TU, SerializableFields!(TU, Policy));
ser.beginWriteDictionary!Traits(nfields);
} else {
ser.beginWriteDictionary!Traits();
}
foreach (mname; SerializableFields!(TU, Policy)) {
alias TM = TypeTuple!(typeof(__traits(getMember, TU, mname)));
alias TA = TypeTuple!(__traits(getAttributes, TypeTuple!(__traits(getMember, T, mname))[0]));
enum name = getPolicyAttribute!(TU, mname, NameAttribute, Policy)(NameAttribute!DefaultPolicy(underscoreStrip(mname))).name;
static if (!isBuiltinTuple!(T, mname)) {
auto vt = safeGetMember!mname(value);
} else {
auto vt = tuple!TM(__traits(getMember, value, mname));
}
alias STraits = SubTraits!(Traits, typeof(vt), TA);
ser.beginWriteDictionaryEntry!STraits(name);
ser.serializeValue!(typeof(vt), TA)(vt);
ser.endWriteDictionaryEntry!STraits(name);
}
static if (__traits(compiles, ser.endWriteDictionary!Traits(0))) {
ser.endWriteDictionary!Traits(nfields);
} else {
ser.endWriteDictionary!Traits();
}
}
} else static if (isPointer!TU) {
if (value is null) {
ser.writeValue!Traits(null);
return;
}
ser.serializeValue!(PointerTarget!TU)(*value);
} else static if (is(TU == bool) || is(TU : real) || is(TU : long)) {
ser.serializeValue!(string, ATTRIBUTES)(to!string(value));
} else static assert(false, "Unsupported serialization type: " ~ T.stringof);
}
}
private struct Traits(T, alias POL, ATTRIBUTES...)
{
alias Type = T;
alias Policy = POL;
alias Attributes = TypeTuple!ATTRIBUTES;
}
private struct SubTraits(Traits, T, A...)
{
alias Type = Unqual!T;
alias Attributes = TypeTuple!A;
alias Policy = Traits.Policy;
alias ContainerType = Traits.Type;
alias ContainerAttributes = Traits.Attributes;
}
private template deserializeValueImpl(Serializer, alias Policy) {
alias _Policy = Policy;
static assert(Serializer.isSupportedValueType!string, "All serializers must support string values.");
static assert(Serializer.isSupportedValueType!(typeof(null)), "All serializers must support null values.");
// work around https://issues.dlang.org/show_bug.cgi?id=16528
static if (isSafeDeserializer!Serializer) {
T deserializeValue(T, ATTRIBUTES...)(ref Serializer ser) @safe { return deserializeValueDeduced!(T, ATTRIBUTES)(ser); }
} else {
T deserializeValue(T, ATTRIBUTES...)(ref Serializer ser) { return deserializeValueDeduced!(T, ATTRIBUTES)(ser); }
}
T deserializeValueDeduced(T, ATTRIBUTES...)(ref Serializer ser) if(!isMutable!T)
{
import std.algorithm.mutation : move;
auto ret = deserializeValue!(Unqual!T, ATTRIBUTES)(ser);
return () @trusted { return cast(T)ret.move; } ();
}
T deserializeValueDeduced(T, ATTRIBUTES...)(ref Serializer ser) if(isMutable!T)
{
import std.typecons : BitFlags, Nullable, Typedef, TypedefType, Tuple;
alias Traits = .Traits!(T, _Policy, ATTRIBUTES);
static if (isPolicySerializable!(Policy, T)) {
alias CustomType = typeof(Policy!T.toRepresentation(T.init));
return Policy!T.fromRepresentation(ser.deserializeValue!(CustomType, ATTRIBUTES));
} else static if (is(T == enum)) {
static if (hasPolicyAttributeL!(ByNameAttribute, Policy, ATTRIBUTES)) {
return ser.deserializeValue!(string, ATTRIBUTES).to!T();
} else {
return cast(T)ser.deserializeValue!(OriginalType!T);
}
} else static if (Serializer.isSupportedValueType!T) {
return ser.readValue!(Traits, T)();
} else static if (/*isInstanceOf!(Tuple, TU)*/is(T == Tuple!TPS, TPS...)) {
enum fieldsCount = T.Types.length;
import std.algorithm.searching: all;
static if (all!"!a.empty"([T.fieldNames]) &&
!hasPolicyAttributeL!(AsArrayAttribute, Policy, ATTRIBUTES)) {
T ret;
bool[fieldsCount] set;
ser.readDictionary!Traits((name) {
switch (name) {
default: break;
foreach (i, TV; T.Types) {
enum fieldName = underscoreStrip(T.fieldNames[i]);
alias STraits = SubTraits!(Traits, TV);
case fieldName: {
ser.beginReadDictionaryEntry!STraits(fieldName);
ret[i] = ser.deserializeValue!(TV, ATTRIBUTES);
ser.endReadDictionaryEntry!STraits(fieldName);
set[i] = true;
} break;
}
}
});
foreach (i, fieldName; T.fieldNames)
enforce(set[i], "Missing tuple field '"~fieldName~"' of type '"~T.Types[i].stringof~"' ("~Policy.stringof~").");
return ret;
} else static if (fieldsCount == 1) {
return T(ser.deserializeValue!(T.Types[0], ATTRIBUTES)());
} else {
T ret;
size_t currentField = 0;
ser.readArray!Traits((sz) { assert(sz == 0 || sz == fieldsCount); }, {
switch (currentField++) {
default: break;
foreach (i, TV; T.Types) {
alias STraits = SubTraits!(Traits, TV);
case i: {
ser.beginReadArrayEntry!STraits(i);
ret[i] = ser.deserializeValue!(TV, ATTRIBUTES);
ser.endReadArrayEntry!STraits(i);
} break;
}
}
});
enforce(currentField == fieldsCount, "Missing tuple field(s) - expected '"~fieldsCount.stringof~"', received '"~currentField.stringof~"' ("~Policy.stringof~").");
return ret;
}
} else static if (isStaticArray!T) {
alias TV = typeof(T.init[0]);
alias STraits = SubTraits!(Traits, TV);
T ret;
size_t i = 0;
ser.readArray!Traits((sz) { assert(sz == 0 || sz == T.length); }, {
assert(i < T.length);
ser.beginReadArrayEntry!STraits(i);
ret[i] = ser.deserializeValue!(TV, ATTRIBUTES);
ser.endReadArrayEntry!STraits(i);
i++;
});
return ret;
} else static if (isDynamicArray!T) {
alias TV = typeof(T.init[0]);
alias STraits = SubTraits!(Traits, TV);
//auto ret = appender!T();
T ret; // Cannot use appender because of DMD BUG 10690/10859/11357
ser.readArray!Traits((sz) @safe { ret.reserve(sz); }, () @safe {
size_t i = ret.length;
ser.beginReadArrayEntry!STraits(i);
static if (__traits(compiles, () @safe { ser.deserializeValue!(TV, ATTRIBUTES); }))
ret ~= ser.deserializeValue!(TV, ATTRIBUTES);
else // recursive array https://issues.dlang.org/show_bug.cgi?id=16528
ret ~= (() @trusted => ser.deserializeValue!(TV, ATTRIBUTES))();
ser.endReadArrayEntry!STraits(i);
});
return ret;//cast(T)ret.data;
} else static if (isAssociativeArray!T) {
alias TK = KeyType!T;
alias TV = ValueType!T;
alias STraits = SubTraits!(Traits, TV);
T ret;
ser.readDictionary!Traits((name) @safe {
TK key;
static if (is(TK == string) || (is(TK == enum) && is(OriginalType!TK == string))) key = cast(TK)name;
else static if (is(TK : real) || is(TK : long) || is(TK == enum)) key = name.to!TK;
else static if (isStringSerializable!TK) key = TK.fromString(name);
else static assert(false, "Associative array keys must be strings, numbers, enums, or have toString/fromString methods.");
ser.beginReadDictionaryEntry!STraits(name);
ret[key] = ser.deserializeValue!(TV, ATTRIBUTES);
ser.endReadDictionaryEntry!STraits(name);
});
return ret;
} else static if (isInstanceOf!(Nullable, T)) {
if (ser.tryReadNull!Traits()) return T.init;
return T(ser.deserializeValue!(typeof(T.init.get()), ATTRIBUTES));
} else static if (isInstanceOf!(Typedef, T)) {
return T(ser.deserializeValue!(TypedefType!T, ATTRIBUTES));
} else static if (is(T == BitFlags!E, E)) {
alias STraits = SubTraits!(Traits, E);
T ret;
size_t i = 0;
ser.readArray!Traits((sz) {}, {
ser.beginReadArrayEntry!STraits(i);
ret |= ser.deserializeValue!(E, ATTRIBUTES);
ser.endReadArrayEntry!STraits(i);
i++;
});
return ret;
} else static if (isCustomSerializable!T) {
alias CustomType = typeof(T.init.toRepresentation());
return T.fromRepresentation(ser.deserializeValue!(CustomType, ATTRIBUTES));
} else static if (isISOExtStringSerializable!T) {
return T.fromISOExtString(ser.readValue!(Traits, string)());
} else static if (isStringSerializable!T) {
return T.fromString(ser.readValue!(Traits, string)());
} else static if (is(T == struct) || is(T == class)) {
static if (is(T == class)) {
if (ser.tryReadNull!Traits()) return null;
}
T ret;
string name;
bool[getExpandedFieldsData!(T, SerializableFields!(T, Policy)).length] set;
static if (is(T == class)) ret = new T;
void safeSetMember(string mname, U)(ref T value, U fval)
@safe {
static if (__traits(compiles, () @safe { __traits(getMember, value, mname) = fval; }))
__traits(getMember, value, mname) = fval;
else {
pragma(msg, "Warning: Setter for "~fullyQualifiedName!T~"."~mname~" is not @safe");
() @trusted { __traits(getMember, value, mname) = fval; } ();
}
}
static if (hasPolicyAttributeL!(AsArrayAttribute, Policy, ATTRIBUTES)) {
size_t idx = 0;
ser.readArray!Traits((sz){}, {
static if (hasSerializableFields!(T, Policy)) {
switch (idx++) {
default: break;
foreach (i, FD; getExpandedFieldsData!(T, SerializableFields!(T, Policy))) {
enum mname = FD[0];
enum msindex = FD[1];
alias MT = TypeTuple!(__traits(getMember, T, mname));
alias MTI = MT[msindex];
alias TMTI = typeof(MTI);
alias TMTIA = TypeTuple!(__traits(getAttributes, MTI));
alias STraits = SubTraits!(Traits, TMTI, TMTIA);
case i:
static if (hasPolicyAttribute!(OptionalAttribute, Policy, MTI))
if (ser.tryReadNull!STraits()) return;
set[i] = true;
ser.beginReadArrayEntry!STraits(i);
static if (!isBuiltinTuple!(T, mname)) {
safeSetMember!mname(ret, ser.deserializeValue!(TMTI, TMTIA));
} else {
__traits(getMember, ret, mname)[msindex] = ser.deserializeValue!(TMTI, TMTIA);
}
ser.endReadArrayEntry!STraits(i);
break;
}
}
} else {
pragma(msg, "Deserializing composite type "~T.stringof~" which has no serializable fields.");
}
});
} else {
ser.readDictionary!Traits((name) {
static if (hasSerializableFields!(T, Policy)) {
switch (name) {
default: break;
foreach (i, mname; SerializableFields!(T, Policy)) {
alias TM = TypeTuple!(typeof(__traits(getMember, T, mname)));
alias TA = TypeTuple!(__traits(getAttributes, TypeTuple!(__traits(getMember, T, mname))[0]));
alias STraits = SubTraits!(Traits, TM, TA);
enum fname = getPolicyAttribute!(T, mname, NameAttribute, Policy)(NameAttribute!DefaultPolicy(underscoreStrip(mname))).name;
case fname:
static if (hasPolicyAttribute!(OptionalAttribute, Policy, TypeTuple!(__traits(getMember, T, mname))[0]))
if (ser.tryReadNull!STraits()) return;
set[i] = true;
ser.beginReadDictionaryEntry!STraits(fname);
static if (!isBuiltinTuple!(T, mname)) {
safeSetMember!mname(ret, ser.deserializeValue!(TM, TA));
} else {
__traits(getMember, ret, mname) = ser.deserializeValue!(Tuple!TM, TA);
}
ser.endReadDictionaryEntry!STraits(fname);
break;
}
}
} else {
pragma(msg, "Deserializing composite type "~T.stringof~" which has no serializable fields.");
}
});
}
foreach (i, mname; SerializableFields!(T, Policy))
static if (!hasPolicyAttribute!(OptionalAttribute, Policy, TypeTuple!(__traits(getMember, T, mname))[0]))
enforce(set[i], "Missing non-optional field '"~mname~"' of type '"~T.stringof~"' ("~Policy.stringof~").");
return ret;
} else static if (isPointer!T) {
if (ser.tryReadNull!Traits()) return null;
alias PT = PointerTarget!T;
auto ret = new PT;
*ret = ser.deserializeValue!(PT, ATTRIBUTES);
return ret;
} else static if (is(T == bool) || is(T : real) || is(T : long)) {
return to!T(ser.deserializeValue!string());
} else static assert(false, "Unsupported serialization type: " ~ T.stringof);
}
}
/**
Attribute for overriding the field name during (de-)serialization.
Note that without the `@name` attribute there is a shorter alternative
for using names that collide with a D keyword. A single trailing
underscore will automatically be stripped when determining a field
name.
*/
NameAttribute!Policy name(alias Policy = DefaultPolicy)(string name)
{
return NameAttribute!Policy(name);
}
///
unittest {
struct CustomPolicy {}
struct Test {
// serialized as "screen-size":
@name("screen-size") int screenSize;
// serialized as "print-size" by default,
// but as "PRINTSIZE" if CustomPolicy is used for serialization.
@name("print-size")
@name!CustomPolicy("PRINTSIZE")
int printSize;
// serialized as "version"
int version_;
}
}
/**
Attribute marking a field as optional during deserialization.
*/
@property OptionalAttribute!Policy optional(alias Policy = DefaultPolicy)()
{
return OptionalAttribute!Policy();
}
///
unittest {
struct Test {
// does not need to be present during deserialization
@optional int screenSize = 100;
}
}
/**
Attribute for marking non-serialized fields.
*/
@property IgnoreAttribute!Policy ignore(alias Policy = DefaultPolicy)()
{
return IgnoreAttribute!Policy();
}
///
unittest {
struct Test {
// is neither serialized not deserialized
@ignore int screenSize;
}
}
///
unittest {
template CustomPolicy(T) {
// ...
}
struct Test {
// not (de)serialized for serializeWithPolicy!(Test, CustomPolicy)
// but for other policies or when serialized without a policy
@ignore!CustomPolicy int screenSize;
}
}
/**
Attribute for forcing serialization of enum fields by name instead of by value.
*/
@property ByNameAttribute!Policy byName(alias Policy = DefaultPolicy)()
{
return ByNameAttribute!Policy();
}
///
unittest {
enum Color {
red,
green,
blue
}
struct Test {
// serialized as an int (e.g. 1 for Color.green)
Color color;
// serialized as a string (e.g. "green" for Color.green)
@byName Color namedColor;
// serialized as array of ints
Color[] colorArray;
// serialized as array of strings
@byName Color[] namedColorArray;
}
}
/**
Attribute for representing a struct/class as an array instead of an object.
Usually structs and class objects are serialized as dictionaries mapping
from field name to value. Using this attribute, they will be serialized
as a flat array instead. Note that changing the layout will make any
already serialized data mismatch when this attribute is used.
*/
@property AsArrayAttribute!Policy asArray(alias Policy = DefaultPolicy)()
{
return AsArrayAttribute!Policy();
}
///
unittest {
struct Fields {
int f1;
string f2;
double f3;
}
struct Test {
// serialized as name:value pairs ["f1": int, "f2": string, "f3": double]
Fields object;
// serialized as a sequential list of values [int, string, double]
@asArray Fields array;
}
import vibe.data.json;
static assert(is(typeof(serializeToJson(Test()))));
}
///
enum FieldExistence
{
missing,
exists,
defer
}
/// User defined attribute (not intended for direct use)
struct NameAttribute(alias POLICY) { alias Policy = POLICY; string name; }
/// ditto
struct OptionalAttribute(alias POLICY) { alias Policy = POLICY; }
/// ditto
struct IgnoreAttribute(alias POLICY) { alias Policy = POLICY; }
/// ditto
struct ByNameAttribute(alias POLICY) { alias Policy = POLICY; }
/// ditto
struct AsArrayAttribute(alias POLICY) { alias Policy = POLICY; }
/**
Checks if a given type has a custom serialization representation.
A class or struct type is custom serializable if it defines a pair of
`toRepresentation`/`fromRepresentation` methods. Any class or
struct type that has this trait will be serialized by using the return
value of it's `toRepresentation` method instead of the original value.
This trait has precedence over `isISOExtStringSerializable` and
`isStringSerializable`.
*/
template isCustomSerializable(T)
{
enum bool isCustomSerializable = is(typeof(T.init.toRepresentation())) && is(typeof(T.fromRepresentation(T.init.toRepresentation())) == T);
}
///
unittest {
// represented as a single uint when serialized
static struct S {
ushort x, y;
uint toRepresentation() const { return x + (y << 16); }
static S fromRepresentation(uint i) { return S(i & 0xFFFF, i >> 16); }
}
static assert(isCustomSerializable!S);
}