forked from davidmoreno/json11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson11.cpp
748 lines (672 loc) · 18.2 KB
/
json11.cpp
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
/*
* This file is part of json11 project (https://github.com/borisgontar/json11).
*
* Copyright (c) 2013 Boris Gontar.
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
// Version 0.6.5, 2013-11-07
#include "include/json11.h"
#include <assert.h>
#include <cmath>
#include <cfloat>
#include <climits>
#include <sstream>
#include <iomanip>
#include <algorithm>
using namespace std;
#ifdef TEST
vector<Json::Node*> Json::Node::nodes;
void Json::Node::test() {
if (nodes.size() == 0) {
cout << "nodes ok\n";
return;
}
for (Node* it : nodes) {
cout << it->refcnt << ' ' << (int)it->type() << '\n';
}
}
#endif
Json::Node Json::Node::null(1);
Json::Node Json::Node::undefined(1);
Json Json::null;
Json Json::undefined(&Node::undefined);
Json::Bool Json::Bool::T(true);
Json::Bool Json::Bool::F(false);
set<string> Json::keyset;
int Json::indent;
int Json::level;
static unsigned currpos(istream& in, unsigned* pos) {
unsigned curr = in.tellg();
if (pos != nullptr)
*pos = 0;
in.seekg(0); // rewind
if (in.bad())
return 0;
unsigned count = 0, line = 1, col = 1;
while (!in.eof() && !in.fail() && ++count < curr) {
if (in.get() == '\n') {
++line;
col = 1;
} else
++col;
}
if (pos != nullptr)
*pos = col;
return line;
}
Json::parse_error::parse_error(const char* msg, std::istream& in) : std::runtime_error(msg) {
line = currpos(in, &col);
}
// Node and helper classes
Json::Node::Node(unsigned init) {
refcnt = init;
#ifdef TEST
if (this != &null && this != &undefined && this != &Bool::T && this != &Bool::F)
nodes.push_back(this);
#endif
}
Json::Node::~Node() {
assert(this == &null || this == &undefined || this == &Bool::T || this == &Bool::F || refcnt == 0);
#ifdef TEST
if (this == &null || this == &undefined || this == &Bool::T || this == &Bool::F)
return;
auto it = find(nodes.begin(), nodes.end(), this);
assert(it != nodes.end());
nodes.erase(it);
#endif
}
void Json::Node::unref() {
if (this == &null || this == &undefined || this == &Bool::T || this == &Bool::F )
return;
assert(refcnt > 0);
if (--refcnt == 0)
delete this;
}
bool Json::Array::operator == (const Node& that) const {
if (this == &that)
return true;
if (that.type() != Type::ARRAY)
return false;
vector<Node*>& that_list = ((Array*)&that)->list;
return equal(list.begin(), list.end(), that_list.begin(),
[](Node* n1, Node* n2){ return *n1 == *n2; });
}
bool Json::Object::operator == (const Node& that) const {
if (this == &that)
return true;
if (that.type() != Type::OBJECT)
return false;
std::map<const string*, Node*>& that_map = ((Object*)&that)->map;
typedef pair<const string*, Node*> kv;
return equal(map.begin(), map.end(), that_map.begin(),
[](kv p, kv q){ return *p.first == *q.first && *p.second == *q.second; });
}
bool Json::Number::operator == (const Node& that) const {
if (this == &that)
return true;
if (that.type() != Type::NUMBER)
return false;
Number& numb = *(Number*)&that;
if (fabs(value) < LDBL_EPSILON)
return fabs(numb.value) < LDBL_EPSILON;
long double delta = fabs((value - numb.value)/value);
int digs = max(prec, numb.prec);
return delta < pow(10, -digs);
}
bool Json::Array::contains(const Node* that) const {
if (this == that)
return true;
for (Node* it : list) {
if (it->contains(that))
return true;
}
return false;
}
bool Json::Object::contains(const Node* that) const {
if (this == that)
return true;
for (auto it : map) {
if (it.second->contains(that))
return true;
}
return false;
}
/** Copy constructor. */
Json::Json(const Json& that) {
(root = that.root)->refcnt++;
}
/** Move constructor. */
Json::Json(Json&& that) {
root = that.root;
that.root = nullptr;
}
Json::Json(std::initializer_list<Json> args) {
(root = new Array())->refcnt++;
for (auto arg : args)
*this << arg;
}
/** Copy assignment */
Json& Json::operator = (const Json& that) {
root->unref();
(root = that.root)->refcnt++;
return *this;
}
/** Move assignment */
Json& Json::operator = (Json&& that) {
root->unref();
root = that.root;
that.root = nullptr;
return *this;
}
Json::~Json() {
if (root != nullptr)
root->unref();
}
Json::Object* Json::mkobject() {
if (root->type() == Type::JSNULL) {
root = new Object();
root->refcnt++;
}
if (root->type() != Type::OBJECT)
throw use_error("method not applicable");
return (Object*)root;
}
Json& Json::set(string key, const Json& val) {
assert(val.root != nullptr);
if (val.root->contains(root))
throw use_error("cyclic dependency");
mkobject()->set(key, val.root);
return *this;
}
Json::Array* Json::mkarray() {
if (root->type() == Type::JSNULL) {
root = new Array();
root->refcnt++;
}
if (root->type() != Type::ARRAY)
throw use_error("method not applicable");
return (Array*)root;
}
Json& Json::operator << (const Json& that) {
if (that.root->contains(root))
throw use_error("cyclic dependency");
mkarray()->add(that.root);
return *this;
}
void Json::insert(int index, const Json& that) {
if (that.root->contains(root))
throw use_error("cyclic dependency");
mkarray()->ins(index, that.root);
}
Json& Json::replace(int index, const Json& that) {
if (that.root->contains(root))
throw use_error("cyclic dependency");
mkarray()->repl(index, that.root);
return *this;
}
void Json::erase(int index) {
mkarray()->del(index);
}
Json Json::Property::operator = (const Json& that) {
if (host->type() == Type::OBJECT)
((Object*)host)->set(key, that.root);
else if (host->type() == Type::ARRAY)
((Array*)host)->repl(index, that.root);
else
throw logic_error("Property::operator =");
return target();
}
Json Json::Property::operator = (const Property& that) {
return (*this = that.target());
}
Json::Property Json::operator [] (int index) {
return Property(mkarray(), index);
}
Json::Property Json::operator [] (const string& key) {
return Property(mkobject(), key);
}
size_t Json::size() const {
if (root->type() == Type::ARRAY)
return ((Array*)root)->list.size();
if (root->type() == Type::OBJECT)
return ((Object*)root)->map.size();
throw use_error("method not applicable");
}
Json Json::get(const string& key) const {
if (root->type() != Type::OBJECT)
throw use_error("method not applicable");
Node* n = ((Object*)root)->get(key);
return n == nullptr ? undefined : Json(n);
}
bool Json::has(const string& key) const {
if (root->type() != Type::OBJECT)
throw use_error("method not applicable");
auto kp = keyset.find(key);
if (kp == keyset.end())
return false;
Object* obj = (Object*)root;
auto it = obj->map.find(&*kp);
return it != obj->map.end();
}
Json::Property::Property(Node* node, const string& key) : host(node) {
if (node->type() != Type::OBJECT)
throw use_error("method not applicable");
this->key = key;
index = -1;
}
Json::Property::Property(Node* node, int index) : host(node) {
if (node->type() != Type::ARRAY)
throw use_error("method not applicable");
key = "";
this->index = index;
}
Json Json::Property::target() const {
if (host->type() == Type::OBJECT)
return ((Object*)host)->get(key);
if (host->type() == Type::ARRAY)
return ((Array*)host)->list.at(index);
throw logic_error("Property::operator Json()");
}
vector<string> Json::keys() {
if (root->type() != Type::OBJECT)
throw use_error("method not applicable");
Object* op = (Object*)root;
vector<string> ret;
for (auto it : op->map)
ret.push_back(*it.first);
return ret;
}
bool Json::String::operator == (const Node& that) const {
return this == &that ||
(that.type() == Type::STRING && value == ((String*)&that)->value);
}
void Json::Bool::print(ostream& out) const {
out << (this == &Bool::T ? "true" : "false");
}
void Json::Number::print(ostream& out) const {
if (prec >= 0)
out << setprecision(prec);
out << value;
}
static void escape(ostream& out, const string& str) {
out << '"';
for (char c : str) {
switch (c) {
case '"':
out << '\\' << '"';
break;
case '\\':
out << c << c;
break;
case '\b':
out << '\\' << 'b';
break;
case '\f':
out << '\\' << 'f';
break;
case '\n':
out << '\\' << 'n';
break;
case '\r':
out << '\\' << 'r';
break;
case '\t':
out << '\\' << 't';
break;
default:
out << c;
}
}
out << '"';
}
void Json::String::print(ostream& out) const {
escape(out, value);
}
void Json::Object::traverse(void (*f)(const Node*)) const {
for (auto it : map)
f(it.second);
}
void Json::Array::traverse(void (*f)(const Node*)) const {
for (auto it : list)
f(it);
}
void Json::Object::print(ostream& out) const {
out << '{';
++level;
bool comma = false;
for (auto it : map) {
if (comma)
out << ',';
if (indent)
out << '\n' << string(indent*level, ' ');
escape(out, *it.first);
out << ':';
if (indent)
out << ' ';
it.second->print(out);
comma = true;
}
--level;
out << '}';
}
void Json::Array::print(ostream& out) const {
out << '[';
++level;
bool comma = false;
for (const Node* it : list) {
if (comma)
out << ',';
if (indent)
out << '\n' << string(indent*level, ' ');
it->print(out);
comma = true;
}
--level;
out << ']';
}
Json::Object::~Object() {
for (auto it : map) {
Node* np = it.second;
np->unref();
}
map.clear();
}
Json::Node* Json::Object::get(const string& key) const {
auto kp = keyset.find(key);
if (kp == keyset.end())
return nullptr;
auto it = map.find(&*kp);
if (it == map.end())
return nullptr;
return it->second;
}
void Json::Object::set(const string& k, Node* v) {
assert(v != nullptr);
auto kit = keyset.insert(keyset.begin(), k);
auto it = map.find(&*kit);
if (it != map.end()) {
Node* np = it->second;
np->unref();
it->second = v;
} else
map[&*kit] = v;
v->refcnt++;
}
Json::Array::~Array() {
for (Node* it : list)
it->unref();
list.clear();
}
void Json::Array::add(Node* v) {
assert(v != nullptr);
list.push_back(v);
v->refcnt++;
}
/** Inserts given Node* before index. */
void Json::Array::ins(int index, Node* v) {
assert(v != nullptr);
if (index < 0)
index += list.size();
if (index < 0 || index > (int)list.size())
throw out_of_range("index out of range");
list.insert(list.begin() + index, v);
v->refcnt++;
}
void Json::Array::del(int index) {
if (index < 0)
index += list.size();
Node* v = list.at(index);
v->unref();
list.erase(list.begin() + index);
}
void Json::Array::repl(int index, Node* v) {
if (index < 0)
index += list.size();
Node* u = list.at(index);
u->unref();
list[index] = v;
v->refcnt++;
}
ostream& operator << (ostream& out, const Json& json) {
json.root->print(out);
return out;
}
istream& operator >> (istream& in, Json& json) {
json.root->unref();
Json temp(in);
json.root = temp.root;
temp.root = nullptr;
return in;
}
Json::String::String(istream& in) {
int quote = in.get();
while (!in.eof()) {
int c = in.get();
if (c == char_traits<char>::eof())
throw parse_error("unterminated string", in);
if (c == quote)
return;
if (c == '\\') {
c = in.get();
if (c == quote || c == '\\' || c == '/')
value.push_back(c);
else if (c == 'n')
value.push_back('\n');
else if (c == 't')
value.push_back('\t');
else if (c == 'r')
value.push_back('\r');
else if (c == 'b')
value.push_back('\b');
else if (c == 'f')
value.push_back('\f');
else if (c == 'u') {
unsigned w = 0;
for (int i = 0; i < 4; i++) {
if (!isxdigit(c = toupper(in.get())))
throw parse_error("not a hex digit", in);
w = (w << 4) | (isdigit(c) ? c - '0' : c - 'A' + 10);
}
// garbage in, garbage out
if (w <= 0x7f)
value.push_back(w);
else if (w <= 0x07ff) {
value.push_back(0xc0 | ((w >> 6) & 0x1f));
value.push_back(0x80 | (w & 0x3f));
} else {
value.push_back(0xe0 | ((w >> 12) & 0x0f));
value.push_back(0x80 | ((w >> 6) & 0x3f));
value.push_back(0x80 | (w & 0x3f));
}
}
else
throw parse_error("illegal backslash escape", in);
continue;
}
if (iscntrl(c))
throw parse_error("control character in string", in);
value.push_back(c);
}
}
Json::Number::Number(istream& in) {
char buf[128];
const char* end = buf+126;
char* p = buf;
char c;
bool leading = true;
while ((isdigit(c = in.get()) || (leading && c == '-')) && p < end) {
*p++ = c;
leading = false;
}
prec = p - buf;
if (c == '.' && p < end) {
*p++ = c;
while (isdigit(c = in.get()) && p < end)
*p++ = c;
prec = p - buf - 1;
}
if ((c == 'e' || c == 'E') && p < end) {
*p++ = c;
leading = true;
while ((isdigit(c = in.get()) || (leading && (c == '-' || c == '+'))) && p < end) {
*p++ = c;
leading = false;
}
}
*p = 0;
in.putback(c);
char* eptr = nullptr;
long double num = strtold(buf, &eptr);
if (eptr != p)
throw parse_error("illegal number format", in);
value = num;
}
Json::Json(istream& in, bool full) {
char c;
string word;
root = nullptr;
if (!(in >> c))
goto out;
if (c == '[') {
root = new Array();
root->refcnt++;
while (in >> c) {
if (c == ']')
goto out;
in.putback(c);
Json elem(in, false);
*this << elem;
in >> c;
if (c == ',')
continue;
in.putback(c);
}
throw parse_error("comma or closing bracket expected", in);
}
if (c == '{') {
root = new Object();
root->refcnt++;
while (in >> c) {
if (c == '}')
goto out;
in.putback(c);
Json key(in, false);
if (key.root->type() != Type::STRING)
throw parse_error("a string expected", in);
in >> c;
if (c != ':')
throw parse_error("a colon expected", in);
Json obj(in, false);
set(key, obj);
in >> c;
if (c == ',')
continue;
in.putback(c);
}
throw parse_error("comma or closing bracket expected", in);
}
if (isdigit(c) || c == '-') {
in.putback(c);
root = new Number(in);
root->refcnt++;
goto out;
}
if (c == '\"' || c == '\'') {
in.putback(c);
root = new String(in);
root->refcnt++;
goto out;
}
word.push_back(c);
for (int i = 0; i < 3; i++)
word.push_back(in.get());
if (word == "null") {
root = &Node::null;
root->refcnt++;
goto out;
}
if (word == "true") {
root = &Bool::T;
root->refcnt++;
goto out;
}
if (word == "fals" && in.get() == 'e') {
root = &Bool::F;
root->refcnt++;
goto out;
}
throw parse_error("json format error", in);
out:
if (full) {
if (in.peek() == char_traits<char>::eof())
return;
while (isspace(in.get()))
/* skip */;
if (in.eof())
return;
throw parse_error("excess text not parsed", in);
}
}
string Json::format() {
ostringstream is("");
is << *this;
return is.str();
}
Json Json::parse(const string& str) {
istringstream is(str);
Json parsed(is);
if (is.peek() == char_traits<char>::eof())
return parsed;
while (isspace(is.get()))
/* skip */;
if (is.eof())
return parsed;
throw parse_error("json format error", is);
}
Json::operator std::string() const {
if (root->type() == Type::STRING)
return ((String*)root)->value;
throw bad_cast();
}
Json::operator long double() const {
if (root->type() == Type::NUMBER)
return ((Number*)root)->value;
throw bad_cast();
}
Json::operator double() const {
if (root->type() == Type::NUMBER)
return ((Number*)root)->value;
throw bad_cast();
}
Json::operator float() const {
if (root->type() == Type::NUMBER) {
return ((Number*)root)->value;
}
throw bad_cast();
}
Json::operator int() const {
if (root->type() == Type::NUMBER)
return ((Number*)root)->value;
throw bad_cast();
}
Json::operator long() const {
if (root->type() == Type::NUMBER)
return ((Number*)root)->value;
throw bad_cast();
}
Json::operator long long() const {
if (root->type() == Type::NUMBER)
return ((Number*)root)->value;
throw bad_cast();
}
Json::operator bool() const {
if (root->type() == Type::BOOL)
return root == &Bool::T;
throw bad_cast();
}
bool Json::operator == (const Json& that) const {
if (root == that.root)
return true;
return *root == *that.root;
}