vibe.data.bson 3/689(0%) 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
1450
1460
1470
1480
1490
1500
1510
1520
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
2050
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
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
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
8301
8311
8320
8330
8340
8350
8360
8371
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
/** BSON serialization and value handling. Copyright: © 2012-2015 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.bson; /// unittest { void manipulateBson(Bson b) { import std.stdio; // retrieving the values is done using get() assert(b["name"].get!string == "Example"); assert(b["id"].get!int == 1); // semantic conversions can be done using to() assert(b["id"].to!string == "1"); // prints: // name: "Example" // id: 1 foreach (string key, value; b) writefln("%s: %s", key, value); // print out with JSON syntax: {"name": "Example", "id": 1} writefln("BSON: %s", b.toString()); // DEPRECATED: object members can be accessed using member syntax, just like in JavaScript //j = Bson.emptyObject; //j.name = "Example"; //j.id = 1; } } /// Constructing `Bson` objects unittest { // construct a BSON object {"field1": "foo", "field2": 42, "field3": true} // using the constructor Bson b1 = Bson(["field1": Bson("foo"), "field2": Bson(42), "field3": Bson(true)]); // using piecewise construction Bson b2 = Bson.emptyObject; b2["field1"] = "foo"; b2["field2"] = 42; b2["field3"] = true; // using serialization struct S { string field1; int field2; bool field3; } Bson b3 = S("foo", 42, true).serializeToBson(); } public import vibe.data.json; import std.algorithm; import std.array; import std.base64; import std.bitmanip; import std.conv; import std.datetime; import std.uuid: UUID; import std.exception; import std.range; import std.traits; import std.typecons : Tuple, tuple; alias bdata_t = immutable(ubyte)[]; /** Represents a BSON value. */ struct Bson { @safe: /// Represents the type of a BSON value enum Type : ubyte { end = 0x00, /// End marker - should never occur explicitly double_ = 0x01, /// A 64-bit floating point value string = 0x02, /// A UTF-8 string object = 0x03, /// An object aka. dictionary of string to Bson array = 0x04, /// An array of BSON values binData = 0x05, /// Raw binary data (ubyte[]) undefined = 0x06, /// Deprecated objectID = 0x07, /// BSON Object ID (96-bit) bool_ = 0x08, /// Boolean value date = 0x09, /// Date value (UTC) null_ = 0x0A, /// Null value regex = 0x0B, /// Regular expression dbRef = 0x0C, /// Deprecated code = 0x0D, /// JaveScript code symbol = 0x0E, /// Symbol/variable name codeWScope = 0x0F, /// JavaScript code with scope int_ = 0x10, /// 32-bit integer timestamp = 0x11, /// Timestamp value long_ = 0x12, /// 64-bit integer minKey = 0xff, /// Internal value maxKey = 0x7f, /// Internal value End = end, /// Compatibility alias - will be deprecated soon. Double = double_, /// Compatibility alias - will be deprecated soon. String = string, /// Compatibility alias - will be deprecated soon. Object = object, /// Compatibility alias - will be deprecated soon. Array = array, /// Compatibility alias - will be deprecated soon. BinData = binData, /// Compatibility alias - will be deprecated soon. Undefined = undefined, /// Compatibility alias - will be deprecated soon. ObjectID = objectID, /// Compatibility alias - will be deprecated soon. Bool = bool_, /// Compatibility alias - will be deprecated soon. Date = date, /// Compatibility alias - will be deprecated soon. Null = null_, /// Compatibility alias - will be deprecated soon. Regex = regex, /// Compatibility alias - will be deprecated soon. DBRef = dbRef, /// Compatibility alias - will be deprecated soon. Code = code, /// Compatibility alias - will be deprecated soon. Symbol = symbol, /// Compatibility alias - will be deprecated soon. CodeWScope = codeWScope, /// Compatibility alias - will be deprecated soon. Int = int_, /// Compatibility alias - will be deprecated soon. Timestamp = timestamp, /// Compatibility alias - will be deprecated soon. Long = long_, /// Compatibility alias - will be deprecated soon. MinKey = minKey, /// Compatibility alias - will be deprecated soon. MaxKey = maxKey /// Compatibility alias - will be deprecated soon. } /// Returns a new, empty Bson value of type Object. static @property Bson emptyObject() { return Bson(cast(Bson[string])null); } /// Returns a new, empty Bson value of type Array. static @property Bson emptyArray() { return Bson(cast(Bson[])null); } private { Type m_type = Type.undefined; bdata_t m_data; } /** Creates a new BSON value using raw data. A slice of the first bytes of `data` is stored, containg the data related to the value. An exception is thrown if `data` is too short. */ this(Type type, bdata_t data) { m_type = type; m_data = data; final switch(type){ case Type.end: m_data = null; break; case Type.double_: m_data = m_data[0 .. 8]; break; case Type.string: m_data = m_data[0 .. 4 + fromBsonData!int(m_data)]; break; case Type.object: m_data = m_data[0 .. fromBsonData!int(m_data)]; break; case Type.array: m_data = m_data[0 .. fromBsonData!int(m_data)]; break; case Type.binData: m_data = m_data[0 .. 5 + fromBsonData!int(m_data)]; break; case Type.undefined: m_data = null; break; case Type.objectID: m_data = m_data[0 .. 12]; break; case Type.bool_: m_data = m_data[0 .. 1]; break; case Type.date: m_data = m_data[0 .. 8]; break; case Type.null_: m_data = null; break; case Type.regex: auto tmp = m_data; tmp.skipCString(); tmp.skipCString(); m_data = m_data[0 .. $ - tmp.length]; break; case Type.dbRef: m_data = m_data[0 .. 0]; assert(false, "Not implemented."); case Type.code: m_data = m_data[0 .. 4 + fromBsonData!int(m_data)]; break; case Type.symbol: m_data = m_data[0 .. 4 + fromBsonData!int(m_data)]; break; case Type.codeWScope: m_data = m_data[0 .. 0]; assert(false, "Not implemented."); case Type.int_: m_data = m_data[0 .. 4]; break; case Type.timestamp: m_data = m_data[0 .. 8]; break; case Type.long_: m_data = m_data[0 .. 8]; break; case Type.minKey: m_data = null; break; case Type.maxKey: m_data = null; break; } } /** Initializes a new BSON value from the given D type. */ this(double value) { opAssign(value); } /// ditto this(string value, Type type = Type.string) { assert(type == Type.string || type == Type.code || type == Type.symbol); opAssign(value); m_type = type; } /// ditto this(in Bson[string] value) { opAssign(value); } /// ditto this(in Bson[] value) { opAssign(value); } /// ditto this(in BsonBinData value) { opAssign(value); } /// ditto this(in BsonObjectID value) { opAssign(value); } /// ditto this(bool value) { opAssign(value); } /// ditto this(in BsonDate value) { opAssign(value); } /// ditto this(typeof(null)) { opAssign(null); } /// ditto this(in BsonRegex value) { opAssign(value); } /// ditto this(int value) { opAssign(value); } /// ditto this(in BsonTimestamp value) { opAssign(value); } /// ditto this(long value) { opAssign(value); } /// ditto this(in Json value) { opAssign(value); } /// ditto this(in UUID value) { opAssign(value); } /** Assigns a D type to a BSON value. */ void opAssign(in Bson other) { m_data = other.m_data; m_type = other.m_type; } /// ditto void opAssign(double value) { m_data = toBsonData(value).idup; m_type = Type.double_; } /// ditto void opAssign(string value) { import std.utf; debug std.utf.validate(value); auto app = appender!bdata_t(); app.put(toBsonData(cast(int)value.length+1)); app.put(cast(bdata_t)value); app.put(cast(ubyte)0); m_data = app.data; m_type = Type.string; } /// ditto void opAssign(in Bson[string] value) { auto app = appender!bdata_t(); foreach( k, ref v; value ){ app.put(cast(ubyte)v.type); putCString(app, k); app.put(v.data); } auto dapp = appender!bdata_t(); dapp.put(toBsonData(cast(int)app.data.length+5)); dapp.put(app.data); dapp.put(cast(ubyte)0); m_data = dapp.data; m_type = Type.object; } /// ditto void opAssign(in Bson[] value) { auto app = appender!bdata_t(); foreach( i, ref v; value ){ app.put(v.type); putCString(app, to!string(i)); app.put(v.data); } auto dapp = appender!bdata_t(); dapp.put(toBsonData(cast(int)app.data.length+5)); dapp.put(app.data); dapp.put(cast(ubyte)0); m_data = dapp.data; m_type = Type.array; } /// ditto void opAssign(in BsonBinData value) { auto app = appender!bdata_t(); app.put(toBsonData(cast(int)value.rawData.length)); app.put(value.type); app.put(value.rawData); m_data = app.data; m_type = Type.binData; } /// ditto void opAssign(in BsonObjectID value) { m_data = value.m_bytes.idup; m_type = Type.objectID; } /// ditto void opAssign(bool value) { m_data = [value ? 0x01 : 0x00]; m_type = Type.bool_; } /// ditto void opAssign(in BsonDate value) { m_data = toBsonData(value.m_time).idup; m_type = Type.date; } /// ditto void opAssign(typeof(null)) { m_data = null; m_type = Type.null_; } /// ditto void opAssign(in BsonRegex value) { auto app = appender!bdata_t(); putCString(app, value.expression); putCString(app, value.options); m_data = app.data; m_type = type.regex; } /// ditto void opAssign(int value) { m_data = toBsonData(value).idup; m_type = Type.int_; } /// ditto void opAssign(in BsonTimestamp value) { m_data = toBsonData(value.m_time).idup; m_type = Type.timestamp; } /// ditto void opAssign(long value) { m_data = toBsonData(value).idup; m_type = Type.long_; } /// ditto void opAssign(in Json value) @trusted { auto app = appender!bdata_t(); m_type = writeBson(app, value); m_data = app.data; } /// ditto void opAssign(in UUID value) { opAssign(BsonBinData(BsonBinData.Type.uuid, value.data.idup)); } /** Returns the BSON type of this value. */ @property Type type() const { return m_type; } bool isNull() const { return m_type == Type.null_; } /** Returns the raw data representing this BSON value (not including the field name and type). */ @property bdata_t data() const { return m_data; } /** Converts the BSON value to a D value. If the BSON type of the value does not match the D type, an exception is thrown. See_Also: `deserializeBson`, `opt` */ T opCast(T)() const { return get!T(); } /// ditto @property T get(T)() const { static if( is(T == double) ){ checkType(Type.double_); return fromBsonData!double(m_data); } else static if( is(T == string) ){ checkType(Type.string, Type.code, Type.symbol); return cast(string)m_data[4 .. 4+fromBsonData!int(m_data)-1]; } else static if( is(Unqual!T == Bson[string]) || is(Unqual!T == const(Bson)[string]) ){ checkType(Type.object); Bson[string] ret; auto d = m_data[4 .. $]; while( d.length > 0 ){ auto tp = cast(Type)d[0]; if( tp == Type.end ) break; d = d[1 .. $]; auto key = skipCString(d); auto value = Bson(tp, d); d = d[value.data.length .. $]; ret[key] = value; } return cast(T)ret; } else static if( is(Unqual!T == Bson[]) || is(Unqual!T == const(Bson)[]) ){ checkType(Type.array); Bson[] ret; auto d = m_data[4 .. $]; while( d.length > 0 ){ auto tp = cast(Type)d[0]; if( tp == Type.end ) break; /*auto key = */skipCString(d); // should be '0', '1', ... auto value = Bson(tp, d); d = d[value.data.length .. $]; ret ~= value; } return cast(T)ret; } else static if( is(T == BsonBinData) ){ checkType(Type.binData); auto size = fromBsonData!int(m_data); auto type = cast(BsonBinData.Type)m_data[4]; return BsonBinData(type, m_data[5 .. 5+size]); } else static if( is(T == BsonObjectID) ){ checkType(Type.objectID); return BsonObjectID(m_data[0 .. 12]); } else static if( is(T == bool) ){ checkType(Type.bool_); return m_data[0] != 0; } else static if( is(T == BsonDate) ){ checkType(Type.date); return BsonDate(fromBsonData!long(m_data)); } else static if( is(T == BsonRegex) ){ checkType(Type.regex); auto d = m_data; auto expr = skipCString(d); auto options = skipCString(d); return BsonRegex(expr, options); } else static if( is(T == int) ){ checkType(Type.int_); return fromBsonData!int(m_data); } else static if( is(T == BsonTimestamp) ){ checkType(Type.timestamp); return BsonTimestamp(fromBsonData!long(m_data)); } else static if( is(T == long) ){ checkType(Type.long_); return fromBsonData!long(m_data); } else static if( is(T == Json) ){ pragma(msg, "Bson.get!Json() and Bson.opCast!Json() will soon be removed. Please use Bson.toJson() instead."); return this.toJson(); } else static if( is(T == UUID) ){ checkType(Type.binData); auto bbd = this.get!BsonBinData(); enforce(bbd.type == BsonBinData.Type.uuid, "BsonBinData value is type '"~to!string(bbd.type)~"', expected to be uuid"); const ubyte[16] b = bbd.rawData; return UUID(b); } else static assert(false, "Cannot cast "~typeof(this).stringof~" to '"~T.stringof~"'."); } /** Returns the native type for this BSON if it matches the current runtime type. If the runtime type does not match the given native type, the 'def' parameter is returned instead. */ T opt(T)(T def = T.init) { if (isNull()) return def; try return cast(T)this; catch (Exception e) return def; } /// ditto const(T) opt(T)(const(T) def = const(T).init) const { if (isNull()) return def; try return cast(T)this; catch (Exception e) return def; } /** Returns the length of a BSON value of type String, Array, Object or BinData. */ @property size_t length() const { switch( m_type ){ default: enforce(false, "Bson objects of type "~to!string(m_type)~" do not have a length field."); break; case Type.string, Type.code, Type.symbol: return (cast(string)this).length; case Type.array: return byValue.walkLength; case Type.object: return byValue.walkLength; case Type.binData: assert(false); //return (cast(BsonBinData)this).length; break; } assert(false); } /** Converts a given JSON value to the corresponding BSON value. */ static Bson fromJson(in Json value) @trusted { auto app = appender!bdata_t(); auto tp = writeBson(app, value); return Bson(tp, app.data); } /** Converts a BSON value to a JSON value. All BSON types that cannot be exactly represented as JSON, will be converted to a string. */ Json toJson() const { switch( this.type ){ default: assert(false); case Bson.Type.double_: return Json(get!double()); case Bson.Type.string: return Json(get!string()); case Bson.Type.object: Json[string] ret; foreach (k, v; this.byKeyValue) ret[k] = v.toJson(); return Json(ret); case Bson.Type.array: auto ret = new Json[this.length]; foreach (i, v; this.byIndexValue) ret[i] = v.toJson(); return Json(ret); case Bson.Type.binData: return Json(() @trusted { return cast(string)Base64.encode(get!BsonBinData.rawData); } ()); case Bson.Type.objectID: return Json(get!BsonObjectID().toString()); case Bson.Type.bool_: return Json(get!bool()); case Bson.Type.date: return Json(get!BsonDate.toString()); case Bson.Type.null_: return Json(null); case Bson.Type.regex: assert(false, "TODO"); case Bson.Type.dbRef: assert(false, "TODO"); case Bson.Type.code: return Json(get!string()); case Bson.Type.symbol: return Json(get!string()); case Bson.Type.codeWScope: assert(false, "TODO"); case Bson.Type.int_: return Json(get!int()); case Bson.Type.timestamp: return Json(get!BsonTimestamp().m_time); case Bson.Type.long_: return Json(get!long()); case Bson.Type.undefined: return Json(); } } /** Returns a string representation of this BSON value in JSON format. */ string toString() const { return toJson().toString(); } import std.typecons : Nullable; /** Check whether the BSON object contains the given key. */ Nullable!Bson tryIndex(string key) const { checkType(Type.object); foreach (string idx, v; this.byKeyValue) if(idx == key) return Nullable!Bson(v); return Nullable!Bson.init; } /** Allows accessing fields of a BSON object using `[]`. Returns a null value if the specified field does not exist. */ inout(Bson) opIndex(string idx) inout { foreach (string key, v; this.byKeyValue) if( key == idx ) return v; return Bson(null); } /// ditto void opIndexAssign(T)(in T value, string idx){ auto newcont = appender!bdata_t(); checkType(Type.object); auto d = m_data[4 .. $]; while( d.length > 0 ){ auto tp = cast(Type)d[0]; if( tp == Type.end ) break; d = d[1 .. $]; auto key = skipCString(d); auto val = Bson(tp, d); d = d[val.data.length .. $]; if( key != idx ){ // copy to new array newcont.put(cast(ubyte)tp); putCString(newcont, key); newcont.put(val.data); } } static if( is(T == Bson) ) alias bval = value; else auto bval = Bson(value); newcont.put(cast(ubyte)bval.type); putCString(newcont, idx); newcont.put(bval.data); auto newdata = appender!bdata_t(); newdata.put(toBsonData(cast(uint)(newcont.data.length + 5))); newdata.put(newcont.data); newdata.put(cast(ubyte)0); m_data = newdata.data; } /// unittest { Bson value = Bson.emptyObject; value["a"] = 1; value["b"] = true; value["c"] = "foo"; assert(value["a"] == Bson(1)); assert(value["b"] == Bson(true)); assert(value["c"] == Bson("foo")); } /// unittest { auto srcUuid = UUID("00010203-0405-0607-0809-0a0b0c0d0e0f"); Bson b = srcUuid; auto u = b.get!UUID(); assert(b.type == Bson.Type.binData); assert(b.get!BsonBinData().type == BsonBinData.Type.uuid); assert(u == srcUuid); } /** Allows index based access of a BSON array value. Returns a null value if the index is out of bounds. */ inout(Bson) opIndex(size_t idx) inout { foreach (size_t i, v; this.byIndexValue) if (i == idx) return v; return Bson(null); } /// unittest { Bson[] entries; entries ~= Bson(1); entries ~= Bson(true); entries ~= Bson("foo"); Bson value = Bson(entries); assert(value[0] == Bson(1)); assert(value[1] == Bson(true)); assert(value[2] == Bson("foo")); } /** Removes an entry from a BSON obect. If the key doesn't exit, this function will be a no-op. */ void remove(string key) { checkType(Type.object); auto d = m_data[4 .. $]; while (d.length > 0) { size_t start_remainder = d.length; auto tp = cast(Type)d[0]; if (tp == Type.end) break; d = d[1 .. $]; auto ekey = skipCString(d); auto evalue = Bson(tp, d); d = d[evalue.data.length .. $]; if (ekey == key) { m_data = m_data[0 .. $-start_remainder] ~ d; break; } } } unittest { auto o = Bson.emptyObject; o["a"] = Bson(1); o["b"] = Bson(2); o["c"] = Bson(3); assert(o.length == 3); o.remove("b"); assert(o.length == 2); assert(o["a"] == Bson(1)); assert(o["c"] == Bson(3)); o.remove("c"); assert(o.length == 1); assert(o["a"] == Bson(1)); o.remove("c"); assert(o.length == 1); assert(o["a"] == Bson(1)); o.remove("a"); assert(o.length == 0); } /** Allows foreach iterating over BSON objects and arrays. */ int opApply(scope int delegate(Bson obj) del) const @system { foreach (value; byValue) if (auto ret = del(value)) return ret; return 0; } /// ditto int opApply(scope int delegate(size_t idx, Bson obj) del) const @system { foreach (index, value; byIndexValue) if (auto ret = del(index, value)) return ret; return 0; } /// ditto int opApply(scope int delegate(string idx, Bson obj) del) const @system { foreach (key, value; byKeyValue) if (auto ret = del(key, value)) return ret; return 0; } /// Iterates over all values of an object or array. auto byValue() const { checkType(Type.array, Type.object); return byKeyValueImpl().map!(t => t[1]); } /// Iterates over all index/value pairs of an array. auto byIndexValue() const { checkType(Type.array); return byKeyValueImpl().map!(t => Tuple!(size_t, "key", Bson, "value")(t[0].to!size_t, t[1])); } /// Iterates over all key/value pairs of an object. auto byKeyValue() const { checkType(Type.object); return byKeyValueImpl(); } private auto byKeyValueImpl() const { checkType(Type.object, Type.array); alias T = Tuple!(string, "key", Bson, "value"); static struct Rng { private { immutable(ubyte)[] data; string key; Bson value; } @property bool empty() const { return data.length == 0; } @property T front() { return T(key, value); } @property Rng save() const { return this; } void popFront() { auto tp = cast(Type)data[0]; data = data[1 .. $]; if (tp == Type.end) return; key = skipCString(data); value = Bson(tp, data); data = data[value.data.length .. $]; } } auto ret = Rng(m_data[4 .. $]); ret.popFront(); return ret; } /// bool opEquals(ref const Bson other) const { if( m_type != other.m_type ) return false; return m_data == other.m_data; } /// ditto bool opEquals(const Bson other) const { if( m_type != other.m_type ) return false; return m_data == other.m_data; } private void checkType(in Type[] valid_types...) const { foreach( t; valid_types ) if( m_type == t ) return; throw new Exception("BSON value is type '"~to!string(m_type)~"', expected to be one of "~to!string(valid_types)); } } /** Represents a BSON binary data value (Bson.Type.binData). */ struct BsonBinData { @safe: enum Type : ubyte { generic = 0x00, function_ = 0x01, binaryOld = 0x02, uuid = 0x03, md5 = 0x05, userDefined = 0x80, Generic = generic, /// Compatibility alias - will be deprecated soon Function = function_, /// Compatibility alias - will be deprecated soon BinaryOld = binaryOld, /// Compatibility alias - will be deprecated soon UUID = uuid, /// Compatibility alias - will be deprecated soon MD5 = md5, /// Compatibility alias - will be deprecated soon UserDefined = userDefined, /// Compatibility alias - will be deprecated soon } private { Type m_type; bdata_t m_data; } this(Type type, immutable(ubyte)[] data) { m_type = type; m_data = data; } @property Type type() const { return m_type; } @property bdata_t rawData() const { return m_data; } } /** Represents a BSON object id (Bson.Type.binData). */ struct BsonObjectID { @safe: private { ubyte[12] m_bytes; static immutable uint MACHINE_ID; static immutable int ms_pid; static uint ms_inc = 0; } shared static this() { import std.process; import std.random; MACHINE_ID = uniform(0, 0xffffff); ms_pid = thisProcessID; } static this() { import std.random; ms_inc = uniform(0, 0xffffff); } /** Constructs a new object ID from the given raw byte array. */ this(in ubyte[] bytes) { assert(bytes.length == 12); m_bytes[] = bytes[]; } /** Creates an on object ID from a string in standard hexa-decimal form. */ static BsonObjectID fromString(string str) { import std.conv : ConvException; static const lengthex = new ConvException("BSON Object ID string must be 24 characters."); static const charex = new ConvException("Not a valid hex string."); if (str.length != 24) throw lengthex; BsonObjectID ret = void; uint b = 0; foreach( i, ch; str ){ ubyte n; if( ch >= '0' && ch <= '9' ) n = cast(ubyte)(ch - '0'); else if( ch >= 'a' && ch <= 'f' ) n = cast(ubyte)(ch - 'a' + 10); else if( ch >= 'A' && ch <= 'F' ) n = cast(ubyte)(ch - 'F' + 10); else throw charex; b <<= 4; b += n; if( i % 8 == 7 ){ auto j = i / 8; ret.m_bytes[j*4 .. (j+1)*4] = toBigEndianData(b)[]; b = 0; } } return ret; } /// ditto alias fromHexString = fromString; /** Generates a unique object ID. * * By default it will use `Clock.currTime(UTC())` as the timestamp * which guarantees that `BsonObjectID`s are chronologically * sorted. */ static BsonObjectID generate(in SysTime time = Clock.currTime(UTC())) { import std.datetime; BsonObjectID ret = void; ret.m_bytes[0 .. 4] = toBigEndianData(cast(uint)time.toUnixTime())[]; ret.m_bytes[4 .. 7] = toBsonData(MACHINE_ID)[0 .. 3]; ret.m_bytes[7 .. 9] = toBsonData(cast(ushort)ms_pid)[]; ret.m_bytes[9 .. 12] = toBigEndianData(ms_inc++)[1 .. 4]; return ret; } /** Creates a pseudo object ID that matches the given date. This kind of ID can be useful to query a database for items in a certain date interval using their ID. This works using the property of standard BSON object IDs that they store their creation date as part of the ID. Note that this date part is only 32-bit wide and is limited to the same timespan as a 32-bit Unix timestamp. */ static BsonObjectID createDateID(in SysTime time) { BsonObjectID ret; ret.m_bytes[0 .. 4] = toBigEndianData(cast(uint)time.toUnixTime())[]; return ret; } /** Returns true for any non-zero ID. */ @property bool valid() const { foreach( b; m_bytes ) if( b != 0 ) return true; return false; } /** Extracts the time/date portion of the object ID. For IDs created using the standard generation algorithm or using createDateID this will return the associated time stamp. */ @property SysTime timeStamp() const { ubyte[4] tm = m_bytes[0 .. 4]; return SysTime(unixTimeToStdTime(bigEndianToNative!uint(tm))); } /** Allows for relational comparison of different IDs. */ int opCmp(ref const BsonObjectID other) const { import core.stdc.string; return () @trusted { return memcmp(m_bytes.ptr, other.m_bytes.ptr, m_bytes.length); } (); } /** Converts the ID to its standard hexa-decimal string representation. */ string toString() const pure { enum hexdigits = "0123456789abcdef"; auto ret = new char[24]; foreach( i, b; m_bytes ){ ret[i*2+0] = hexdigits[(b >> 4) & 0x0F]; ret[i*2+1] = hexdigits[b & 0x0F]; } return ret; } inout(ubyte)[] opCast() inout { return m_bytes; } } unittest { auto t0 = SysTime(Clock.currTime(UTC()).toUnixTime.unixTimeToStdTime); auto id = BsonObjectID.generate(); auto t1 = SysTime(Clock.currTime(UTC()).toUnixTime.unixTimeToStdTime); assert(t0 <= id.timeStamp); assert(id.timeStamp <= t1); id = BsonObjectID.generate(t0); assert(id.timeStamp == t0); id = BsonObjectID.generate(t1); assert(id.timeStamp == t1); immutable dt = DateTime(2014, 07, 31, 19, 14, 55); id = BsonObjectID.generate(SysTime(dt, UTC())); assert(id.timeStamp == SysTime(dt, UTC())); } unittest { auto b = Bson(true); assert(b.opt!bool(false) == true); assert(b.opt!int(12) == 12); assert(b.opt!(Bson[])(null).length == 0); const c = b; assert(c.opt!bool(false) == true); assert(c.opt!int(12) == 12); assert(c.opt!(Bson[])(null).length == 0); } /** Represents a BSON date value (`Bson.Type.date`). BSON date values are stored in UNIX time format, counting the number of milliseconds from 1970/01/01. */ struct BsonDate { @safe: private long m_time; // milliseconds since UTC unix epoch /** Constructs a BsonDate from the given date value. The time-zone independent Date and DateTime types are assumed to be in the local time zone and converted to UTC if tz is left to null. */ this(in Date date, immutable TimeZone tz = null) { this(SysTime(date, tz)); } /// ditto this(in DateTime date, immutable TimeZone tz = null) { this(SysTime(date, tz)); } /// ditto this(in SysTime date) { this(fromStdTime(date.stdTime()).m_time); } /** Constructs a BsonDate from the given UNIX time. unix_time needs to be given in milliseconds from 1970/01/01. This is the native storage format for BsonDate. */ this(long unix_time) { m_time = unix_time; } /** Constructs a BsonDate from the given date/time string in ISO extended format. */ static BsonDate fromString(string iso_ext_string) { return BsonDate(SysTime.fromISOExtString(iso_ext_string)); } /** Constructs a BsonDate from the given date/time in standard time as defined in `std.datetime`. */ static BsonDate fromStdTime(long std_time) { enum zero = unixTimeToStdTime(0); return BsonDate((std_time - zero) / 10_000L); } /** The raw unix time value. This is the native storage/transfer format of a BsonDate. */ @property long value() const { return m_time; } /// ditto @property void value(long v) { m_time = v; } /** Returns the date formatted as ISO extended format. */ string toString() const { return toSysTime().toISOExtString(); } /* Converts to a SysTime. */ SysTime toSysTime() const { auto zero = unixTimeToStdTime(0); return SysTime(zero + m_time * 10_000L, UTC()); } /** Allows relational and equality comparisons. */ bool opEquals(ref const BsonDate other) const { return m_time == other.m_time; } /// ditto int opCmp(ref const BsonDate other) const { if( m_time == other.m_time ) return 0; if( m_time < other.m_time ) return -1; else return 1; } } /** Represents a BSON timestamp value `(Bson.Type.timestamp)`. */ struct BsonTimestamp { @safe: private long m_time; this( long time ){ m_time = time; } } /** Represents a BSON regular expression value `(Bson.Type.regex)`. */ struct BsonRegex { @safe: private { string m_expr; string m_options; } this(string expr, string options) { m_expr = expr; m_options = options; } @property string expression() const { return m_expr; } @property string options() const { return m_options; } } /** Serializes the given value to BSON. The following types of values are supported: $(DL $(DT `Bson`) $(DD Used as-is) $(DT `Json`) $(DD Converted to BSON) $(DT `BsonBinData`) $(DD Converted to `Bson.Type.binData`) $(DT `BsonObjectID`) $(DD Converted to `Bson.Type.objectID`) $(DT `BsonDate`) $(DD Converted to `Bson.Type.date`) $(DT `BsonTimestamp`) $(DD Converted to `Bson.Type.timestamp`) $(DT `BsonRegex`) $(DD Converted to `Bson.Type.regex`) $(DT `null`) $(DD Converted to `Bson.Type.null_`) $(DT `bool`) $(DD Converted to `Bson.Type.bool_`) $(DT `float`, `double`) $(DD Converted to `Bson.Type.double_`) $(DT `short`, `ushort`, `int`, `uint`, `long`, `ulong`) $(DD Converted to `Bson.Type.long_`) $(DT `string`) $(DD Converted to `Bson.Type.string`) $(DT `ubyte[]`) $(DD Converted to `Bson.Type.binData`) $(DT `T[]`) $(DD Converted to `Bson.Type.array`) $(DT `T[string]`) $(DD Converted to `Bson.Type.object`) $(DT `struct`) $(DD Converted to `Bson.Type.object`) $(DT `class`) $(DD Converted to `Bson.Type.object` or `Bson.Type.null_`) ) All entries of an array or an associative array, as well as all R/W properties and all fields of a struct/class are recursively serialized using the same rules. Fields ending with an underscore will have the last underscore stripped in the serialized output. This makes it possible to use fields with D keywords as their name by simply appending an underscore. The following methods can be used to customize the serialization of structs/classes: --- Bson toBson() const; static T fromBson(Bson src); Json toJson() const; static T fromJson(Json src); string toString() const; static T fromString(string src); --- The methods will have to be defined in pairs. The first pair that is implemented by the type will be used for serialization (i.e. `toBson` overrides `toJson`). See_Also: `deserializeBson` */ Bson serializeToBson(T)(T value, ubyte[] buffer = null) { return serialize!BsonSerializer(value, buffer); } template deserializeBson(T) { /** Deserializes a BSON value into the destination variable. The same types as for `serializeToBson()` are supported and handled inversely. See_Also: `serializeToBson` */ void deserializeBson(ref T dst, Bson src) { dst = deserializeBson!T(src); } /// ditto T deserializeBson(Bson src) { return deserialize!(BsonSerializer, T)(src); } } unittest { import std.stdio; enum Foo : string { k = "test" } enum Boo : int { l = 5 } static struct S { float a; double b; bool c; int d; string e; byte f; ubyte g; long h; ulong i; float[] j; Foo k; Boo l;} immutable S t = {1.5, -3.0, true, int.min, "Test", -128, 255, long.min, ulong.max, [1.1, 1.2, 1.3], Foo.k, Boo.l,}; S u; deserializeBson(u, serializeToBson(t)); assert(t.a == u.a); assert(t.b == u.b); assert(t.c == u.c); assert(t.d == u.d); assert(t.e == u.e); assert(t.f == u.f); assert(t.g == u.g); assert(t.h == u.h); assert(t.i == u.i); assert(t.j == u.j); assert(t.k == u.k); assert(t.l == u.l); } unittest { assert(uint.max == serializeToBson(uint.max).deserializeBson!uint); assert(ulong.max == serializeToBson(ulong.max).deserializeBson!ulong); } unittest { assert(deserializeBson!SysTime(serializeToBson(SysTime(0))) == SysTime(0)); assert(deserializeBson!SysTime(serializeToBson(SysTime(0, UTC()))) == SysTime(0, UTC())); assert(deserializeBson!Date(serializeToBson(Date.init)) == Date.init); assert(deserializeBson!Date(serializeToBson(Date(2001, 1, 1))) == Date(2001, 1, 1)); } @safe unittest { static struct A { int value; static A fromJson(Json val) @safe { return A(val.get!int); } Json toJson() const @safe { return Json(value); } Bson toBson() { return Bson(); } } static assert(!isStringSerializable!A && isJsonSerializable!A && !isBsonSerializable!A); static assert(!isStringSerializable!(const(A)) && !isJsonSerializable!(const(A)) && !isBsonSerializable!(const(A))); // assert(serializeToBson(const A(123)) == Bson(123)); // assert(serializeToBson(A(123)) == Bson(123)); static struct B { int value; static B fromBson(Bson val) @safe { return B(val.get!int); } Bson toBson() const @safe { return Bson(value); } Json toJson() { return Json(); } } static assert(!isStringSerializable!B && !isJsonSerializable!B && isBsonSerializable!B); static assert(!isStringSerializable!(const(B)) && !isJsonSerializable!(const(B)) && !isBsonSerializable!(const(B))); assert(serializeToBson(const B(123)) == Bson(123)); assert(serializeToBson(B(123)) == Bson(123)); static struct C { int value; static C fromString(string val) @safe { return C(val.to!int); } string toString() const @safe { return value.to!string; } Json toJson() { return Json(); } } static assert(isStringSerializable!C && !isJsonSerializable!C && !isBsonSerializable!C); static assert(!isStringSerializable!(const(C)) && !isJsonSerializable!(const(C)) && !isBsonSerializable!(const(C))); assert(serializeToBson(const C(123)) == Bson("123")); assert(serializeToBson(C(123)) == Bson("123")); static struct D { int value; string toString() const { return ""; } } static assert(!isStringSerializable!D && !isJsonSerializable!D && !isBsonSerializable!D); static assert(!isStringSerializable!(const(D)) && !isJsonSerializable!(const(D)) && !isBsonSerializable!(const(D))); assert(serializeToBson(const D(123)) == serializeToBson(["value": 123])); assert(serializeToBson(D(123)) == serializeToBson(["value": 123])); // test if const(class) is serializable static class E { int value; this(int v) @safe { value = v; } static E fromBson(Bson val) @safe { return new E(val.get!int); } Bson toBson() const @safe { return Bson(value); } Json toJson() { return Json(); } } static assert(!isStringSerializable!E && !isJsonSerializable!E && isBsonSerializable!E); static assert(!isStringSerializable!(const(E)) && !isJsonSerializable!(const(E)) && !isBsonSerializable!(const(E))); assert(serializeToBson(new const E(123)) == Bson(123)); assert(serializeToBson(new E(123)) == Bson(123)); } @safe unittest { static struct E { ubyte[4] bytes; ubyte[] more; } auto e = E([1, 2, 3, 4], [5, 6]); auto eb = serializeToBson(e); assert(eb["bytes"].type == Bson.Type.binData); assert(eb["more"].type == Bson.Type.binData); assert(e == deserializeBson!E(eb)); } @safe unittest { static class C { @safe: int a; private int _b; @property int b() const { return _b; } @property void b(int v) { _b = v; } @property int test() const @safe { return 10; } void test2() {} } C c = new C; c.a = 1; c.b = 2; C d; deserializeBson(d, serializeToBson(c)); assert(c.a == d.a); assert(c.b == d.b); const(C) e = c; // serialize const class instances (issue #653) deserializeBson(d, serializeToBson(e)); assert(e.a == d.a); assert(e.b == d.b); } unittest { static struct C { @safe: int value; static C fromString(string val) { return C(val.to!int); } string toString() const { return value.to!string; } } enum Color { Red, Green, Blue } { static class T { @safe: string[Color] enumIndexedMap; string[C] stringableIndexedMap; this() { enumIndexedMap = [ Color.Red : "magenta", Color.Blue : "deep blue" ]; stringableIndexedMap = [ C(42) : "forty-two" ]; } } T original = new T; original.enumIndexedMap[Color.Green] = "olive"; T other; deserializeBson(other, serializeToBson(original)); assert(serializeToBson(other) == serializeToBson(original)); } { static struct S { string[Color] enumIndexedMap; string[C] stringableIndexedMap; } S original; original.enumIndexedMap = [ Color.Red : "magenta", Color.Blue : "deep blue" ]; original.enumIndexedMap[Color.Green] = "olive"; original.stringableIndexedMap = [ C(42) : "forty-two" ]; S other; deserializeBson(other, serializeToBson(original)); assert(serializeToBson(other) == serializeToBson(original)); } } unittest { ubyte[] data = [1, 2, 3]; auto bson = serializeToBson(data); assert(bson.type == Bson.Type.binData); assert(deserializeBson!(ubyte[])(bson) == data); } unittest { // issue #709 ulong[] data = [2354877787627192443, 1, 2354877787627192442]; auto bson = Bson.fromJson(serializeToBson(data).toJson); assert(deserializeBson!(ulong[])(bson) == data); } unittest { // issue #709 uint[] data = [1, 2, 3, 4]; auto bson = Bson.fromJson(serializeToBson(data).toJson); // assert(deserializeBson!(uint[])(bson) == data); assert(deserializeBson!(ulong[])(bson).equal(data)); } unittest { import std.typecons; Nullable!bool x; auto bson = serializeToBson(x); assert(bson.type == Bson.Type.null_); deserializeBson(x, bson); assert(x.isNull); x = true; bson = serializeToBson(x); assert(bson.type == Bson.Type.bool_ && bson.get!bool == true); deserializeBson(x, bson); assert(x == true); } unittest { // issue #793 char[] test = "test".dup; auto bson = serializeToBson(test); //assert(bson.type == Bson.Type.string); //assert(bson.get!string == "test"); assert(bson.type == Bson.Type.array); assert(bson[0].type == Bson.Type.string && bson[0].get!string == "t"); } /** Serializes to an in-memory BSON representation. See_Also: `vibe.data.serialization.serialize`, `vibe.data.serialization.deserialize`, `serializeToBson`, `deserializeBson` */ struct BsonSerializer { import vibe.utils.array : AllocAppender; private { AllocAppender!(ubyte[]) m_dst; size_t[] m_compositeStack; Bson.Type m_type = Bson.Type.null_; Bson m_inputData; string m_entryName; size_t m_entryIndex = size_t.max; } this(Bson input) @safe { m_inputData = input; } this(ubyte[] buffer) @safe { import vibe.internal.utilallocator; m_dst = () @trusted { return AllocAppender!(ubyte[])(vibeThreadAllocator(), buffer); } (); } @disable this(this); template isSupportedValueType(T) { enum isSupportedValueType = is(typeof(getBsonTypeID(T.init))); } // // serialization // Bson getSerializedResult() @safe { auto ret = Bson(m_type, () @trusted { return cast(immutable)m_dst.data; } ()); () @trusted { m_dst.reset(); } (); m_type = Bson.Type.null_; return ret; } void beginWriteDictionary(Traits)() { writeCompositeEntryHeader(Bson.Type.object); m_compositeStack ~= m_dst.data.length; m_dst.put(toBsonData(cast(int)0)); } void endWriteDictionary(Traits)() { m_dst.put(Bson.Type.end); auto sh = m_compositeStack[$-1]; m_compositeStack.length--; m_dst.data[sh .. sh + 4] = toBsonData(cast(uint)(m_dst.data.length - sh))[]; } void beginWriteDictionaryEntry(Traits)(string name) { m_entryName = name; } void endWriteDictionaryEntry(Traits)(string name) {} void beginWriteArray(Traits)(size_t) { writeCompositeEntryHeader(Bson.Type.array); m_compositeStack ~= m_dst.data.length; m_dst.put(toBsonData(cast(int)0)); } void endWriteArray(Traits)() { endWriteDictionary!Traits(); } void beginWriteArrayEntry(Traits)(size_t idx) { m_entryIndex = idx; } void endWriteArrayEntry(Traits)(size_t idx) {} // auto ref does't work for DMD 2.064 void writeValue(Traits, T)(/*auto ref const*/ in T value) { writeValueH!(T, true)(value); } private void writeValueH(T, bool write_header)(/*auto ref const*/ in T value) { static if (write_header) writeCompositeEntryHeader(getBsonTypeID(value)); static if (is(T == Bson)) { m_dst.put(value.data); } else static if (is(T == Json)) { m_dst.put(Bson(value).data); } // FIXME: use .writeBsonValue else static if (is(T == typeof(null))) {} else static if (is(T == string)) { m_dst.put(toBsonData(cast(uint)value.length+1)); m_dst.putCString(value); } else static if (is(T == BsonBinData)) { m_dst.put(toBsonData(cast(int)value.rawData.length)); m_dst.put(value.type); m_dst.put(value.rawData); } else static if (is(T == BsonObjectID)) { m_dst.put(value.m_bytes[]); } else static if (is(T == BsonDate)) { m_dst.put(toBsonData(value.m_time)); } else static if (is(T == SysTime)) { m_dst.put(toBsonData(BsonDate(value).m_time)); } else static if (is(T == BsonRegex)) { m_dst.putCString(value.expression); m_dst.putCString(value.options); } else static if (is(T == BsonTimestamp)) { m_dst.put(toBsonData(value.m_time)); } else static if (is(T == bool)) { m_dst.put(cast(ubyte)(value ? 0x01 : 0x00)); } else static if (is(T : int) && isIntegral!T) { m_dst.put(toBsonData(cast(int)value)); } else static if (is(T : long) && isIntegral!T) { m_dst.put(toBsonData(value)); } else static if (is(T : double) && isFloatingPoint!T) { m_dst.put(toBsonData(cast(double)value)); } else static if (isBsonSerializable!T) { static if (!__traits(compiles, () @safe { return value.toBson(); } ())) pragma(msg, "Non-@safe toBson/fromBson methods are deprecated - annotate "~T.stringof~".toBson() with @safe."); m_dst.put(() @trusted { return value.toBson(); } ().data); } else static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return value.toJson(); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".toJson() with @safe."); m_dst.put(Bson(() @trusted { return value.toJson(); } ()).data); } else static if (is(T : const(ubyte)[])) { writeValueH!(BsonBinData, false)(BsonBinData(BsonBinData.Type.generic, value.idup)); } else static assert(false, "Unsupported type: " ~ T.stringof); } private void writeCompositeEntryHeader(Bson.Type tp) @safe { if (!m_compositeStack.length) { assert(m_type == Bson.Type.null_, "Overwriting root item."); m_type = tp; } if (m_entryName !is null) { m_dst.put(tp); m_dst.putCString(m_entryName); m_entryName = null; } else if (m_entryIndex != size_t.max) { import std.format; m_dst.put(tp); static struct Wrapper { @trusted: AllocAppender!(ubyte[])* app; void put(char ch) { (*app).put(ch); } void put(in char[] str) { (*app).put(cast(const(ubyte)[])str); } } auto wr = Wrapper(&m_dst); wr.formattedWrite("%d\0", m_entryIndex); m_entryIndex = size_t.max; } } // // deserialization // void readDictionary(Traits)(scope void delegate(string) @safe entry_callback) { enforce(m_inputData.type == Bson.Type.object, "Expected object instead of "~m_inputData.type.to!string()); auto old = m_inputData; foreach (string name, value; old.byKeyValue) { m_inputData = value; entry_callback(name); } m_inputData = old; } 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) { enforce(m_inputData.type == Bson.Type.array, "Expected array instead of "~m_inputData.type.to!string()); auto old = m_inputData; foreach (value; old.byValue) { m_inputData = value; entry_callback(); } m_inputData = old; } void beginReadArrayEntry(Traits)(size_t index) {} void endReadArrayEntry(Traits)(size_t index) {} T readValue(Traits, T)() { static if (is(T == Bson)) return m_inputData; else static if (is(T == Json)) return m_inputData.toJson(); else static if (is(T == bool)) return m_inputData.get!bool(); else static if (is(T == uint)) return cast(T)m_inputData.get!int(); else static if (is(T : int)) { if(m_inputData.type == Bson.Type.long_) { enforce((m_inputData.get!long() >= int.min) && (m_inputData.get!long() <= int.max), "Long out of range while attempting to deserialize to int: " ~ m_inputData.get!long.to!string); return cast(T)m_inputData.get!long(); } else return m_inputData.get!int().to!T; } else static if (is(T : long)) { if(m_inputData.type == Bson.Type.int_) return cast(T)m_inputData.get!int(); else return cast(T)m_inputData.get!long(); } else static if (is(T : double)) return cast(T)m_inputData.get!double(); else static if (is(T == SysTime)) { // support legacy behavior to serialize as string if (m_inputData.type == Bson.Type.string) return SysTime.fromISOExtString(m_inputData.get!string); else return m_inputData.get!BsonDate().toSysTime(); } else static if (isBsonSerializable!T) { static if (!__traits(compiles, () @safe { return T.fromBson(Bson.init); } ())) pragma(msg, "Non-@safe toBson/fromBson methods are deprecated - annotate "~T.stringof~".fromBson() with @safe."); auto bval = readValue!(Traits, Bson); return () @trusted { return T.fromBson(bval); } (); } else static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return T.fromJson(Json.init); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".fromJson() with @safe."); auto jval = readValue!(Traits, Bson).toJson(); return () @trusted { return T.fromJson(jval); } (); } else static if (is(T : const(ubyte)[])) { auto ret = m_inputData.get!BsonBinData.rawData; static if (isStaticArray!T) return cast(T)ret[0 .. T.length]; else static if (is(T : immutable(char)[])) return ret; else return cast(T)ret.dup; } else return m_inputData.get!T(); } bool tryReadNull(Traits)() { if (m_inputData.type == Bson.Type.null_) return true; return false; } private static Bson.Type getBsonTypeID(T, bool accept_ao = false)(/*auto ref const*/ in T value) @safe { Bson.Type tp; static if (is(T == Bson)) tp = value.type; else static if (is(T == Json)) tp = jsonTypeToBsonType(value.type); else static if (is(T == typeof(null))) tp = Bson.Type.null_; else static if (is(T == string)) tp = Bson.Type.string; else static if (is(T == BsonBinData)) tp = Bson.Type.binData; else static if (is(T == BsonObjectID)) tp = Bson.Type.objectID; else static if (is(T == BsonDate)) tp = Bson.Type.date; else static if (is(T == SysTime)) tp = Bson.Type.date; else static if (is(T == BsonRegex)) tp = Bson.Type.regex; else static if (is(T == BsonTimestamp)) tp = Bson.Type.timestamp; else static if (is(T == bool)) tp = Bson.Type.bool_; else static if (isIntegral!T && is(T : int)) tp = Bson.Type.int_; else static if (isIntegral!T && is(T : long)) tp = Bson.Type.long_; else static if (isFloatingPoint!T && is(T : double)) tp = Bson.Type.double_; else static if (isBsonSerializable!T) tp = value.toBson().type; // FIXME: this is highly inefficient else static if (isJsonSerializable!T) tp = jsonTypeToBsonType(value.toJson().type); // FIXME: this is highly inefficient else static if (is(T : const(ubyte)[])) tp = Bson.Type.binData; else static if (accept_ao && isArray!T) tp = Bson.Type.array; else static if (accept_ao && isAssociativeArray!T) tp = Bson.Type.object; else static if (accept_ao && (is(T == class) || is(T == struct))) tp = Bson.Type.object; else static assert(false, "Unsupported type: " ~ T.stringof); return tp; } } private Bson.Type jsonTypeToBsonType(Json.Type tp) @safe { static immutable Bson.Type[Json.Type.max+1] JsonIDToBsonID = [ Bson.Type.undefined, Bson.Type.null_, Bson.Type.bool_, Bson.Type.long_, Bson.Type.long_, Bson.Type.double_, Bson.Type.string, Bson.Type.array, Bson.Type.object ]; return JsonIDToBsonID[tp]; } private Bson.Type writeBson(R)(ref R dst, in Json value) if( isOutputRange!(R, ubyte) ) { final switch(value.type){ case Json.Type.undefined: return Bson.Type.undefined; case Json.Type.null_: return Bson.Type.null_; case Json.Type.bool_: dst.put(cast(ubyte)(cast(bool)value ? 0x01 : 0x00)); return Bson.Type.bool_; case Json.Type.int_: dst.put(toBsonData(cast(long)value)); return Bson.Type.long_; case Json.Type.bigInt: dst.put(toBsonData(cast(long)value)); return Bson.Type.long_; case Json.Type.float_: dst.put(toBsonData(cast(double)value)); return Bson.Type.double_; case Json.Type.string: dst.put(toBsonData(cast(uint)value.length+1)); dst.put(cast(bdata_t)cast(string)value); dst.put(cast(ubyte)0); return Bson.Type.string; case Json.Type.array: auto app = appender!bdata_t(); foreach( size_t i, ref const Json v; value ){ app.put(cast(ubyte)(jsonTypeToBsonType(v.type))); putCString(app, to!string(i)); writeBson(app, v); } dst.put(toBsonData(cast(int)(app.data.length + int.sizeof + 1))); dst.put(app.data); dst.put(cast(ubyte)0); return Bson.Type.array; case Json.Type.object: auto app = appender!bdata_t(); foreach( string k, ref const Json v; value ){ app.put(cast(ubyte)(jsonTypeToBsonType(v.type))); putCString(app, k); writeBson(app, v); } dst.put(toBsonData(cast(int)(app.data.length + int.sizeof + 1))); dst.put(app.data); dst.put(cast(ubyte)0); return Bson.Type.object; } } unittest { Json jsvalue = parseJsonString("{\"key\" : \"Value\"}"); assert(serializeToBson(jsvalue).toJson() == jsvalue); jsvalue = parseJsonString("{\"key\" : [{\"key\" : \"Value\"}, {\"key2\" : \"Value2\"}] }"); assert(serializeToBson(jsvalue).toJson() == jsvalue); jsvalue = parseJsonString("[ 1 , 2 , 3]"); assert(serializeToBson(jsvalue).toJson() == jsvalue); } private string skipCString(ref bdata_t data) @safe { auto idx = data.countUntil(0); enforce(idx >= 0, "Unterminated BSON C-string."); auto ret = data[0 .. idx]; data = data[idx+1 .. $]; return cast(string)ret; } private void putCString(R)(ref R dst, string str) { dst.put(cast(bdata_t)str); dst.put(cast(ubyte)0); } ubyte[] toBsonData(T)(T v) { /*static T tmp; tmp = nativeToLittleEndian(v); return cast(ubyte[])((&tmp)[0 .. 1]);*/ if (__ctfe) return nativeToLittleEndian(v).dup; else { static ubyte[T.sizeof] ret; ret = nativeToLittleEndian(v); return ret; } } T fromBsonData(T)(in ubyte[] v) { assert(v.length >= T.sizeof); //return (cast(T[])v[0 .. T.sizeof])[0]; ubyte[T.sizeof] vu = v[0 .. T.sizeof]; return littleEndianToNative!T(vu); } ubyte[] toBigEndianData(T)(T v) { if (__ctfe) return nativeToBigEndian(v).dup; else { static ubyte[T.sizeof] ret; ret = nativeToBigEndian(v); return ret; } } private string underscoreStrip(string field_name) pure @safe { if( field_name.length < 1 || field_name[$-1] != '_' ) return field_name; else return field_name[0 .. $-1]; } /// private package template isBsonSerializable(T) { enum isBsonSerializable = is(typeof(T.init.toBson()) == Bson) && is(typeof(T.fromBson(Bson())) == T); }