forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.d
1851 lines (1635 loc) · 52.5 KB
/
json.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
JavaScript Object Notation
Copyright: Copyright Jeremie Pelletier 2008 - 2009.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jeremie Pelletier, David Herberth
References: $(LINK http://json.org/)
Source: $(PHOBOSSRC std/json.d)
*/
/*
Copyright Jeremie Pelletier 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.json;
import std.array;
import std.conv;
import std.range.primitives;
import std.traits;
///
@system unittest
{
import std.conv : to;
// parse a file or string of json into a usable structure
string s = `{ "language": "D", "rating": 3.5, "code": "42" }`;
JSONValue j = parseJSON(s);
// j and j["language"] return JSONValue,
// j["language"].str returns a string
assert(j["language"].str == "D");
assert(j["rating"].floating == 3.5);
// check a type
long x;
if (const(JSONValue)* code = "code" in j)
{
if (code.type() == JSON_TYPE.INTEGER)
x = code.integer;
else
x = to!int(code.str);
}
// create a json struct
JSONValue jj = [ "language": "D" ];
// rating doesnt exist yet, so use .object to assign
jj.object["rating"] = JSONValue(3.5);
// create an array to assign to list
jj.object["list"] = JSONValue( ["a", "b", "c"] );
// list already exists, so .object optional
jj["list"].array ~= JSONValue("D");
string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`;
assert(jj.toString == jjStr);
}
/**
String literals used to represent special float values within JSON strings.
*/
enum JSONFloatLiteral : string
{
nan = "NaN", /// string representation of floating-point NaN
inf = "Infinite", /// string representation of floating-point Infinity
negativeInf = "-Infinite", /// string representation of floating-point negative Infinity
}
/**
Flags that control how json is encoded and parsed.
*/
enum JSONOptions
{
none, /// standard parsing
specialFloatLiterals = 0x1, /// encode NaN and Inf float values as strings
escapeNonAsciiChars = 0x2, /// encode non ascii characters with an unicode escape sequence
doNotEscapeSlashes = 0x4, /// do not escape slashes ('/')
}
/**
JSON type enumeration
*/
enum JSON_TYPE : byte
{
/// Indicates the type of a `JSONValue`.
NULL,
STRING, /// ditto
INTEGER, /// ditto
UINTEGER,/// ditto
FLOAT, /// ditto
OBJECT, /// ditto
ARRAY, /// ditto
TRUE, /// ditto
FALSE /// ditto
}
/**
JSON value node
*/
struct JSONValue
{
import std.exception : enforce;
union Store
{
string str;
long integer;
ulong uinteger;
double floating;
JSONValue[string] object;
JSONValue[] array;
}
private Store store;
private JSON_TYPE type_tag;
/**
Returns the JSON_TYPE of the value stored in this structure.
*/
@property JSON_TYPE type() const pure nothrow @safe @nogc
{
return type_tag;
}
///
@safe unittest
{
string s = "{ \"language\": \"D\" }";
JSONValue j = parseJSON(s);
assert(j.type == JSON_TYPE.OBJECT);
assert(j["language"].type == JSON_TYPE.STRING);
}
/***
* Value getter/setter for `JSON_TYPE.STRING`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.STRING`.
*/
@property string str() const pure @trusted
{
enforce!JSONException(type == JSON_TYPE.STRING,
"JSONValue is not a string");
return store.str;
}
/// ditto
@property string str(string v) pure nothrow @nogc @safe
{
assign(v);
return v;
}
///
@safe unittest
{
JSONValue j = [ "language": "D" ];
// get value
assert(j["language"].str == "D");
// change existing key to new string
j["language"].str = "Perl";
assert(j["language"].str == "Perl");
}
/***
* Value getter/setter for `JSON_TYPE.INTEGER`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.INTEGER`.
*/
@property inout(long) integer() inout pure @safe
{
enforce!JSONException(type == JSON_TYPE.INTEGER,
"JSONValue is not an integer");
return store.integer;
}
/// ditto
@property long integer(long v) pure nothrow @safe @nogc
{
assign(v);
return store.integer;
}
/***
* Value getter/setter for `JSON_TYPE.UINTEGER`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.UINTEGER`.
*/
@property inout(ulong) uinteger() inout pure @safe
{
enforce!JSONException(type == JSON_TYPE.UINTEGER,
"JSONValue is not an unsigned integer");
return store.uinteger;
}
/// ditto
@property ulong uinteger(ulong v) pure nothrow @safe @nogc
{
assign(v);
return store.uinteger;
}
/***
* Value getter/setter for `JSON_TYPE.FLOAT`. Note that despite
* the name, this is a $(B 64)-bit `double`, not a 32-bit `float`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.FLOAT`.
*/
@property inout(double) floating() inout pure @safe
{
enforce!JSONException(type == JSON_TYPE.FLOAT,
"JSONValue is not a floating type");
return store.floating;
}
/// ditto
@property double floating(double v) pure nothrow @safe @nogc
{
assign(v);
return store.floating;
}
/***
* Value getter/setter for `JSON_TYPE.OBJECT`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.OBJECT`.
* Note: this is @system because of the following pattern:
---
auto a = &(json.object());
json.uinteger = 0; // overwrite AA pointer
(*a)["hello"] = "world"; // segmentation fault
---
*/
@property ref inout(JSONValue[string]) object() inout pure @system
{
enforce!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
return store.object;
}
/// ditto
@property JSONValue[string] object(JSONValue[string] v) pure nothrow @nogc @safe
{
assign(v);
return v;
}
/***
* Value getter for `JSON_TYPE.OBJECT`.
* Unlike `object`, this retrieves the object by value and can be used in @safe code.
*
* A caveat is that, if the returned value is null, modifications will not be visible:
* ---
* JSONValue json;
* json.object = null;
* json.objectNoRef["hello"] = JSONValue("world");
* assert("hello" !in json.object);
* ---
*
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.OBJECT`.
*/
@property inout(JSONValue[string]) objectNoRef() inout pure @trusted
{
enforce!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
return store.object;
}
/***
* Value getter/setter for `JSON_TYPE.ARRAY`.
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.ARRAY`.
* Note: this is @system because of the following pattern:
---
auto a = &(json.array());
json.uinteger = 0; // overwrite array pointer
(*a)[0] = "world"; // segmentation fault
---
*/
@property ref inout(JSONValue[]) array() inout pure @system
{
enforce!JSONException(type == JSON_TYPE.ARRAY,
"JSONValue is not an array");
return store.array;
}
/// ditto
@property JSONValue[] array(JSONValue[] v) pure nothrow @nogc @safe
{
assign(v);
return v;
}
/***
* Value getter for `JSON_TYPE.ARRAY`.
* Unlike `array`, this retrieves the array by value and can be used in @safe code.
*
* A caveat is that, if you append to the returned array, the new values aren't visible in the
* JSONValue:
* ---
* JSONValue json;
* json.array = [JSONValue("hello")];
* json.arrayNoRef ~= JSONValue("world");
* assert(json.array.length == 1);
* ---
*
* Throws: `JSONException` for read access if `type` is not
* `JSON_TYPE.ARRAY`.
*/
@property inout(JSONValue[]) arrayNoRef() inout pure @trusted
{
enforce!JSONException(type == JSON_TYPE.ARRAY,
"JSONValue is not an array");
return store.array;
}
/// Test whether the type is `JSON_TYPE.NULL`
@property bool isNull() const pure nothrow @safe @nogc
{
return type == JSON_TYPE.NULL;
}
private void assign(T)(T arg) @safe
{
static if (is(T : typeof(null)))
{
type_tag = JSON_TYPE.NULL;
}
else static if (is(T : string))
{
type_tag = JSON_TYPE.STRING;
string t = arg;
() @trusted { store.str = t; }();
}
else static if (isSomeString!T) // issue 15884
{
type_tag = JSON_TYPE.STRING;
// FIXME: std.array.array(Range) is not deduced as 'pure'
() @trusted {
import std.utf : byUTF;
store.str = cast(immutable)(arg.byUTF!char.array);
}();
}
else static if (is(T : bool))
{
type_tag = arg ? JSON_TYPE.TRUE : JSON_TYPE.FALSE;
}
else static if (is(T : ulong) && isUnsigned!T)
{
type_tag = JSON_TYPE.UINTEGER;
store.uinteger = arg;
}
else static if (is(T : long))
{
type_tag = JSON_TYPE.INTEGER;
store.integer = arg;
}
else static if (isFloatingPoint!T)
{
type_tag = JSON_TYPE.FLOAT;
store.floating = arg;
}
else static if (is(T : Value[Key], Key, Value))
{
static assert(is(Key : string), "AA key must be string");
type_tag = JSON_TYPE.OBJECT;
static if (is(Value : JSONValue))
{
JSONValue[string] t = arg;
() @trusted { store.object = t; }();
}
else
{
JSONValue[string] aa;
foreach (key, value; arg)
aa[key] = JSONValue(value);
() @trusted { store.object = aa; }();
}
}
else static if (isArray!T)
{
type_tag = JSON_TYPE.ARRAY;
static if (is(ElementEncodingType!T : JSONValue))
{
JSONValue[] t = arg;
() @trusted { store.array = t; }();
}
else
{
JSONValue[] new_arg = new JSONValue[arg.length];
foreach (i, e; arg)
new_arg[i] = JSONValue(e);
() @trusted { store.array = new_arg; }();
}
}
else static if (is(T : JSONValue))
{
type_tag = arg.type;
store = arg.store;
}
else
{
static assert(false, text(`unable to convert type "`, T.stringof, `" to json`));
}
}
private void assignRef(T)(ref T arg) if (isStaticArray!T)
{
type_tag = JSON_TYPE.ARRAY;
static if (is(ElementEncodingType!T : JSONValue))
{
store.array = arg;
}
else
{
JSONValue[] new_arg = new JSONValue[arg.length];
foreach (i, e; arg)
new_arg[i] = JSONValue(e);
store.array = new_arg;
}
}
/**
* Constructor for `JSONValue`. If `arg` is a `JSONValue`
* its value and type will be copied to the new `JSONValue`.
* Note that this is a shallow copy: if type is `JSON_TYPE.OBJECT`
* or `JSON_TYPE.ARRAY` then only the reference to the data will
* be copied.
* Otherwise, `arg` must be implicitly convertible to one of the
* following types: `typeof(null)`, `string`, `ulong`,
* `long`, `double`, an associative array `V[K]` for any `V`
* and `K` i.e. a JSON object, any array or `bool`. The type will
* be set accordingly.
*/
this(T)(T arg) if (!isStaticArray!T)
{
assign(arg);
}
/// Ditto
this(T)(ref T arg) if (isStaticArray!T)
{
assignRef(arg);
}
/// Ditto
this(T : JSONValue)(inout T arg) inout
{
store = arg.store;
type_tag = arg.type;
}
///
@safe unittest
{
JSONValue j = JSONValue( "a string" );
j = JSONValue(42);
j = JSONValue( [1, 2, 3] );
assert(j.type == JSON_TYPE.ARRAY);
j = JSONValue( ["language": "D"] );
assert(j.type == JSON_TYPE.OBJECT);
}
void opAssign(T)(T arg) if (!isStaticArray!T && !is(T : JSONValue))
{
assign(arg);
}
void opAssign(T)(ref T arg) if (isStaticArray!T)
{
assignRef(arg);
}
/***
* Array syntax for json arrays.
* Throws: `JSONException` if `type` is not `JSON_TYPE.ARRAY`.
*/
ref inout(JSONValue) opIndex(size_t i) inout pure @safe
{
auto a = this.arrayNoRef;
enforce!JSONException(i < a.length,
"JSONValue array index is out of range");
return a[i];
}
///
@safe unittest
{
JSONValue j = JSONValue( [42, 43, 44] );
assert( j[0].integer == 42 );
assert( j[1].integer == 43 );
}
/***
* Hash syntax for json objects.
* Throws: `JSONException` if `type` is not `JSON_TYPE.OBJECT`.
*/
ref inout(JSONValue) opIndex(string k) inout pure @safe
{
auto o = this.objectNoRef;
return *enforce!JSONException(k in o,
"Key not found: " ~ k);
}
///
@safe unittest
{
JSONValue j = JSONValue( ["language": "D"] );
assert( j["language"].str == "D" );
}
/***
* Operator sets `value` for element of JSON object by `key`.
*
* If JSON value is null, then operator initializes it with object and then
* sets `value` for it.
*
* Throws: `JSONException` if `type` is not `JSON_TYPE.OBJECT`
* or `JSON_TYPE.NULL`.
*/
void opIndexAssign(T)(auto ref T value, string key) pure
{
enforce!JSONException(type == JSON_TYPE.OBJECT || type == JSON_TYPE.NULL,
"JSONValue must be object or null");
JSONValue[string] aa = null;
if (type == JSON_TYPE.OBJECT)
{
aa = this.objectNoRef;
}
aa[key] = value;
this.object = aa;
}
///
@safe unittest
{
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
}
void opIndexAssign(T)(T arg, size_t i) pure
{
auto a = this.arrayNoRef;
enforce!JSONException(i < a.length,
"JSONValue array index is out of range");
a[i] = arg;
this.array = a;
}
///
@safe unittest
{
JSONValue j = JSONValue( ["Perl", "C"] );
j[1].str = "D";
assert( j[1].str == "D" );
}
JSONValue opBinary(string op : "~", T)(T arg) @safe
{
auto a = this.arrayNoRef;
static if (isArray!T)
{
return JSONValue(a ~ JSONValue(arg).arrayNoRef);
}
else static if (is(T : JSONValue))
{
return JSONValue(a ~ arg.arrayNoRef);
}
else
{
static assert(false, "argument is not an array or a JSONValue array");
}
}
void opOpAssign(string op : "~", T)(T arg) @safe
{
auto a = this.arrayNoRef;
static if (isArray!T)
{
a ~= JSONValue(arg).arrayNoRef;
}
else static if (is(T : JSONValue))
{
a ~= arg.arrayNoRef;
}
else
{
static assert(false, "argument is not an array or a JSONValue array");
}
this.array = a;
}
/**
* Support for the `in` operator.
*
* Tests wether a key can be found in an object.
*
* Returns:
* when found, the `const(JSONValue)*` that matches to the key,
* otherwise `null`.
*
* Throws: `JSONException` if the right hand side argument `JSON_TYPE`
* is not `OBJECT`.
*/
auto opBinaryRight(string op : "in")(string k) const @safe
{
return k in this.objectNoRef;
}
///
@safe unittest
{
JSONValue j = [ "language": "D", "author": "walter" ];
string a = ("author" in j).str;
}
bool opEquals(const JSONValue rhs) const @nogc nothrow pure @safe
{
return opEquals(rhs);
}
bool opEquals(ref const JSONValue rhs) const @nogc nothrow pure @trusted
{
// Default doesn't work well since store is a union. Compare only
// what should be in store.
// This is @trusted to remain nogc, nothrow, fast, and usable from @safe code.
if (type_tag != rhs.type_tag) return false;
final switch (type_tag)
{
case JSON_TYPE.STRING:
return store.str == rhs.store.str;
case JSON_TYPE.INTEGER:
return store.integer == rhs.store.integer;
case JSON_TYPE.UINTEGER:
return store.uinteger == rhs.store.uinteger;
case JSON_TYPE.FLOAT:
return store.floating == rhs.store.floating;
case JSON_TYPE.OBJECT:
return store.object == rhs.store.object;
case JSON_TYPE.ARRAY:
return store.array == rhs.store.array;
case JSON_TYPE.TRUE:
case JSON_TYPE.FALSE:
case JSON_TYPE.NULL:
return true;
}
}
/// Implements the foreach `opApply` interface for json arrays.
int opApply(scope int delegate(size_t index, ref JSONValue) dg) @system
{
int result;
foreach (size_t index, ref value; array)
{
result = dg(index, value);
if (result)
break;
}
return result;
}
/// Implements the foreach `opApply` interface for json objects.
int opApply(scope int delegate(string key, ref JSONValue) dg) @system
{
enforce!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
int result;
foreach (string key, ref value; object)
{
result = dg(key, value);
if (result)
break;
}
return result;
}
/***
* Implicitly calls `toJSON` on this JSONValue.
*
* $(I options) can be used to tweak the conversion behavior.
*/
string toString(in JSONOptions options = JSONOptions.none) const @safe
{
return toJSON(this, false, options);
}
/***
* Implicitly calls `toJSON` on this JSONValue, like `toString`, but
* also passes $(I true) as $(I pretty) argument.
*
* $(I options) can be used to tweak the conversion behavior
*/
string toPrettyString(in JSONOptions options = JSONOptions.none) const @safe
{
return toJSON(this, true, options);
}
}
/**
Parses a serialized string and returns a tree of JSON values.
Throws: $(LREF JSONException) if the depth exceeds the max depth.
Params:
json = json-formatted string to parse
maxDepth = maximum depth of nesting allowed, -1 disables depth checking
options = enable decoding string representations of NaN/Inf as float values
*/
JSONValue parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none)
if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T))
{
import std.ascii : isWhite, isDigit, isHexDigit, toUpper, toLower;
import std.typecons : Yes;
JSONValue root;
root.type_tag = JSON_TYPE.NULL;
// Avoid UTF decoding when possible, as it is unnecessary when
// processing JSON.
static if (is(T : const(char)[]))
alias Char = char;
else
alias Char = Unqual!(ElementType!T);
if (json.empty) return root;
int depth = -1;
Char next = 0;
int line = 1, pos = 0;
void error(string msg)
{
throw new JSONException(msg, line, pos);
}
Char popChar()
{
if (json.empty) error("Unexpected end of data.");
static if (is(T : const(char)[]))
{
Char c = json[0];
json = json[1..$];
}
else
{
Char c = json.front;
json.popFront();
}
if (c == '\n')
{
line++;
pos = 0;
}
else
{
pos++;
}
return c;
}
Char peekChar()
{
if (!next)
{
if (json.empty) return '\0';
next = popChar();
}
return next;
}
void skipWhitespace()
{
while (isWhite(peekChar())) next = 0;
}
Char getChar(bool SkipWhitespace = false)()
{
static if (SkipWhitespace) skipWhitespace();
Char c;
if (next)
{
c = next;
next = 0;
}
else
c = popChar();
return c;
}
void checkChar(bool SkipWhitespace = true, bool CaseSensitive = true)(char c)
{
static if (SkipWhitespace) skipWhitespace();
auto c2 = getChar();
static if (!CaseSensitive) c2 = toLower(c2);
if (c2 != c) error(text("Found '", c2, "' when expecting '", c, "'."));
}
bool testChar(bool SkipWhitespace = true, bool CaseSensitive = true)(char c)
{
static if (SkipWhitespace) skipWhitespace();
auto c2 = peekChar();
static if (!CaseSensitive) c2 = toLower(c2);
if (c2 != c) return false;
getChar();
return true;
}
wchar parseWChar()
{
wchar val = 0;
foreach_reverse (i; 0 .. 4)
{
auto hex = toUpper(getChar());
if (!isHexDigit(hex)) error("Expecting hex character");
val += (isDigit(hex) ? hex - '0' : hex - ('A' - 10)) << (4 * i);
}
return val;
}
string parseString()
{
import std.ascii : isControl;
import std.uni : isSurrogateHi, isSurrogateLo;
import std.utf : encode, decode;
auto str = appender!string();
Next:
switch (peekChar())
{
case '"':
getChar();
break;
case '\\':
getChar();
auto c = getChar();
switch (c)
{
case '"': str.put('"'); break;
case '\\': str.put('\\'); break;
case '/': str.put('/'); break;
case 'b': str.put('\b'); break;
case 'f': str.put('\f'); break;
case 'n': str.put('\n'); break;
case 'r': str.put('\r'); break;
case 't': str.put('\t'); break;
case 'u':
wchar wc = parseWChar();
dchar val;
// Non-BMP characters are escaped as a pair of
// UTF-16 surrogate characters (see RFC 4627).
if (isSurrogateHi(wc))
{
wchar[2] pair;
pair[0] = wc;
if (getChar() != '\\') error("Expected escaped low surrogate after escaped high surrogate");
if (getChar() != 'u') error("Expected escaped low surrogate after escaped high surrogate");
pair[1] = parseWChar();
size_t index = 0;
val = decode(pair[], index);
if (index != 2) error("Invalid escaped surrogate pair");
}
else
if (isSurrogateLo(wc))
error(text("Unexpected low surrogate"));
else
val = wc;
char[4] buf;
immutable len = encode!(Yes.useReplacementDchar)(buf, val);
str.put(buf[0 .. len]);
break;
default:
error(text("Invalid escape sequence '\\", c, "'."));
}
goto Next;
default:
// RFC 7159 states that control characters U+0000 through
// U+001F must not appear unescaped in a JSON string.
auto c = getChar();
if (isControl(c))
error("Illegal control character.");
str.put(c);
goto Next;
}
return str.data.length ? str.data : "";
}
bool tryGetSpecialFloat(string str, out double val) {
switch (str)
{
case JSONFloatLiteral.nan:
val = double.nan;
return true;
case JSONFloatLiteral.inf:
val = double.infinity;
return true;
case JSONFloatLiteral.negativeInf:
val = -double.infinity;
return true;
default:
return false;
}
}
void parseValue(ref JSONValue value)
{
depth++;
if (maxDepth != -1 && depth > maxDepth) error("Nesting too deep.");
auto c = getChar!true();
switch (c)
{
case '{':
if (testChar('}'))
{
value.object = null;
break;
}
JSONValue[string] obj;
do
{
checkChar('"');
string name = parseString();
checkChar(':');
JSONValue member;
parseValue(member);
obj[name] = member;
}
while (testChar(','));
value.object = obj;
checkChar('}');
break;
case '[':
if (testChar(']'))
{
value.type_tag = JSON_TYPE.ARRAY;
break;
}
JSONValue[] arr;
do
{
JSONValue element;
parseValue(element);
arr ~= element;
}
while (testChar(','));
checkChar(']');
value.array = arr;
break;
case '"':
auto str = parseString();
// if special float parsing is enabled, check if string represents NaN/Inf
if ((options & JSONOptions.specialFloatLiterals) &&
tryGetSpecialFloat(str, value.store.floating))
{
// found a special float, its value was placed in value.store.floating
value.type_tag = JSON_TYPE.FLOAT;
break;
}
value.type_tag = JSON_TYPE.STRING;
value.store.str = str;
break;
case '0': .. case '9':
case '-':
auto number = appender!string();
bool isFloat, isNegative;
void readInteger()
{
if (!isDigit(c)) error("Digit expected");
Next: number.put(c);
if (isDigit(peekChar()))
{
c = getChar();
goto Next;
}
}
if (c == '-')
{
number.put('-');
c = getChar();