vibe.data.serialization 9/615(1%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1452
1462
1474
1480
1490
1500
1510
1522
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2052
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3562
3570
3580
3590
3600
3610
3620
3632
3640
3652
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3782
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13650
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16130
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
16440
16450
16460
16470
16480
16490
16500
16510
16520
16530
16540
16550
16560
16570
16580
16590
16600
16610
16620
16630
16640
16650
16660
16670
16680
16690
16700
16710
16720
16730
16740
16750
16760
16770
16780
16790
16800
16810
16820
16830
16840
16850
16860
16870
16880
16890
16900
16910
16920
16930
16940
16950
16960
16970
16980
16990
17000
17010
17020
17030
17040
17050
17060
17070
17080
17090
17100
17110
17120
17130
17140
17150
17160
17170
17180
17190
17200
17210
17220
17230
17240
17250
17260
17270
17280
17290
17300
17310
17320
17330
17340
17350
17360
17370
17380
17390
17400
17410
17420
17430
17440
17450
17460
17470
17480
17490
17500
17510
17520
17530
17540
17550
17560
17570
17580
17590
17600
17610
17620
17630
17640
17650
17660
17670
17680
17690
17700
17710
17720
17730
17740
17750
17760
17770
17780
17790
17800
17810
17820
17830
17840
17850
17860
17870
17880
17890
17900
17910
17920
17930
17940
17950
17960
17970
17980
17990
18000
18010
18020
18030
18040
18050
18060
18070
18080
18090
18100
18110
18120
18130
18140
18150
18160
18170
18180
18190
18200
18210
18220
18230
18240
18250
18260
18270
18280
18290
18300
18310
18320
18330
18340
18350
18360
18370
18380
18390
18400
18410
18420
18430
18440
18450
18460
18470
18480
18490
18500
18510
18520
18530
18540
18550
18560
18570
18580
18590
18600
18610
18620
18630
18640
18650
18660
18670
18680
18690
18700
18710
18720
18730
18740
18750
18760
18770
18780
18790
18800
18810
18820
18830
18840
18850
18860
18870
18880
18890
18900
18910
18920
18930
18940
18950
18960
18970
18980
/** 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 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); 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 (TM.length == 1) { auto vt = __traits(getMember, value, mname); } 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 (isSafeSerializer!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; 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 (MT.length == 1) { __traits(getMember, ret, mname) = 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 (TM.length == 1) { __traits(getMember, ret, mname) = 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); } /** Checks if a given type has an ISO extended string serialization representation. A class or struct type is ISO extended string serializable if it defines a pair of `toISOExtString`/`fromISOExtString` methods. Any class or struct type that has this trait will be serialized by using the return value of it's `toISOExtString` method instead of the original value. This is mainly useful for supporting serialization of the the date/time types in `std.datetime`. This trait has precedence over `isStringSerializable`. */ template isISOExtStringSerializable(T) { enum bool isISOExtStringSerializable = is(typeof(T.init.toISOExtString()) == string) && is(typeof(T.fromISOExtString("")) == T); } /// unittest { import std.datetime; static assert(isISOExtStringSerializable!DateTime); static assert(isISOExtStringSerializable!SysTime); // represented as an ISO extended string when serialized static struct S { // dummy example implementations string toISOExtString() const { return ""; } static S fromISOExtString(string s) { return S.init; } } static assert(isISOExtStringSerializable!S); } /** Checks if a given type has a string serialization representation. A class or struct type is string serializable if it defines a pair of `toString`/`fromString` methods. Any class or struct type that has this trait will be serialized by using the return value of it's `toString` method instead of the original value. */ template isStringSerializable(T) { enum bool isStringSerializable = is(typeof(T.init.toString()) == string) && is(typeof(T.fromString("")) == T); } /// unittest { import std.conv; // represented as a string when serialized static struct S { int value; // dummy example implementations string toString() const { return value.to!string(); } static S fromString(string s) { return S(s.to!int()); } } static assert(isStringSerializable!S); } /** Default policy (performs no customization). */ template DefaultPolicy(T) { } /** Checks if a given policy supports custom serialization for a given type. A class or struct type is custom serializable according to a policy if the policy defines a pair of `toRepresentation`/`fromRepresentation` functions. Any class or struct type that has this trait for the policy supplied to `serializeWithPolicy` will be serialized by using the return value of the policy `toRepresentation` function instead of the original value. This trait has precedence over `isCustomSerializable`, `isISOExtStringSerializable` and `isStringSerializable`. See_Also: `vibe.data.serialization.serializeWithPolicy` */ template isPolicySerializable(alias Policy, T) { enum bool isPolicySerializable = is(typeof(Policy!T.toRepresentation(T.init))) && is(typeof(Policy!T.fromRepresentation(Policy!T.toRepresentation(T.init))) == T); } /// unittest { import std.conv; // represented as the boxed value when serialized static struct Box(T) { T value; } template BoxPol(S) { auto toRepresentation(S s) { return s.value; } S fromRepresentation(typeof(S.init.value) v) { return S(v); } } static assert(isPolicySerializable!(BoxPol, Box!int)); } /** Chains serialization policy. Constructs a serialization policy that given a type `T` will apply the first compatible policy `toRepresentation` and `fromRepresentation` functions. Policies are evaluated left-to-right according to `isPolicySerializable`. See_Also: `vibe.data.serialization.serializeWithPolicy` */ template ChainedPolicy(alias Primary, Fallbacks...) { static if (Fallbacks.length == 0) { alias ChainedPolicy = Primary; } else { alias ChainedPolicy = ChainedPolicy!(ChainedPolicyImpl!(Primary, Fallbacks[0]), Fallbacks[1..$]); } } /// unittest { import std.conv; // To be represented as the boxed value when serialized static struct Box(T) { T value; } // Also to berepresented as the boxed value when serialized, but has // a different way to access the value. static struct Box2(T) { private T v; ref T get() { return v; } } template BoxPol(S) { auto toRepresentation(S s) { return s.value; } S fromRepresentation(typeof(toRepresentation(S.init)) v) { return S(v); } } template Box2Pol(S) { auto toRepresentation(S s) { return s.get(); } S fromRepresentation(typeof(toRepresentation(S.init)) v) { S s; s.get() = v; return s; } } alias ChainPol = ChainedPolicy!(BoxPol, Box2Pol); static assert(!isPolicySerializable!(BoxPol, Box2!int)); static assert(!isPolicySerializable!(Box2Pol, Box!int)); static assert(isPolicySerializable!(ChainPol, Box!int)); static assert(isPolicySerializable!(ChainPol, Box2!int)); } private template ChainedPolicyImpl(alias Primary, alias Fallback) { template Pol(T) { static if (isPolicySerializable!(Primary, T)) { alias toRepresentation = Primary!T.toRepresentation; alias fromRepresentation = Primary!T.fromRepresentation; } else { alias toRepresentation = Fallback!T.toRepresentation; alias fromRepresentation = Fallback!T.fromRepresentation; } } alias ChainedPolicyImpl = Pol; } // heuristically determines @safe'ty of the serializer by testing readValue and writeValue for type int private enum isSafeSerializer(S) = __traits(compiles, (S s) @safe { alias T = Traits!(int, DefaultPolicy); s.writeValue!T(42); s.readValue!(T, int)(); }); private template hasAttribute(T, alias decl) { enum hasAttribute = findFirstUDA!(T, decl).found; } unittest { @asArray int i1; static assert(hasAttribute!(AsArrayAttribute!DefaultPolicy, i1)); int i2; static assert(!hasAttribute!(AsArrayAttribute!DefaultPolicy, i2)); } private template hasPolicyAttribute(alias T, alias POLICY, alias decl) { enum hasPolicyAttribute = hasAttribute!(T!POLICY, decl) || hasAttribute!(T!DefaultPolicy, decl); } unittest { template CP(T) {} @asArray!CP int i1; @asArray int i2; int i3; static assert(hasPolicyAttribute!(AsArrayAttribute, CP, i1)); static assert(hasPolicyAttribute!(AsArrayAttribute, CP, i2)); static assert(!hasPolicyAttribute!(AsArrayAttribute, CP, i3)); static assert(!hasPolicyAttribute!(AsArrayAttribute, DefaultPolicy, i1)); static assert(hasPolicyAttribute!(AsArrayAttribute, DefaultPolicy, i2)); static assert(!hasPolicyAttribute!(AsArrayAttribute, DefaultPolicy, i3)); } private template hasAttributeL(T, ATTRIBUTES...) { static if (ATTRIBUTES.length == 1) { enum hasAttributeL = is(typeof(ATTRIBUTES[0]) == T); } else static if (ATTRIBUTES.length > 1) { enum hasAttributeL = hasAttributeL!(T, ATTRIBUTES[0 .. $/2]) || hasAttributeL!(T, ATTRIBUTES[$/2 .. $]); } else { enum hasAttributeL = false; } } unittest { static assert(hasAttributeL!(AsArrayAttribute!DefaultPolicy, byName, asArray)); static assert(!hasAttributeL!(AsArrayAttribute!DefaultPolicy, byName)); } private template hasPolicyAttributeL(alias T, alias POLICY, ATTRIBUTES...) { enum hasPolicyAttributeL = hasAttributeL!(T!POLICY, ATTRIBUTES) || hasAttributeL!(T!DefaultPolicy, ATTRIBUTES); } private static T getAttribute(TT, string mname, T)(T default_value) { enum val = findFirstUDA!(T, __traits(getMember, TT, mname)); static if (val.found) return val.value; else return default_value; } private static auto getPolicyAttribute(TT, string mname, alias Attribute, alias Policy)(Attribute!DefaultPolicy default_value) { enum val = findFirstUDA!(Attribute!Policy, TypeTuple!(__traits(getMember, TT, mname))[0]); static if (val.found) return val.value; else { enum val2 = findFirstUDA!(Attribute!DefaultPolicy, TypeTuple!(__traits(getMember, TT, mname))[0]); static if (val2.found) return val2.value; else return default_value; } } private string underscoreStrip(string field_name) @safe nothrow @nogc { if( field_name.length < 1 || field_name[$-1] != '_' ) return field_name; else return field_name[0 .. $-1]; } private template hasSerializableFields(T, alias POLICY, size_t idx = 0) { enum hasSerializableFields = SerializableFields!(T, POLICY).length > 0; /*static if (idx < __traits(allMembers, T).length) { enum mname = __traits(allMembers, T)[idx]; static if (!isRWPlainField!(T, mname) && !isRWField!(T, mname)) enum hasSerializableFields = hasSerializableFields!(T, idx+1); else static if (hasAttribute!(IgnoreAttribute, __traits(getMember, T, mname))) enum hasSerializableFields = hasSerializableFields!(T, idx+1); else enum hasSerializableFields = true; } else enum hasSerializableFields = false;*/ } private template SerializableFields(COMPOSITE, alias POLICY) { alias SerializableFields = FilterSerializableFields!(COMPOSITE, POLICY, __traits(allMembers, COMPOSITE)); } private template FilterSerializableFields(COMPOSITE, alias POLICY, FIELDS...) { static if (FIELDS.length > 1) { alias FilterSerializableFields = TypeTuple!( FilterSerializableFields!(COMPOSITE, POLICY, FIELDS[0 .. $/2]), FilterSerializableFields!(COMPOSITE, POLICY, FIELDS[$/2 .. $])); } else static if (FIELDS.length == 1) { alias T = COMPOSITE; enum mname = FIELDS[0]; static if (isRWPlainField!(T, mname) || isRWField!(T, mname)) { alias Tup = TypeTuple!(__traits(getMember, COMPOSITE, FIELDS[0])); static if (Tup.length != 1) { alias FilterSerializableFields = TypeTuple!(mname); } else { static if (!hasPolicyAttribute!(IgnoreAttribute, POLICY, __traits(getMember, T, mname))) { alias FilterSerializableFields = TypeTuple!(mname); } else alias FilterSerializableFields = TypeTuple!(); } } else alias FilterSerializableFields = TypeTuple!(); } else alias FilterSerializableFields = TypeTuple!(); } private size_t getExpandedFieldCount(T, FIELDS...)() { size_t ret = 0; foreach (F; FIELDS) ret += TypeTuple!(__traits(getMember, T, F)).length; return ret; } private template getExpandedFieldsData(T, FIELDS...) { import std.meta : aliasSeqOf, staticMap; import std.range : repeat, zip, iota; enum subfieldsCount(alias F) = TypeTuple!(__traits(getMember, T, F)).length; alias processSubfield(alias F) = aliasSeqOf!(zip(repeat(F), iota(subfieldsCount!F))); alias getExpandedFieldsData = staticMap!(processSubfield, FIELDS); } /******************************************************************************/ /* General serialization unit testing */ /******************************************************************************/ version (unittest) { static assert(isSafeSerializer!TestSerializer); private struct TestSerializer { import std.array, std.conv, std.string; string result; enum isSupportedValueType(T) = is(T == string) || is(T == typeof(null)) || is(T == float) || is (T == int); string getSerializedResult() @safe { return result; } void beginWriteDictionary(Traits)() { result ~= "D("~Traits.Type.mangleof~"){"; } void endWriteDictionary(Traits)() { result ~= "}D("~Traits.Type.mangleof~")"; } void beginWriteDictionaryEntry(Traits)(string name) { result ~= "DE("~Traits.Type.mangleof~","~name~")("; } void endWriteDictionaryEntry(Traits)(string name) { result ~= ")DE("~Traits.Type.mangleof~","~name~")"; } void beginWriteArray(Traits)(size_t length) { result ~= "A("~Traits.Type.mangleof~")["~length.to!string~"]["; } void endWriteArray(Traits)() { result ~= "]A("~Traits.Type.mangleof~")"; } void beginWriteArrayEntry(Traits)(size_t i) { result ~= "AE("~Traits.Type.mangleof~","~i.to!string~")("; } void endWriteArrayEntry(Traits)(size_t i) { result ~= ")AE("~Traits.Type.mangleof~","~i.to!string~")"; } void writeValue(Traits, T)(T value) { if (is(T == typeof(null))) result ~= "null"; else { assert(isSupportedValueType!T); result ~= "V("~T.mangleof~")("~value.to!string~")"; } } // deserialization void readDictionary(Traits)(scope void delegate(string) @safe entry_callback) { skip("D("~Traits.Type.mangleof~"){"); while (result.startsWith("DE(")) { result = result[3 .. $]; auto idx = result.indexOf(','); auto idx2 = result.indexOf(")("); assert(idx > 0 && idx2 > idx); auto t = result[0 .. idx]; auto n = result[idx+1 .. idx2]; result = result[idx2+2 .. $]; entry_callback(n); skip(")DE("~t~","~n~")"); } skip("}D("~Traits.Type.mangleof~")"); } void beginReadDictionaryEntry(Traits)(string name) {} void endReadDictionaryEntry(Traits)(string name) {} void readArray(Traits)(scope void delegate(size_t) @safe size_callback, scope void delegate() @safe entry_callback) { skip("A("~Traits.Type.mangleof~")["); auto bidx = result.indexOf("]["); assert(bidx > 0); auto cnt = result[0 .. bidx].to!size_t; result = result[bidx+2 .. $]; size_t i = 0; while (result.startsWith("AE(")) { result = result[3 .. $]; auto idx = result.indexOf(','); auto idx2 = result.indexOf(")("); assert(idx > 0 && idx2 > idx); auto t = result[0 .. idx]; auto n = result[idx+1 .. idx2]; result = result[idx2+2 .. $]; assert(n == i.to!string); entry_callback(); skip(")AE("~t~","~n~")"); i++; } skip("]A("~Traits.Type.mangleof~")"); assert(i == cnt); } void beginReadArrayEntry(Traits)(size_t index) {} void endReadArrayEntry(Traits)(size_t index) {} T readValue(Traits, T)() { skip("V("~T.mangleof~")("); auto idx = result.indexOf(')'); assert(idx >= 0); auto ret = result[0 .. idx].to!T; result = result[idx+1 .. $]; return ret; } void skip(string prefix) @safe { assert(result.startsWith(prefix), prefix ~ " vs. " ~result); result = result[prefix.length .. $]; } bool tryReadNull(Traits)() { if (result.startsWith("null")) { result = result[4 .. $]; return true; } else return false; } } } unittest { // basic serialization behavior import std.typecons : Nullable; static void test(T)(T value, string expected) { assert(serialize!TestSerializer(value) == expected, serialize!TestSerializer(value)); static if (isPointer!T) { if (value) assert(*deserialize!(TestSerializer, T)(expected) == *value); else assert(deserialize!(TestSerializer, T)(expected) is null); } else static if (is(T == Nullable!U, U)) { if (value.isNull()) assert(deserialize!(TestSerializer, T)(expected).isNull); else assert(deserialize!(TestSerializer, T)(expected) == value); } else assert(deserialize!(TestSerializer, T)(expected) == value); } test("hello", "V(Aya)(hello)"); test(12, "V(i)(12)"); test(12.0, "V(Aya)(12)"); test(12.0f, "V(f)(12)"); assert(serialize!TestSerializer(null) == "null"); test(["hello", "world"], "A(AAya)[2][AE(Aya,0)(V(Aya)(hello))AE(Aya,0)AE(Aya,1)(V(Aya)(world))AE(Aya,1)]A(AAya)"); string mangleOfAA = (string[string]).mangleof; test(["hello": "world"], "D(" ~ mangleOfAA ~ "){DE(Aya,hello)(V(Aya)(world))DE(Aya,hello)}D(" ~ mangleOfAA ~ ")"); test(cast(int*)null, "null"); int i = 42; test(&i, "V(i)(42)"); Nullable!int j; test(j, "null"); j = 42; test(j, "V(i)(42)"); } unittest { // basic user defined types static struct S { string f; } enum Sm = S.mangleof; auto s = S("hello"); enum s_ser = "D("~Sm~"){DE(Aya,f)(V(Aya)(hello))DE(Aya,f)}D("~Sm~")"; assert(serialize!TestSerializer(s) == s_ser, serialize!TestSerializer(s)); assert(deserialize!(TestSerializer, S)(s_ser) == s); static class C { string f; } enum Cm = C.mangleof; C c; assert(serialize!TestSerializer(c) == "null"); c = new C; c.f = "hello"; enum c_ser = "D("~Cm~"){DE(Aya,f)(V(Aya)(hello))DE(Aya,f)}D("~Cm~")"; assert(serialize!TestSerializer(c) == c_ser); assert(deserialize!(TestSerializer, C)(c_ser).f == c.f); enum E { hello, world } assert(serialize!TestSerializer(E.hello) == "V(i)(0)"); assert(serialize!TestSerializer(E.world) == "V(i)(1)"); } unittest { // tuple serialization import std.typecons : Tuple; static struct S(T...) { T f; } enum Sm = S!(int, string).mangleof; enum Tum = Tuple!(int, string).mangleof; const s = S!(int, string)(42, "hello"); const ss = serialize!TestSerializer(s); const es = "D("~Sm~"){DE("~Tum~",f)(A("~Tum~")[2][AE(i,0)(V(i)(42))AE(i,0)AE(Aya,1)(V(Aya)(hello))AE(Aya,1)]A("~Tum~"))DE("~Tum~",f)}D("~Sm~")"; assert(ss == es); const dss = deserialize!(TestSerializer, typeof(s))(ss); assert(dss == s); static struct T { @asArray S!(int, string) g; } enum Tm = T.mangleof; const t = T(s); const st = serialize!TestSerializer(t); const et = "D("~Tm~"){DE("~Sm~",g)(A("~Sm~")[2][AE(i,0)(V(i)(42))AE(i,0)AE(Aya,1)(V(Aya)(hello))AE(Aya,1)]A("~Sm~"))DE("~Sm~",g)}D("~Tm~")"; assert(st == et); const dst = deserialize!(TestSerializer, typeof(t))(st); assert(dst == t); } unittest { // named tuple serialization import std.typecons : tuple; static struct I { int i; } static struct S { int x; string s_; } static struct T { @asArray typeof(tuple!(FieldNameTuple!I)(I.init.tupleof)) tuple1AsArray; @name(fullyQualifiedName!I) typeof(tuple!(FieldNameTuple!I)(I.init.tupleof)) tuple1AsDictionary; @asArray typeof(tuple!(FieldNameTuple!S)(S.init.tupleof)) tuple2AsArray; @name(fullyQualifiedName!S) typeof(tuple!(FieldNameTuple!S)(S.init.tupleof)) tuple2AsDictionary; } const i = I(42); const s = S(42, "hello"); const T t = { i.tupleof, i.tupleof, s.tupleof, s.tupleof }; const st = serialize!TestSerializer(t); enum Tm = T.mangleof; enum TuIm = typeof(T.tuple1AsArray).mangleof; enum TuSm = typeof(T.tuple2AsArray).mangleof; const et = "D("~Tm~")"~ "{"~ "DE("~TuIm~",tuple1AsArray)"~ "("~ "V(i)(42)"~ ")"~ "DE("~TuIm~",tuple1AsArray)"~ "DE("~TuIm~","~fullyQualifiedName!I~")"~ "("~ "D("~TuIm~")"~ "{"~ "DE(i,i)"~ "("~ "V(i)(42)"~ ")"~ "DE(i,i)"~ "}"~ "D("~TuIm~")"~ ")"~ "DE("~TuIm~","~fullyQualifiedName!I~")"~ "DE("~TuSm~",tuple2AsArray)"~ "("~ "A("~TuSm~")[2]"~ "["~ "AE(i,0)"~ "("~ "V(i)(42)"~ ")"~ "AE(i,0)"~ "AE(Aya,1)"~ "("~ "V(Aya)(hello)"~ ")"~ "AE(Aya,1)"~ "]"~ "A("~TuSm~")"~ ")"~ "DE("~TuSm~",tuple2AsArray)"~ "DE("~TuSm~","~fullyQualifiedName!S~")"~ "("~ "D("~TuSm~")"~ "{"~ "DE(i,x)"~ "("~ "V(i)(42)"~ ")"~ "DE(i,x)"~ "DE(Aya,s)"~ "("~ "V(Aya)(hello)"~ ")"~ "DE(Aya,s)"~ "}"~ "D("~TuSm~")"~ ")"~ "DE("~TuSm~","~fullyQualifiedName!S~")"~ "}"~ "D("~Tm~")"; assert(st == et); const dst = deserialize!(TestSerializer, typeof(t))(st); assert(dst == t); } unittest { // testing the various UDAs enum E { hello, world } enum Em = E.mangleof; static struct S { @byName E e; @ignore int i; @optional float f; } enum Sm = S.mangleof; auto s = S(E.world, 42, 1.0f); assert(serialize!TestSerializer(s) == "D("~Sm~"){DE("~Em~",e)(V(Aya)(world))DE("~Em~",e)DE(f,f)(V(f)(1))DE(f,f)}D("~Sm~")"); } unittest { // custom serialization support // iso-ext import std.datetime; auto t = TimeOfDay(6, 31, 23); assert(serialize!TestSerializer(t) == "V(Aya)(06:31:23)"); auto d = Date(1964, 1, 23); assert(serialize!TestSerializer(d) == "V(Aya)(1964-01-23)"); auto dt = DateTime(d, t); assert(serialize!TestSerializer(dt) == "V(Aya)(1964-01-23T06:31:23)"); auto st = SysTime(dt, UTC()); assert(serialize!TestSerializer(st) == "V(Aya)(1964-01-23T06:31:23Z)"); } @safe unittest { // custom serialization support // string static struct S1 { int i; string toString() const @safe { return "hello"; } static S1 fromString(string) @safe { return S1.init; } } static struct S2 { int i; string toString() const { return "hello"; } } enum S2m = S2.mangleof; static struct S3 { int i; static S3 fromString(string) { return S3.init; } } enum S3m = S3.mangleof; assert(serialize!TestSerializer(S1.init) == "V(Aya)(hello)"); assert(serialize!TestSerializer(S2.init) == "D("~S2m~"){DE(i,i)(V(i)(0))DE(i,i)}D("~S2m~")"); assert(serialize!TestSerializer(S3.init) == "D("~S3m~"){DE(i,i)(V(i)(0))DE(i,i)}D("~S3m~")"); // custom static struct C1 { int i; float toRepresentation() const @safe { return 1.0f; } static C1 fromRepresentation(float f) @safe { return C1.init; } } static struct C2 { int i; float toRepresentation() const { return 1.0f; } } enum C2m = C2.mangleof; static struct C3 { int i; static C3 fromRepresentation(float f) { return C3.init; } } enum C3m = C3.mangleof; assert(serialize!TestSerializer(C1.init) == "V(f)(1)"); assert(serialize!TestSerializer(C2.init) == "D("~C2m~"){DE(i,i)(V(i)(0))DE(i,i)}D("~C2m~")"); assert(serialize!TestSerializer(C3.init) == "D("~C3m~"){DE(i,i)(V(i)(0))DE(i,i)}D("~C3m~")"); } unittest // Testing corner case: member function returning by ref { import vibe.data.json; static struct S { int i; ref int foo() { return i; } } static assert(__traits(compiles, { S().serializeToJson(); })); static assert(__traits(compiles, { Json().deserializeJson!S(); })); auto s = S(1); assert(s.serializeToJson().deserializeJson!S() == s); } unittest // Testing corner case: Variadic template constructors and methods { import vibe.data.json; static struct S { int i; this(Args...)(Args args) {} int foo(Args...)(Args args) { return i; } ref int bar(Args...)(Args args) { return i; } } static assert(__traits(compiles, { S().serializeToJson(); })); static assert(__traits(compiles, { Json().deserializeJson!S(); })); auto s = S(1); assert(s.serializeToJson().deserializeJson!S() == s); } @safe unittest // Make sure serializing through properties still works { import vibe.data.json; static struct S { @safe: public int i; private int privateJ; @property int j() @safe { return privateJ; } @property void j(int j) @safe { privateJ = j; } } auto s = S(1, 2); assert(s.serializeToJson().deserializeJson!S() == s); } @safe unittest // Immutable data deserialization { import vibe.data.json; static struct S { int a; } static class C { immutable(S)[] arr; } auto c = new C; c.arr ~= S(10); auto d = c.serializeToJson().deserializeJson!(immutable C); static assert(is(typeof(d) == immutable C)); assert(d.arr == c.arr); } unittest { // test BitFlags serialization import std.typecons : BitFlags; enum Flag { a = 1<<0, b = 1<<1, c = 1<<2 } enum Flagm = Flag.mangleof; alias Flags = BitFlags!Flag; enum Flagsm = Flags.mangleof; enum Fi_ser = "A("~Flagsm~")[0][]A("~Flagsm~")"; assert(serialize!TestSerializer(Flags.init) == Fi_ser); enum Fac_ser = "A("~Flagsm~")[2][AE("~Flagm~",0)(V(i)(1))AE("~Flagm~",0)AE("~Flagm~",1)(V(i)(4))AE("~Flagm~",1)]A("~Flagsm~")"; assert(serialize!TestSerializer(Flags(Flag.a, Flag.c)) == Fac_ser); struct S { @byName Flags f; } enum Sm = S.mangleof; enum Sac_ser = "D("~Sm~"){DE("~Flagsm~",f)(A("~Flagsm~")[2][AE("~Flagm~",0)(V(Aya)(a))AE("~Flagm~",0)AE("~Flagm~",1)(V(Aya)(c))AE("~Flagm~",1)]A("~Flagsm~"))DE("~Flagsm~",f)}D("~Sm~")"; assert(serialize!TestSerializer(S(Flags(Flag.a, Flag.c))) == Sac_ser); assert(deserialize!(TestSerializer, Flags)(Fi_ser) == Flags.init); assert(deserialize!(TestSerializer, Flags)(Fac_ser) == Flags(Flag.a, Flag.c)); assert(deserialize!(TestSerializer, S)(Sac_ser) == S(Flags(Flag.a, Flag.c))); } @safe unittest { // issue #1182 struct T { int x; string y; } struct S { @asArray T t; } auto s = S(T(42, "foo")); enum Sm = S.mangleof; enum Tm = T.mangleof; enum s_ser = "D("~Sm~"){DE("~Tm~",t)(A("~Tm~")[2][AE(i,0)(V(i)(42))AE(i,0)AE(Aya,1)(V(Aya)(foo))AE(Aya,1)]A("~Tm~"))DE("~Tm~",t)}D("~Sm~")"; auto serialized = serialize!TestSerializer(s); assert(serialized == s_ser, serialized); assert(deserialize!(TestSerializer, S)(serialized) == s); } @safe unittest { // issue #1352 - ingore per policy struct P1 {} struct P2 {} struct T { @ignore int a = 5; @ignore!P1 @ignore!P2 int b = 6; @ignore!P1 c = 7; int d = 8; } auto t = T(1, 2, 3, 4); auto Tm = T.mangleof; auto t_ser_plain = "D("~Tm~"){DE(i,b)(V(i)(2))DE(i,b)DE(i,c)(V(i)(3))DE(i,c)DE(i,d)(V(i)(4))DE(i,d)}D("~Tm~")"; auto t_ser_p1 = "D("~Tm~"){DE(i,d)(V(i)(4))DE(i,d)}D("~Tm~")"; auto t_ser_p2 = "D("~Tm~"){DE(i,c)(V(i)(3))DE(i,c)DE(i,d)(V(i)(4))DE(i,d)}D("~Tm~")"; { auto serialized_plain = serialize!TestSerializer(t); assert(serialized_plain == t_ser_plain); assert(deserialize!(TestSerializer, T)(serialized_plain) == T(5, 2, 3, 4)); } { auto serialized_p1 = serializeWithPolicy!(TestSerializer, P1)(t); assert(serialized_p1 == t_ser_p1, serialized_p1); assert(deserializeWithPolicy!(TestSerializer, P1, T)(serialized_p1) == T(5, 6, 7, 4)); } { auto serialized_p2 = serializeWithPolicy!(TestSerializer, P2)(t); assert(serialized_p2 == t_ser_p2); assert(deserializeWithPolicy!(TestSerializer, P2, T)(serialized_p2) == T(5, 6, 3, 4)); } } unittest { import std.conv : to; import std.string : toLower, toUpper; template P(T) if (is(T == enum)) { @safe: static string toRepresentation(T v) { return v.to!string.toLower(); } static T fromRepresentation(string str) { return str.toUpper().to!T; } } enum E { RED, GREEN } assert(P!E.fromRepresentation("green") == E.GREEN); static assert(isPolicySerializable!(P, E)); auto ser_red = "V(Aya)(red)"; assert(serializeWithPolicy!(TestSerializer, P)(E.RED) == ser_red, serializeWithPolicy!(TestSerializer, P)(E.RED)); assert(deserializeWithPolicy!(TestSerializer, P, E)(ser_red) == E.RED); import vibe.data.json : Json, JsonSerializer; assert(serializeWithPolicy!(JsonSerializer, P)(E.RED) == Json("red")); } unittest { static struct R { int y; } static struct Custom { @safe: int x; R toRepresentation() const { return R(x); } static Custom fromRepresentation(R r) { return Custom(r.y); } } auto c = Custom(42); auto Rn = R.mangleof; auto ser = serialize!TestSerializer(c); assert(ser == "D("~Rn~"){DE(i,y)(V(i)(42))DE(i,y)}D("~Rn~")"); auto deser = deserialize!(TestSerializer, Custom)(ser); assert(deser.x == 42); } unittest { import std.typecons : Typedef; alias T = Typedef!int; auto ser = serialize!TestSerializer(T(42)); assert(ser == "V(i)(42)", ser); auto deser = deserialize!(TestSerializer, T)(ser); assert(deser == 42); } @safe unittest { static struct Foo { Foo[] foos; } Foo f; string ser = serialize!TestSerializer(f); assert(deserialize!(TestSerializer, Foo)(ser) == f); } @system unittest { static struct SystemSerializer { TestSerializer ser; alias ser this; this(string s) { ser.result = s; } T readValue(Traits, T)() @system { return ser.readValue!(Traits, T); } void writeValue(Traits, T)(T value) @system { ser.writeValue!(Traits, T)(value); } void readDictionary(Traits)(scope void delegate(string) @system entry_callback) { ser.readDictionary!Traits((s) @trusted { entry_callback(s); }); } void readArray(Traits)(scope void delegate(size_t) @system size_callback, scope void delegate() @system entry_callback) { ser.readArray!Traits((s) @trusted { size_callback(s); }, () @trusted { entry_callback(); }); } } static struct Bar { Bar[] foos; int i; } Bar f; string ser = serialize!SystemSerializer(f); assert(deserialize!(SystemSerializer, Bar)(ser) == f); } @safe unittest { static struct S { @name("+foo") int bar; } auto Sn = S.mangleof; auto s = S(42); string ser = serialize!TestSerializer(s); assert(ser == "D("~Sn~"){DE(i,+foo)(V(i)(42))DE(i,+foo)}D("~Sn~")", ser); auto deser = deserialize!(TestSerializer, S)(ser); assert(deser.bar == 42); } @safe unittest { static struct S { int bar_; } auto Sn = S.mangleof; auto s = S(42); string ser = serialize!TestSerializer(s); assert(ser == "D("~Sn~"){DE(i,bar)(V(i)(42))DE(i,bar)}D("~Sn~")", ser); auto deser = deserialize!(TestSerializer, S)(ser); assert(deser.bar_ == 42); }