-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.h
806 lines (761 loc) · 22.3 KB
/
json.h
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
#ifndef _JSON_H
#define _JSON_H
#include <string>
#include <vector>
#include <unordered_map>
#include <variant>
#include <fstream>
namespace json {
enum ValueType {
String,
Number,
Object,
Array,
True,
False,
Null,
};
//////////////////// JSON value ////////////////////
class value {
private:
// JSON String
typedef std::string string;
// JSON Number
typedef double number;
// JSON Value
typedef std::unique_ptr<value> value_ptr;
// JSON Object
typedef std::unordered_map<string, value_ptr> object;
typedef std::unique_ptr<object> object_ptr;
// JSON Array
typedef std::vector<value_ptr> array;
typedef std::unique_ptr<array> array_ptr;
// Saved Value
typedef std::variant<string, number, object_ptr, array_ptr> union_value;
public:
value() : type(Null) { }
value(const value&) = delete;
value& operator=(const value&) = delete;
value(value&& val);
value& operator=(value&& val);
// For String
value(const char *val) : type(String), uv(string(val)) { }
value(const string& val) : type(String), uv(val) { }
value(string&& val) : type(String), uv(std::move(val)) { }
value& operator=(const char *val);
value& operator=(const string& val);
value& operator=(string&& val);
// For Number
template <typename T,
typename = std::enable_if_t<std::is_arithmetic_v<T>>>
value(T val) : type(Number), uv(static_cast<number>(val)) { }
template <typename T,
typename = std::enable_if_t<std::is_arithmetic_v<T>>>
value& operator=(T val)
{
type = Number;
uv = static_cast<number>(val);
return *this;
}
// For Boolean
value(bool val) : type(val ? True : False), uv{} { }
value& operator=(bool val);
// For Null
value(std::nullptr_t val) : type(Null), uv{} { }
value& operator=(std::nullptr_t val);
// Init an Array by list
template <typename T>
value(std::initializer_list<T> l);
template <typename T>
value& operator=(std::initializer_list<T> l);
// The value can be any other ValueType,
// which we override as Object.
value& operator[](const string& key);
value& at(const string& key);
// The value can be any other ValueType,
// which we override as Array;
template <typename T>
value& append(T&& val);
template <typename T>
value& append(std::initializer_list<T> l);
// The value must be an Array, and ensure that
// the subscript access does not exceed the bounds.
value& operator[](size_t i);
value& at(size_t i);
// Swap value
void swap(value& other);
// Judge value type
ValueType get_type() { return type; }
bool is_string() { return type == String; }
bool is_number() { return type == Number; }
bool is_object() { return type == Object; }
bool is_array() { return type == Array; }
bool is_true() { return type == True; }
bool is_false() { return type == False; }
bool is_null() { return type == Null; }
// Take out value
string& as_string() { return std::get<string>(uv); }
number as_number() { return std::get<number>(uv); }
object& as_object() { return *std::get<object_ptr>(uv); }
array& as_array() { return *std::get<array_ptr>(uv); }
// Parser and writer wrapper
//
// If parse fails, the error str is saved in value,
// you can get it by as_string().
bool parse(const char *s);
bool parse(const std::string& s);
bool parse(const char *s, size_t len);
bool parsefile(const std::string& filename);
void dump(std::string& s, int spaces = 0);
private:
// For Object
value(object&& val) : type(Object), uv(object_ptr(new object(std::move(val)))) { }
value& operator=(object&& val);
// For Array
value(array&& val) : type(Array), uv(array_ptr(new array(std::move(val)))) { }
value& operator=(array&& val);
ValueType type;
union_value uv;
friend class parser;
friend class writer;
};
value::value(value&& val) : type(val.type), uv(std::move(val.uv))
{
val.type = Null;
}
value& value::operator=(value&& val)
{
swap(val);
return *this;
}
value& value::operator=(const char *val)
{
return operator=(string(val));
}
value& value::operator=(const string& val)
{
type = String;
uv.emplace<string>(val);
return *this;
}
value& value::operator=(string&& val)
{
type = String;
uv.emplace<string>(std::move(val));
return *this;
}
value& value::operator=(bool val)
{
type = val ? True : False;
uv = { };
return *this;
}
value& value::operator=(std::nullptr_t val)
{
type = Null;
uv = { };
return *this;
}
value& value::operator=(object&& val)
{
type = Object;
uv = object_ptr(new object(std::move(val)));
return *this;
}
value& value::operator=(array&& val)
{
type = Array;
uv = array_ptr(new array(std::move(val)));
return *this;
}
template <typename T>
value::value(std::initializer_list<T> l) : type(Array), uv(array_ptr(new array()))
{
for (auto& e : l)
as_array().emplace_back(new value(e));
}
template <typename T>
value& value::operator=(std::initializer_list<T> l)
{
*this = array();
for (auto& e : l)
as_array().emplace_back(new value(e));
return *this;
}
value& value::operator[](const string& key)
{
if (type != Object) {
*this = object();
}
auto& o = as_object();
if (!o.count(key)) {
o.emplace(key, new value());
}
return *o[key];
}
value& value::at(const string& key)
{
return operator[](key);
}
template <typename T>
value& value::append(T&& val)
{
if (type != Array) {
*this = array();
}
as_array().emplace_back(new value(std::move(val)));
return *this;
}
template <typename T>
value& value::append(std::initializer_list<T> l)
{
if (type != Array) {
*this = array();
}
as_array().emplace_back(new value(l));
return *this;
}
value& value::operator[](size_t i)
{
return *as_array()[i];
}
value& value::at(size_t i)
{
return *as_array().at(i);
}
void value::swap(value& other)
{
std::swap(type, other.type);
uv.swap(other.uv);
other.type = Null;
}
//////////////////// Parser ////////////////////
enum error_code {
invalid_value_type,
invalid_object,
invalid_array,
invalid_string_tab,
invalid_string_break,
invalid_escape,
invalid_unicode,
invalid_unicode_surrogate,
invalid_number,
number_out_of_range,
invalid_true,
invalid_false,
invalid_null,
incomplete,
extra,
};
class parser {
private:
typedef value::string string;
typedef value::number number;
typedef value::object object;
typedef value::object_ptr object_ptr;
typedef value::array array;
typedef value::array_ptr array_ptr;
typedef value::value_ptr value_ptr;
public:
parser() = default;
~parser() = default;
parser(const parser&) = delete;
parser& operator=(const parser&) = delete;
bool parse(value& value, const char *s, size_t len)
{
charstream.reset(new string_stream(this, s, len));
return parse(value);
}
bool parsefile(value& value, const std::string& filename)
{
charstream.reset(new file_stream(this, filename));
return parse(value);
}
error_code get_error_code() { return errcode; }
static const char *get_error_string(error_code code);
private:
// Abstract the input to a stream of characters
struct char_stream {
char_stream(parser *psr) : parser(psr) { }
virtual ~char_stream() { }
// Extracts a character
virtual int nextchar() = 0;
// Unextracts a character
virtual void backward() = 0;
// At the end of the stream ?
virtual bool eof() = 0;
// Reaches the next non-whitespace character
int skipspace()
{
while (isspace(nextchar())) ;
return parser->c;
}
// Set parser.c to cur character
parser *parser;
};
// This is where we catch the exception,
// and provide the error code to user.
bool parse(value& value)
{
try {
value = std::move(parse_value());
while (!eof() && isspace(nextchar())) ;
if (!eof()) throw extra;
} catch (error_code code) {
errcode = code;
return false;
}
return true;
}
value parse_value()
{
skipspace();
switch (c) {
case '{': return parse_object();
case '[': return parse_array();
case '"': return parse_string();
case 't': return parse_constant("true");
case 'f': return parse_constant("false");
case 'n': return parse_constant("null");
default: return parse_number();
}
}
object parse_object()
{
object o;
skipspace();
if (c == '}') return o;
backward();
while (true) {
skipspace();
if (c != '"') throw invalid_object;
auto key = parse_string();
skipspace();
if (c != ':') throw invalid_object;
value *value = new class value(parse_value());
auto it = o.emplace(key, value);
// For the same key, the old value will be overwritten
if (!it.second) o[key] = value_ptr(value);
skipspace();
if (c == '}') break;
if (c != ',') throw invalid_object;
}
return o;
}
array parse_array()
{
array a;
skipspace();
if (c == ']') return a;
backward();
while (true) {
a.emplace_back(new value(parse_value()));
skipspace();
if (c == ']') break;
if (c != ',') throw invalid_array;
}
return a;
}
void parse_escape(string& s)
{
switch (nextchar()) {
case '"': s.push_back('\"'); break;
case '\\': s.push_back('\\'); break;
case '/': s.push_back('/'); break;
case 'b': s.push_back('\b'); break;
case 'f': s.push_back('\f'); break;
case 'n': s.push_back('\n'); break;
case 'r': s.push_back('\r'); break;
case 't': s.push_back('\t'); break;
case 'u': encode_unicode(s); break;
default: throw invalid_escape;
}
}
string parse_string()
{
string s;
while (true) {
switch (nextchar()) {
case '\\': parse_escape(s); break;
case '\"': return s;
case '\t': throw invalid_string_tab;
case '\n': throw invalid_string_break;
default: s.push_back(c); break;
}
}
}
void nextsave(std::string& s)
{
s.push_back(nextchar());
}
void skipnumber(std::string& s)
{
while (!eof() && isnumber(c)) {
nextsave(s);
}
}
// We just do the number format check,
// then call stod() to convert.
number parse_number()
{
std::string s;
if (!isnumber(c) && c != '-') {
throw invalid_value_type;
}
s.push_back(c);
if (c == '-') nextsave(s);
if (c == '0' && !eof()) {
nextsave(s);
if (isnumber(c)) throw invalid_number;
} else if (isnumber(c)) {
skipnumber(s);
}
if (c == '.') {
nextsave(s);
if (!isnumber(c)) throw invalid_number;
skipnumber(s);
}
if (c == 'e' || c == 'E') {
nextsave(s);
if (c == '+' || c == '-') nextsave(s);
if (!isnumber(c)) throw invalid_number;
skipnumber(s);
}
if (!isnumber(c)) backward();
try {
return std::stod(s);
} catch (std::out_of_range& e) {
throw number_out_of_range;
} catch (std::invalid_argument& e) {
throw invalid_number;
}
}
value parse_constant(const char *s)
{
for (const char *p = s + 1; *p != '\0'; p++) {
if (*p != nextchar()) {
switch (s[0]) {
case 't': throw invalid_true;
case 'f': throw invalid_false;
case 'n': throw invalid_null;
}
}
}
switch (s[0]) {
case 't': return value(true);
case 'f': return value(false);
case 'n': return value();
default: assert(0);
}
}
unsigned fromhex()
{
nextchar();
if (isnumber(c)) return (c - '0');
else if (ishexnumber(c)) return (toupper(c) - 'A') + 10;
else throw invalid_unicode;
}
unsigned parse_hex4()
{
return (fromhex() << 12) | (fromhex() << 8) | (fromhex() << 4) | (fromhex());
}
// Only support UTF-8
// +----------------------------------------------------------------+
// | range | byte-1 | byte-2 | byte-3 | byte-4 |
// +----------------------------------------------------------------|
// | U+0000 ~ U+007F | 0xxxxxxx | | | |
// |----------------------------------------------------------------|
// | U+0080 ~ U+07FF | 110xxxxx | 10xxxxxx | | |
// |----------------------------------------------------------------|
// | U+0800 ~ U+FFFF | 1110xxxx | 10xxxxxx | 10xxxxxx | |
// |----------------------------------------------------------------|
// | U+10000 ~ U+10FFFF | 11110xxx | 10xxxxxx | 10xxxxxx | 10xxxxxx |
// +----------------------------------------------------------------+
void encode_unicode(std::string& s)
{
unsigned u = parse_hex4();
if (u >= 0xD800 && u <= 0xDBFF) { // SURROGATE-PAIR
if (nextchar() != '\\') throw invalid_unicode_surrogate;
if (nextchar() != 'u') throw invalid_unicode_surrogate;
unsigned u2 = parse_hex4();
if (u2 < 0xDC00 || u2 > 0xDFFF) throw invalid_unicode_surrogate;
u = (((u - 0xD800) << 10) | (u2 - 0xDC00)) + 0x10000;
}
if (u <= 0x7F) {
s.push_back(u & 0xFF);
} else if (u >= 0x80 && u <= 0x7FF) {
s.push_back(0xC0 | ((u >> 6) & 0xFF));
s.push_back(0x80 | ( u & 0x3F));
} else if (u >= 0x800 && u <= 0xFFFF) {
s.push_back(0xE0 | ((u >> 12) & 0xFF));
s.push_back(0x80 | ((u >> 6) & 0x3F));
s.push_back(0x80 | ( u & 0x3F));
} else {
assert(u <= 0x10FFFF);
s.push_back(0xF0 | ((u >> 18) & 0xFF));
s.push_back(0x80 | ((u >> 12) & 0x3F));
s.push_back(0x80 | ((u >> 6) & 0x3F));
s.push_back(0x80 | ( u & 0x3F));
}
}
int nextchar() { return charstream->nextchar(); }
int skipspace() { return charstream->skipspace(); }
void backward() { charstream->backward(); }
bool eof() { return charstream->eof(); }
struct string_stream : char_stream {
string_stream(class parser *psr, const char *s, size_t len)
: char_stream(psr), p(s), end(s + len) { }
int nextchar() override
{
if (p == end) throw incomplete;
return parser->c = *p++;
}
void backward() override { p--; }
bool eof() override { return p == end; }
const char *p, *end;
};
struct file_stream : char_stream {
file_stream(class parser *psr, const std::string& filename)
: char_stream(psr), ifs(filename) { }
int nextchar() override
{
if (ifs.eof()) throw incomplete;
return parser->c = ifs.get();
}
void backward() override { ifs.unget(); }
bool eof() override { return ifs.eof(); }
std::ifstream ifs;
};
int c; // cur valid character
std::unique_ptr<char_stream> charstream;
error_code errcode;
};
const char *parser::get_error_string(error_code code)
{
static constexpr const char *error_code_map[] = {
"invalid_value_type",
"invalid_object",
"invalid_array",
"invalid_string_tab",
"invalid_string_break",
"invalid_escape",
"invalid_unicode",
"invalid_unicode_surrogate",
"invalid_number",
"number_out_of_range",
"invalid_true",
"invalid_false",
"invalid_null",
"incomplete",
"extra",
};
return error_code_map[code];
}
//////////////////// Writer ////////////////////
class writer {
private:
typedef value::string string;
public:
writer() = default;
~writer() = default;
writer(const writer&) = delete;
writer& operator=(const writer&) = delete;
// The default format is compact.
// Or you can visualize it in a 2, 4, or 8 space indentation format.
void dump(value& value, std::string& s, int spaces = 0)
{
visual_init(spaces);
buf.clear();
dump_value(value);
buf.swap(s);
}
private:
void visual_init(int spaces)
{
if (spaces > 8) {
spaces = 8; // 8-space indent is enough!
}
if (spaces > 0) {
visual = true;
indent_spaces = spaces;
} else {
visual = false;
indent_spaces = 0;
}
cur_level = 0;
}
void dump_value(value& value)
{
auto type = value.get_type();
switch (type) {
case String: dump_string(value); break;
case Number: dump_number(value); break;
case Object: dump_object(value); break;
case Array: dump_array(value); break;
case True: dump_true(value); break;
case False: dump_false(value); break;
case Null: dump_null(value); break;
}
}
void dump_string(const string& s)
{
buf.push_back('\"');
decode_unicode(s);
buf.push_back('\"');
}
void dump_string(value& value)
{
dump_string(value.as_string());
}
void dump_number(value& value)
{
buf.append(std::to_string(value.as_number()));
}
void dump_object(value& value)
{
int level = cur_level;
cur_level += indent_spaces;
buf.push_back('{');
add_newline();
for (auto& [k, v] : value.as_object()) {
add_spaces();
dump_string(k);
buf.append(":");
dump_value(*v);
buf.append(",");
add_newline();
}
cur_level = level;
handle_right_indent('}');
}
void dump_array(value& value)
{
int level = cur_level;
cur_level += indent_spaces;
buf.push_back('[');
add_newline();
for (auto& e : value.as_array()) {
add_spaces();
dump_value(*e);
buf.append(",");
add_newline();
}
cur_level = level;
handle_right_indent(']');
}
void dump_true(value& value)
{
buf.append("true");
}
void dump_false(value& value)
{
buf.append("false");
}
void dump_null(value& value)
{
buf.append("null");
}
void add_newline()
{
if (visual) buf.push_back('\n');
}
void add_spaces()
{
if (visual) buf.append(cur_level, ' ');
}
void handle_right_indent(int c)
{
if (visual) {
buf.pop_back();
buf.back() = '\n';
add_spaces();
buf.push_back(c);
} else {
buf.back() = c;
}
}
void put_unicode(int c1, int c2, int c3, int c4)
{
static const char *tohex = "0123456789ABCDEF";
buf.push_back('\\');
buf.push_back('u');
buf.push_back(tohex[c1]);
buf.push_back(tohex[c2]);
buf.push_back(tohex[c3]);
buf.push_back(tohex[c4]);
}
void decode_unicode(const string& s)
{
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (!(c & 0x80)) {
// 1 bit is treated as an ASCII character,
// in which case UTF-8 is compatible with ASCII.
buf.push_back(c);
} else if ((c & 0xE0) == 0xC0) { // 110xxxxx
if (i + 1 >= s.size()) throw invalid_unicode;
char c2 = s[++i];
// xxx|xx xx|xxxx
put_unicode(0,
(c & 0x1C) >> 2,
((c & 0x03) << 2) | ((c2 & 0x30) >> 4),
(c2 & 0x0F));
} else if ((c & 0xF0) == 0xE0) { // 1110xxxx
if (i + 2 >= s.size()) throw invalid_unicode;
char c2 = s[++i], c3 = s[++i];
// xxxx |xxxx|xx xx|xxxx
put_unicode((c & 0x0F),
(c2 & 0x3C) >> 2,
((c2 & 0x03) << 2) | ((c3 & 0x30) >> 4),
(c3 & 0x0F));
} else { // SURROGATE-PAIR
assert((c & 0xF8) == 0xF0); // 11110xxx
if (i + 3 >= s.size()) throw invalid_unicode;
char c2 = s[++i], c3 = s[++i], c4 = s[++i];
unsigned u = 0;
u = (u | (c & 0x07)) << 6;
u = (u | (c2 & 0x3F)) << 6;
u = (u | (c3 & 0x3F)) << 6;
u = (u | (c4 & 0x3F));
u -= 0x10000;
unsigned u1 = (u >> 10) + 0xD800;
unsigned u2 = (u & 0x3FF) + 0xDC00;
put_unicode((u1 >> 12) & 0x0F, (u1 >> 8) & 0x0F, (u1 >> 4) & 0x0F, (u1 & 0x0F));
put_unicode((u2 >> 12) & 0x0F, (u2 >> 8) & 0x0F, (u2 >> 4) & 0x0F, (u2 & 0x0F));
}
}
}
std::string buf;
bool visual;
int indent_spaces; // A few spaces to indent
int cur_level; // Current indent level
};
bool value::parse(const char *s)
{
return parse(s, ::strlen(s));
}
bool value::parse(const std::string& s)
{
return parse(s.data(), s.size());
}
bool value::parse(const char *s, size_t len)
{
parser parser;
if (parser.parse(*this, s, len)) return true;
*this = parser.get_error_string(parser.get_error_code());
return false;
}
bool value::parsefile(const std::string& filename)
{
parser parser;
if (parser.parsefile(*this, filename)) return true;
*this = parser.get_error_string(parser.get_error_code());
return false;
}
void value::dump(std::string& s, int spaces)
{
writer writer;
writer.dump(*this, s, spaces);
}
}
#endif // _JSON_H