forked from squix78/json-streaming-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonStreamingParser.cpp
615 lines (570 loc) · 16.3 KB
/
JsonStreamingParser.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
/**The MIT License (MIT)
Copyright (c) 2015 by Daniel Eichhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See more at http://blog.squix.ch and https://github.com/squix78/json-streaming-parser
*/
#include "JsonStreamingParser.h"
#ifdef USE_LONG_ERRORS
const char PROGMEM_ERR0[] PROGMEM = "Unescaped control character encountered: %c at position: %d";
const char PROGMEM_ERR1[] PROGMEM = "Start of string expected for object key. Instead got: %c at position: %d";
const char PROGMEM_ERR2[] PROGMEM = "Expected ':' after key. Instead got %c at position %d";
const char PROGMEM_ERR3[] PROGMEM = "Expected ',' or '}' while parsing object. Got: %c at position %d";
const char PROGMEM_ERR4[] PROGMEM = "Expected ',' or ']' while parsing array. Got: %c at position: %d";
const char PROGMEM_ERR5[] PROGMEM = "Finished a literal, but unclear what state to move to. Last state: %d";
const char PROGMEM_ERR6[] PROGMEM = "Cannot have multiple decimal points in a number at: %d";
const char PROGMEM_ERR7[] PROGMEM = "Cannot have a decimal point in an exponent at: %d";
const char PROGMEM_ERR8[] PROGMEM = "Cannot have multiple exponents in a number at: %d";
const char PROGMEM_ERR9[] PROGMEM = "Can only have '+' or '-' after the 'e' or 'E' in a number at: %d";
const char PROGMEM_ERR10[] PROGMEM = "Document must start with object or array";
const char PROGMEM_ERR11[] PROGMEM = "Expected end of document";
const char PROGMEM_ERR12[] PROGMEM = "Internal error. Reached an unknown state at: %d";
const char PROGMEM_ERR13[] PROGMEM = "Unexpected end of string";
const char PROGMEM_ERR14[] PROGMEM = "Unexpected character for value";
const char PROGMEM_ERR15[] PROGMEM = "Unexpected end of array encountered";
const char PROGMEM_ERR16[] PROGMEM = "Unexpected end of object encountered";
const char PROGMEM_ERR17[] PROGMEM = "Expected escaped character after backslash";
const char PROGMEM_ERR18[] PROGMEM = "Expected hex character for escaped Unicode character";
const char PROGMEM_ERR19[] PROGMEM = "Expected '\\u' following a Unicode high surrogate";
const char PROGMEM_ERR20[] PROGMEM = "Expected 'true'";
const char PROGMEM_ERR21[] PROGMEM = "Expected 'false'";
const char PROGMEM_ERR22[] PROGMEM = "Expected 'null'";
#else
const char PROGMEM_ERR0[] PROGMEM = "err0: %c at: %d";
const char PROGMEM_ERR1[] PROGMEM = "err1: %c at: %d";
const char PROGMEM_ERR2[] PROGMEM = "err2: %c at: %d";
const char PROGMEM_ERR3[] PROGMEM = "err3: %c at: %d";
const char PROGMEM_ERR4[] PROGMEM = "err4: %c at: %d";
const char PROGMEM_ERR5[] PROGMEM = "err5: %d";
const char PROGMEM_ERR6[] PROGMEM = "err6: at: %d";
const char PROGMEM_ERR7[] PROGMEM = "err7: at: %d";
const char PROGMEM_ERR8[] PROGMEM = "err8: at: %d";
const char PROGMEM_ERR9[] PROGMEM = "err9: at: %d";
const char PROGMEM_ERR10[] PROGMEM = "err10";
const char PROGMEM_ERR11[] PROGMEM = "err11";
const char PROGMEM_ERR12[] PROGMEM = "err12: %d";
const char PROGMEM_ERR13[] PROGMEM = "err13";
const char PROGMEM_ERR14[] PROGMEM = "err14";
const char PROGMEM_ERR15[] PROGMEM = "err15";
const char PROGMEM_ERR16[] PROGMEM = "err16";
const char PROGMEM_ERR17[] PROGMEM = "err17";
const char PROGMEM_ERR18[] PROGMEM = "err18";
const char PROGMEM_ERR19[] PROGMEM = "err19";
const char PROGMEM_ERR20[] PROGMEM = "err20";
const char PROGMEM_ERR21[] PROGMEM = "err21";
const char PROGMEM_ERR22[] PROGMEM = "err22";
#endif
JsonStreamingParser::JsonStreamingParser() {
reset();
}
void JsonStreamingParser::reset() {
state = STATE_START_DOCUMENT;
stackPos = 0;
bufferPos = 0;
unicodeEscapeBufferPos = 0;
unicodeBufferPos = 0;
characterCounter = 0;
}
void JsonStreamingParser::setListener(JsonListener* listener) {
myListener = listener;
}
bool JsonStreamingParser::parse(char c) {
// Serial.println(c);
// valid whitespace characters in JSON (from RFC4627 for JSON) include:
// space, horizontal tab, line feed or new line, and carriage return.
// thanks:
// http://stackoverflow.com/questions/16042274/definition-of-whitespace-in-json
if ((c == ' ' || c == '\t' || c == '\n' || c == '\r')
&& !(state == STATE_IN_STRING || state == STATE_UNICODE || state == STATE_START_ESCAPE || state == STATE_IN_NUMBER
|| state == STATE_START_DOCUMENT)) {
return true;
}
switch (state) {
case STATE_IN_STRING:
if (c == '"') {
if (!endString()) {
return false;
}
} else if (c == '\\') {
state = STATE_START_ESCAPE;
} else if ((c < 0x1f) || (c == 0x7f)) {
sprintf_P(errorMessage, PROGMEM_ERR0, c, characterCounter);
myListener->error(errorMessage);
return false;
} else {
buffer[bufferPos] = c;
increaseBufferPointer();
}
break;
case STATE_IN_ARRAY:
if (c == ']') {
if (!endArray()) {
return false;
}
} else {
if (!startValue(c)) {
return false;
}
}
break;
case STATE_IN_OBJECT:
if (c == '}') {
if (!endObject()) {
return false;
}
} else if (c == '"') {
startKey();
} else {
sprintf_P(errorMessage, PROGMEM_ERR1, c, characterCounter);
myListener->error(errorMessage);
return false;
}
break;
case STATE_END_KEY:
if (c != ':') {
sprintf_P(errorMessage, PROGMEM_ERR2, c, characterCounter);
myListener->error(errorMessage);
return false;
}
state = STATE_AFTER_KEY;
break;
case STATE_AFTER_KEY:
if (!startValue(c)) {
return false;
}
break;
case STATE_START_ESCAPE:
if (!processEscapeCharacters(c)) {
return false;
}
break;
case STATE_UNICODE:
if (!processUnicodeCharacter(c)) {
return false;
}
break;
case STATE_UNICODE_SURROGATE:
unicodeEscapeBuffer[unicodeEscapeBufferPos] = c;
unicodeEscapeBufferPos++;
if (unicodeEscapeBufferPos == 2) {
if (!endUnicodeSurrogateInterstitial()) {
return false;
}
}
break;
case STATE_AFTER_VALUE: {
// not safe for size == 0!!!
int within = peek();
if (within == STACK_OBJECT) {
if (c == '}') {
if (!endObject()) {
return false;
}
} else if (c == ',') {
state = STATE_IN_OBJECT;
} else {
sprintf_P(errorMessage, PROGMEM_ERR3, c, characterCounter);
myListener->error(errorMessage);
return false;
}
} else if (within == STACK_ARRAY) {
if (c == ']') {
if (!endArray()) {
return false;
}
} else if (c == ',') {
state = STATE_IN_ARRAY;
} else {
sprintf_P(errorMessage, PROGMEM_ERR4, c, characterCounter);
myListener->error(errorMessage);
return false;
}
} else {
sprintf_P(errorMessage, PROGMEM_ERR5, characterCounter);
myListener->error(errorMessage);
return false;
}
}
break;
case STATE_IN_NUMBER:
if (c >= '0' && c <= '9') {
buffer[bufferPos] = c;
increaseBufferPointer();
} else if (c == '.') {
if (doesCharArrayContain(buffer, bufferPos, '.')) {
sprintf_P(errorMessage, PROGMEM_ERR6, characterCounter);
myListener->error(errorMessage);
return false;
} else if (doesCharArrayContain(buffer, bufferPos, 'e')) {
sprintf_P(errorMessage, PROGMEM_ERR7, characterCounter);
myListener->error(errorMessage);
return false;
}
buffer[bufferPos] = c;
increaseBufferPointer();
} else if (c == 'e' || c == 'E') {
if (doesCharArrayContain(buffer, bufferPos, 'e')) {
sprintf_P(errorMessage, PROGMEM_ERR8, characterCounter);
myListener->error(errorMessage);
return false;
}
buffer[bufferPos] = c;
increaseBufferPointer();
} else if (c == '+' || c == '-') {
char last = buffer[bufferPos - 1];
if (!(last == 'e' || last == 'E')) {
sprintf_P(errorMessage, PROGMEM_ERR9, characterCounter);
myListener->error(errorMessage);
return false;
}
buffer[bufferPos] = c;
increaseBufferPointer();
} else {
endNumber();
// we have consumed one beyond the end of the number
parse(c);
}
break;
case STATE_IN_TRUE:
buffer[bufferPos] = c;
increaseBufferPointer();
if (bufferPos == 4) {
if (!endTrue()) {
return false;
}
}
break;
case STATE_IN_FALSE:
buffer[bufferPos] = c;
increaseBufferPointer();
if (bufferPos == 5) {
if (!endFalse()) {
return false;
}
}
break;
case STATE_IN_NULL:
buffer[bufferPos] = c;
increaseBufferPointer();
if (bufferPos == 4) {
if (!endNull()) {
return false;
}
}
break;
case STATE_START_DOCUMENT: {
myListener->startDocument();
if (c == '[') {
startArray();
} else if (c == '{') {
startObject();
} else {
sprintf_P(errorMessage, PROGMEM_ERR10);
myListener->error(errorMessage);
return false;
}
break;
}
case STATE_DONE: {
sprintf_P(errorMessage, PROGMEM_ERR11);
myListener->error(errorMessage);
return false;
}
default: {
sprintf_P(errorMessage, PROGMEM_ERR12, characterCounter);
myListener->error(errorMessage);
return false;
}
}
characterCounter++;
return true;
}
void JsonStreamingParser::increaseBufferPointer() {
bufferPos = min(bufferPos + 1, BUFFER_MAX_LENGTH - 1);
}
void JsonStreamingParser::push(int value) {
stack[stackPos] = value;
stackPos++;
}
int JsonStreamingParser::pop() {
stackPos--;
return stack[stackPos];
}
int JsonStreamingParser::peek() {
return stack[stackPos - 1];
}
void JsonStreamingParser::startKey() {
push(STACK_KEY);
state = STATE_IN_STRING;
}
boolean JsonStreamingParser::startValue(char c) {
if (c == '[') {
startArray();
} else if (c == '{') {
startObject();
} else if (c == '"') {
startString();
} else if (isDigit(c)) {
startNumber(c);
} else if (c == 't') {
state = STATE_IN_TRUE;
buffer[bufferPos] = c;
increaseBufferPointer();
} else if (c == 'f') {
state = STATE_IN_FALSE;
buffer[bufferPos] = c;
increaseBufferPointer();
} else if (c == 'n') {
state = STATE_IN_NULL;
buffer[bufferPos] = c;
increaseBufferPointer();
} else {
sprintf_P(errorMessage, PROGMEM_ERR14);
myListener->error(errorMessage);
return false;
}
return true;
}
void JsonStreamingParser::startObject() {
myListener->startObject();
state = STATE_IN_OBJECT;
push(STACK_OBJECT);
}
boolean JsonStreamingParser::endObject() {
if (pop() != STACK_OBJECT) {
sprintf_P(errorMessage, PROGMEM_ERR16);
myListener->error(errorMessage);
return false;
}
myListener->endObject();
state = STATE_AFTER_VALUE;
if (stackPos == 0) {
endDocument();
}
return true;
}
void JsonStreamingParser::startArray() {
myListener->startArray();
state = STATE_IN_ARRAY;
push(STACK_ARRAY);
}
boolean JsonStreamingParser::endArray() {
if (pop() != STACK_ARRAY) {
sprintf_P(errorMessage, PROGMEM_ERR15);
myListener->error(errorMessage);
return false;
}
myListener->endArray();
state = STATE_AFTER_VALUE;
if (stackPos == 0) {
endDocument();
}
return true;
}
void JsonStreamingParser::startString() {
push(STACK_STRING);
state = STATE_IN_STRING;
}
boolean JsonStreamingParser::endString() {
int popped = pop();
if (popped == STACK_KEY) {
buffer[bufferPos] = '\0';
myListener->key(buffer);
state = STATE_END_KEY;
} else if (popped == STACK_STRING) {
buffer[bufferPos] = '\0';
myListener->value(buffer);
state = STATE_AFTER_VALUE;
} else {
sprintf_P(errorMessage, PROGMEM_ERR13);
myListener->error(errorMessage);
return false;
}
bufferPos = 0;
return true;
}
void JsonStreamingParser::startNumber(char c) {
state = STATE_IN_NUMBER;
buffer[bufferPos] = c;
increaseBufferPointer();
}
void JsonStreamingParser::endNumber() {
buffer[bufferPos] = '\0';
myListener->value(buffer);
bufferPos = 0;
state = STATE_AFTER_VALUE;
}
boolean JsonStreamingParser::endTrue() {
buffer[bufferPos] = '\0';
// String value = String(buffer);
if (strncmp(buffer, "true", 4) == 0) {
myListener->value("true");
} else {
sprintf_P(errorMessage, PROGMEM_ERR20);
myListener->error(errorMessage);
return false;
}
bufferPos = 0;
state = STATE_AFTER_VALUE;
return true;
}
boolean JsonStreamingParser::endFalse() {
buffer[bufferPos] = '\0';
// String value = String(buffer);
if (strncmp(buffer, "false", 5) == 0) {
myListener->value("false");
} else {
sprintf_P(errorMessage, PROGMEM_ERR21);
myListener->error(errorMessage);
return false;
}
bufferPos = 0;
state = STATE_AFTER_VALUE;
return true;
}
boolean JsonStreamingParser::endNull() {
buffer[bufferPos] = '\0';
// String value = String(buffer);
if (strncmp(buffer, "null", 4) == 0) {
myListener->value("null");
} else {
sprintf_P(errorMessage, PROGMEM_ERR22);
myListener->error(errorMessage);
return false;
}
bufferPos = 0;
state = STATE_AFTER_VALUE;
return true;
}
void JsonStreamingParser::endDocument() {
myListener->endDocument();
reset();
}
boolean JsonStreamingParser::isDigit(char c) {
// Only concerned with the first character in a number.
return (c >= '0' && c <= '9') || c == '-';
}
boolean JsonStreamingParser::isHexCharacter(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
boolean JsonStreamingParser::doesCharArrayContain(char myArray[], int length, char c) {
for (int i = 0; i < length; i++) {
if (myArray[i] == c) {
return true;
}
}
return false;
}
boolean JsonStreamingParser::processEscapeCharacters(char c) {
if (c == '"') {
buffer[bufferPos] = '"';
increaseBufferPointer();
} else if (c == '\\') {
buffer[bufferPos] = '\\';
increaseBufferPointer();
} else if (c == '/') {
buffer[bufferPos] = '/';
increaseBufferPointer();
} else if (c == 'b') {
buffer[bufferPos] = 0x08;
increaseBufferPointer();
} else if (c == 'f') {
buffer[bufferPos] = '\f';
increaseBufferPointer();
} else if (c == 'n') {
buffer[bufferPos] = '\n';
increaseBufferPointer();
} else if (c == 'r') {
buffer[bufferPos] = '\r';
increaseBufferPointer();
} else if (c == 't') {
buffer[bufferPos] = '\t';
increaseBufferPointer();
} else if (c == 'u') {
state = STATE_UNICODE;
} else {
sprintf_P(errorMessage, PROGMEM_ERR17);
myListener->error(errorMessage);
return false;
}
if (state != STATE_UNICODE) {
state = STATE_IN_STRING;
}
return true;
}
boolean JsonStreamingParser::processUnicodeCharacter(char c) {
if (!isHexCharacter(c)) {
sprintf_P(errorMessage, PROGMEM_ERR18);
myListener->error(errorMessage);
return false;
}
unicodeBuffer[unicodeBufferPos] = c;
unicodeBufferPos++;
if (unicodeBufferPos == 4) {
int codepoint = getHexArrayAsDecimal(unicodeBuffer, unicodeBufferPos);
endUnicodeCharacter(codepoint);
}
return true;
}
int JsonStreamingParser::getHexArrayAsDecimal(char hexArray[], int length) {
int result = 0;
for (int i = 0; i < length; i++) {
char current = hexArray[length - i - 1];
int value = 0;
if (current >= 'a' && current <= 'f') {
value = current - 'a' + 10;
} else if (current >= 'A' && current <= 'F') {
value = current - 'A' + 10;
} else if (current >= '0' && current <= '9') {
value = current - '0';
}
result += value * 16 ^ i;
}
return result;
}
boolean JsonStreamingParser::endUnicodeSurrogateInterstitial() {
char unicodeEscape = unicodeEscapeBuffer[unicodeEscapeBufferPos - 1];
if (unicodeEscape != 'u') {
sprintf_P(errorMessage, PROGMEM_ERR19);
myListener->error(errorMessage);
return false;
}
unicodeBufferPos = 0;
unicodeEscapeBufferPos = 0;
state = STATE_UNICODE;
return true;
}
int JsonStreamingParser::convertDecimalBufferToInt(char myArray[], int length) {
int result = 0;
for (int i = 0; i < length; i++) {
char current = myArray[length - i - 1];
result += (current - '0') * 10;
}
return result;
}
void JsonStreamingParser::endUnicodeCharacter(int codepoint) {
buffer[bufferPos] = convertCodepointToCharacter(codepoint);
increaseBufferPointer();
unicodeBufferPos = 0;
unicodeHighSurrogate = -1;
state = STATE_IN_STRING;
}
char JsonStreamingParser::convertCodepointToCharacter(int num) {
if (num <= 0x7F) {
return (char) (num);
}
return ' ';
}