-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtinyjson.cpp
executable file
·643 lines (551 loc) · 16.8 KB
/
tinyjson.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
#include "tinyjson.hpp"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <string_view>
#include <utility>
namespace tinyjson
{
/* Utility to jump whitespace and cr/lf */
const char* skip(const char* in)
{
while (in && *in && (unsigned char)*in <= 32)
in++;
return in;
}
/* Parse the input text into an unescaped cstring, and populate item. */
thread_local const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
/// escape `in` to a printable version
std::string& escape_string(const std::string_view& str, std::string* escaped)
{
const char* ptr = nullptr;
char *ptr2 = nullptr, *out = nullptr;
int len = 0;
unsigned char token;
if (str.empty()) {
return *escaped;
}
ptr = str.data();
while ((token = *ptr) && ++len) {
if (strchr("\"\\\b\f\n\r\t", token))
len++;
else if (token < 32)
len += 5;
ptr++;
}
escaped->resize(len + 2);
out = escaped->data();
ptr2 = out;
ptr = str.data();
*ptr2++ = '\"';
while (*ptr) {
if ((unsigned char)*ptr > 31 && *ptr != '\"' && *ptr != '\\')
*ptr2++ = *ptr++;
else {
*ptr2++ = '\\';
switch (token = *ptr++) {
case '\\':
*ptr2++ = '\\';
break;
case '\"':
*ptr2++ = '\"';
break;
case '\b':
*ptr2++ = 'b';
break;
case '\f':
*ptr2++ = 'f';
break;
case '\n':
*ptr2++ = 'n';
break;
case '\r':
*ptr2++ = 'r';
break;
case '\t':
*ptr2++ = 't';
break;
default:
snprintf(ptr2, 6, "u%04x", token);
ptr2 += 6;
break; /* escape and print */
}
}
}
*ptr2++ = '\"';
return *escaped;
}
const char* element::parse_string(tinyjson::element* item, const char* str)
{
const char* ptr = str + 1;
char* ptr2;
int len = 0;
unsigned uc, uc2;
if (*str != '\"') {
return nullptr;
} /* not a string! */
while (*ptr != '\"' && *ptr && ++len)
if (*ptr++ == '\\')
ptr++; /* Skip escaped quotes. */
char* out = (char*)malloc(len + 1);
ptr = str + 1;
ptr2 = out;
while (*ptr != '\"' && *ptr) {
if (*ptr != '\\')
*ptr2++ = *ptr++;
else {
ptr++;
switch (*ptr) {
case 'b':
*ptr2++ = '\b';
break;
case 'f':
*ptr2++ = '\f';
break;
case 'n':
*ptr2++ = '\n';
break;
case 'r':
*ptr2++ = '\r';
break;
case 't':
*ptr2++ = '\t';
break;
case 'u': /* transcode utf16 to utf8. */
sscanf(ptr + 1, "%4x", &uc);
ptr += 4; /* get the unicode char. */
if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0)
break; // check for invalid.
if (uc >= 0xD800 && uc <= 0xDBFF) // UTF16 surrogate pairs.
{
if (ptr[1] != '\\' || ptr[2] != 'u')
break; // missing second-half of surrogate.
sscanf(ptr + 3, "%4x", &uc2);
ptr += 6;
if (uc2 < 0xDC00 || uc2 > 0xDFFF)
break; // invalid second-half of surrogate.
uc = 0x10000 | ((uc & 0x3FF) << 10) | (uc2 & 0x3FF);
}
len = 4;
if (uc < 0x80)
len = 1;
else if (uc < 0x800)
len = 2;
else if (uc < 0x10000)
len = 3;
ptr2 += len;
switch (len) {
case 4:
*--ptr2 = ((uc | 0x80) & 0xBF);
uc >>= 6;
case 3:
*--ptr2 = ((uc | 0x80) & 0xBF);
uc >>= 6;
case 2:
*--ptr2 = ((uc | 0x80) & 0xBF);
uc >>= 6;
case 1:
*--ptr2 = (uc | firstByteMark[len]);
}
ptr2 += len;
break;
default:
*ptr2++ = *ptr;
break;
}
ptr++;
}
}
*ptr2 = 0;
if (*ptr == '\"')
ptr++;
item->m_value.str = out;
item->m_kind = tinyjson::element_kind::T_STRING;
return ptr;
}
element::~element()
{
m_elements_map.clear();
m_children.clear();
if (m_kind == element_kind::T_STRING && m_value.str) {
free(m_value.str);
m_value.str = nullptr;
}
}
element::element() { memset(&m_value, 0, sizeof(m_value)); }
element::element(element&& other)
{
m_kind = other.m_kind;
m_elements_map.clear();
m_property_name = std::move(other.m_property_name);
m_value = other.m_value;
if (other.m_kind == element_kind::T_STRING) {
// ensure that no double free is occured
other.m_value.str = nullptr;
}
m_children = std::move(other.m_children);
m_elements_map = std::move(other.m_elements_map);
}
/* Parse the input text to generate a number, and populate the result into item. */
const char* element::parse_number(tinyjson::element* item, const char* num)
{
double n = 0, sign = 1, scale = 0;
int subscale = 0, signsubscale = 1;
/* Could use sscanf for this? */
if (*num == '-')
sign = -1, num++; /* Has sign? */
if (*num == '0')
num++; /* is zero */
if (*num >= '1' && *num <= '9')
do
n = (n * 10.0) + (*num++ - '0');
while (*num >= '0' && *num <= '9'); /* Number? */
if (*num == '.' && num[1] >= '0' && num[1] <= '9') {
num++;
do
n = (n * 10.0) + (*num++ - '0'), scale--;
while (*num >= '0' && *num <= '9');
} /* Fractional part? */
if (*num == 'e' || *num == 'E') /* Exponent? */
{
num++;
if (*num == '+')
num++;
else if (*num == '-')
signsubscale = -1, num++; /* With sign? */
while (*num >= '0' && *num <= '9')
subscale = (subscale * 10) + (*num++ - '0'); /* Number? */
}
n = sign * n * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
item->m_kind = tinyjson::element_kind::T_NUMBER;
item->m_value.number = n;
return num;
}
/* Build an array from input text. */
const char* element::parse_array(tinyjson::element* item, const char* value)
{
if (*value != '[') {
return nullptr;
} /* not an array! */
item->m_kind = tinyjson::element_kind::T_ARRAY;
value = skip(value + 1);
if (*value == ']')
return value + 1; /* empty array. */
auto& child = item->append_new();
value = skip(parse_value(&child, skip(value))); /* skip any spacing, get the value. */
if (!value)
return nullptr;
while (*value == ',') {
auto& child = item->append_new();
value = skip(parse_value(&child, skip(value + 1)));
if (!value)
return nullptr; /* memory fail */
}
if (*value == ']')
return value + 1; /* end of array */
return nullptr; /* malformed. */
}
/* Build an object from the text. */
const char* element::parse_object(tinyjson::element* item, const char* value)
{
if (*value != '{') {
return nullptr;
} // not an object
item->m_kind = tinyjson::element_kind::T_OBJECT;
value = skip(value + 1);
if (*value == '}')
return value + 1; // empty object
auto& child = item->append_new();
value = skip(parse_string(&child, skip(value)));
if (!value) {
return nullptr;
}
// parse the property name
child.m_property_name = child.m_value.str;
free(child.m_value.str);
child.m_value.str = nullptr;
if (*value != ':') {
// parse error
return nullptr;
}
// parse the property value
value = skip(parse_value(&child, skip(value + 1))); /* skip any spacing, get the value. */
if (!value)
return nullptr;
while (*value == ',') {
auto& child = item->append_new();
value = skip(parse_string(&child, skip(value + 1)));
if (!value) {
return nullptr;
}
child.m_property_name = child.m_value.str;
free(child.m_value.str);
child.m_value.str = nullptr;
if (*value != ':') {
// parse error
return nullptr;
}
// parse the property value
value = skip(parse_value(&child, skip(value + 1))); /* skip any spacing, get the value. */
if (!value)
return nullptr;
}
if (*value == '}')
return value + 1; /* end of array */
return nullptr; /* malformed. */
}
const char* element::parse_value(tinyjson::element* item, const char* value)
{
if (!value)
return nullptr; /* Fail on null. */
if (!strncmp(value, "null", 4)) {
item->m_kind = tinyjson::element_kind::T_NULL;
return value + 4;
}
if (!strncmp(value, "false", 5)) {
item->m_kind = tinyjson::element_kind::T_FALSE;
return value + 5;
}
if (!strncmp(value, "true", 4)) {
item->m_kind = tinyjson::element_kind::T_TRUE;
return value + 4;
}
if (*value == '\"') {
return parse_string(item, value);
}
if (*value == '-' || (*value >= '0' && *value <= '9')) {
return parse_number(item, value);
}
if (*value == '[') {
return parse_array(item, value);
}
if (*value == '{') {
return parse_object(item, value);
}
return nullptr; /* failure. */
}
void element::index_elements()
{
if (!m_children.empty()) {
m_elements_map.reserve(m_children.size());
for (auto& child : m_children) {
if (child.property_name()) {
m_elements_map.emplace(std::make_pair(child.property_name(), &child));
}
}
}
}
bool element::create_array(element* arr)
{
arr->m_kind = element_kind::T_ARRAY;
return true;
}
bool element::create_object(element* obj)
{
obj->m_kind = element_kind::T_OBJECT;
return true;
}
bool element::parse(const std::string& content, element* root)
{
if (!element::parse_value(root, skip(content.c_str()))) {
return false;
}
return true;
}
bool element::parse_file(const std::string& path, element* root)
{
// read the file content
std::string content;
FILE* file = fopen(path.c_str(), "rb");
// Check if there was an error.
if (file == nullptr) {
return false;
}
// Get the file length
fseek(file, 0, SEEK_END);
auto length = ftell(file);
fseek(file, 0, SEEK_SET);
content.resize(length);
// Set the contents of the string.
size_t bytes = fread(content.data(), sizeof(char), length, file);
// no need for the file pointer any more, close it
fclose(file);
// did we read all the file?
if (bytes != length) {
return false;
}
return parse(content, root);
}
thread_local element null_element;
const element& element::operator[](const char* index) const
{
if (m_children.empty()) {
return null_element;
}
if (m_elements_map.empty()) {
// need to index it first
const_cast<element&>(*this).index_elements();
}
if (m_elements_map.count(index) == 0) {
return null_element;
}
return *m_elements_map.find(index)->second;
}
element& element::operator[](const char* index)
{
if (m_children.empty()) {
return null_element;
}
if (m_elements_map.empty()) {
// need to index it first
const_cast<element&>(*this).index_elements();
}
if (m_elements_map.count(index) == 0) {
return null_element;
}
auto& elem = *m_elements_map.find(index)->second;
return elem;
}
const element& element::operator[](size_t index) const
{
if (index >= m_children.size()) {
return null_element;
}
return m_children[index];
}
element& element::operator[](size_t index)
{
if (index >= m_children.size()) {
return null_element;
}
return m_children[index];
}
element& element::add_property_internal(const std::string& name)
{
auto& elem = append_new();
elem.m_property_name = name;
// add new indexed entry
if (elem.property_name()) {
m_elements_map.insert({ elem.property_name(), &elem });
}
return elem;
}
element& element::add_element(element&& elem)
{
m_children.emplace_back(std::move(elem));
auto& item_added = m_children.back();
if (item_added.property_name()) {
m_elements_map.insert({ item_added.property_name(), &item_added });
}
return item_added;
}
element& element::add_array(const std::string& name)
{
element arr;
create_array(&arr);
arr.m_property_name = name;
return add_element(std::move(arr));
}
element& element::add_object(const std::string& name)
{
element obj;
create_object(&obj);
obj.m_property_name = name;
return add_element(std::move(obj));
}
element& element::add_property(const std::string& name, int value)
{
return add_property(name, static_cast<double>(value));
}
element& element::add_property(const std::string& name, long value)
{
return add_property(name, static_cast<double>(value));
}
element& element::add_property(const std::string& name, size_t value)
{
return add_property(name, static_cast<double>(value));
}
element& element::add_property(const std::string& name, double value)
{
auto& elem = add_property_internal(name);
elem.m_value.number = value;
elem.m_kind = element_kind::T_NUMBER;
return *this;
}
element& element::add_property(const std::string& name, const std::string& value)
{
auto& elem = add_property_internal(name);
elem.m_value.str = strdup(value.c_str());
elem.m_kind = element_kind::T_STRING;
return *this;
}
element& element::add_property(const std::string& name, const char* value)
{
auto& elem = add_property_internal(name);
elem.m_value.str = strdup(value);
elem.m_kind = element_kind::T_STRING;
return *this;
}
element& element::add_property(const std::string& name, bool b)
{
auto& elem = add_property_internal(name);
elem.m_value.boolean = b;
elem.m_kind = b ? element_kind::T_TRUE : element_kind::T_FALSE;
return *this;
}
element& element::add_property_null(const std::string& name)
{
auto& elem = add_property_internal(name);
elem.m_kind = element_kind::T_NULL;
return *this;
}
element& element::add_array_item(const std::string& value)
{
auto& elem = add_property_internal("");
elem.m_kind = element_kind::T_STRING;
elem.m_value.str = strdup(value.c_str());
return *this;
}
element& element::add_array_item(const char* value)
{
auto& elem = add_property_internal("");
elem.m_kind = element_kind::T_STRING;
elem.m_value.str = strdup(value);
return *this;
}
element& element::add_array_item(double value)
{
auto& elem = add_property_internal("");
elem.m_kind = element_kind::T_NUMBER;
elem.m_value.number = value;
return *this;
}
element& element::add_array_item(bool value)
{
auto& elem = add_property_internal("");
elem.m_kind = value ? element_kind::T_TRUE : element_kind::T_FALSE;
elem.m_value.boolean = value;
return *this;
}
element& element::add_array_item(element elem) { return add_element(std::move(elem)); }
element& element::add_array_object()
{
auto& elem = append_new();
elem.m_kind = element_kind::T_OBJECT;
return elem;
}
bool element::contains(const char* name) const
{
if (m_children.empty()) {
return false;
}
if (m_elements_map.empty()) {
// need to index it first
const_cast<element&>(*this).index_elements();
}
return m_elements_map.count(std::string(name)) > 0;
}
bool element::contains(const std::string& name) const { return contains(name.c_str()); }
} // namespace tinyjson