Coverage Report

Created: 2024-02-16 06:12

/src/open62541/deps/cj5.c
Line
Count
Source (jump to first uncovered line)
1
// MIT License
2
//
3
// Copyright (c) 2020 Sepehr Taghdisian
4
// Copyright (c) 2022 Julius Pfrommer
5
//
6
// Permission is hereby granted, free of charge, to any person obtaining a copy
7
// of this software and associated documentation files (the "Software"), to deal
8
// in the Software without restriction, including without limitation the rights
9
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
// copies of the Software, and to permit persons to whom the Software is
11
// furnished to do so, subject to the following conditions:
12
//
13
// The above copyright notice and this permission notice shall be included in all
14
// copies or substantial portions of the Software.
15
//
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
// SOFTWARE.
23
24
#include "cj5.h"
25
#include "parse_num.h"
26
27
#include <math.h>
28
#include <float.h>
29
#include <string.h>
30
31
#if defined(_MSC_VER)
32
# define CJ5_INLINE __inline
33
#else
34
# define CJ5_INLINE inline
35
#endif
36
37
/* vs2008 does not have INFINITY and NAN defined */
38
#ifndef INFINITY
39
# define INFINITY ((double)(DBL_MAX+DBL_MAX))
40
#endif
41
#ifndef NAN
42
# define NAN ((double)(INFINITY-INFINITY))
43
#endif
44
45
#if defined(_MSC_VER)
46
# pragma warning(disable: 4056)
47
# pragma warning(disable: 4756)
48
#endif
49
50
/* Max nesting depth of objects and arrays */
51
276k
#define CJ5_MAX_NESTING 32
52
53
#define CJ5__FOURCC(_a, _b, _c, _d)                         \
54
    (((uint32_t)(_a) | ((uint32_t)(_b) << 8) |              \
55
      ((uint32_t)(_c) << 16) | ((uint32_t)(_d) << 24)))
56
57
static const uint32_t CJ5__NULL_FOURCC  = CJ5__FOURCC('n', 'u', 'l', 'l');
58
static const uint32_t CJ5__TRUE_FOURCC  = CJ5__FOURCC('t', 'r', 'u', 'e');
59
static const uint32_t CJ5__FALSE_FOURCC = CJ5__FOURCC('f', 'a', 'l', 's');
60
61
typedef struct {
62
    unsigned int pos;
63
    unsigned int line_start;
64
    unsigned int line;
65
    cj5_error_code error;
66
67
    const char *json5;
68
    unsigned int len;
69
70
    unsigned int curr_tok_idx;
71
72
    cj5_token *tokens;
73
    unsigned int token_count;
74
    unsigned int max_tokens;
75
76
    bool stop_early;
77
} cj5__parser;
78
79
static CJ5_INLINE bool
80
181M
cj5__isrange(char ch, char from, char to) {
81
181M
    return (uint8_t)(ch - from) <= (uint8_t)(to - from);
82
181M
}
83
84
138M
#define cj5__isupperchar(ch) cj5__isrange(ch, 'A', 'Z')
85
142M
#define cj5__islowerchar(ch) cj5__isrange(ch, 'a', 'z')
86
183M
#define cj5__isnum(ch)       cj5__isrange(ch, '0', '9')
87
88
static cj5_token *
89
42.2M
cj5__alloc_token(cj5__parser *parser) {
90
42.2M
    cj5_token* token = NULL;
91
42.2M
    if(parser->token_count < parser->max_tokens) {
92
21.0M
        token = &parser->tokens[parser->token_count];
93
21.0M
        memset(token, 0x0, sizeof(cj5_token));
94
21.2M
    } else {
95
21.2M
        parser->error = CJ5_ERROR_OVERFLOW;
96
21.2M
    }
97
98
    // Always increase the index. So we know eventually how many token would be
99
    // required (if there are not enough).
100
42.2M
    parser->token_count++;
101
42.2M
    return token;
102
42.2M
}
103
104
static void
105
1.16M
cj5__parse_string(cj5__parser *parser) {
106
1.16M
    const char *json5 = parser->json5;
107
1.16M
    unsigned int len = parser->len;
108
1.16M
    unsigned int start = parser->pos;
109
1.16M
    char str_open = json5[start];
110
111
1.16M
    parser->pos++;
112
53.7M
    for(; parser->pos < len; parser->pos++) {
113
53.7M
        char c = json5[parser->pos];
114
115
        // End of string
116
53.7M
        if(str_open == c) {
117
1.16M
            cj5_token *token = cj5__alloc_token(parser);
118
1.16M
            if(token) {
119
604k
                token->type = CJ5_TOKEN_STRING;
120
604k
                token->start = start + 1;
121
604k
                token->end = parser->pos - 1;
122
604k
                token->size = token->end - token->start + 1;
123
604k
                token->parent_id = parser->curr_tok_idx;
124
604k
            } 
125
1.16M
            return;
126
1.16M
        }
127
128
        // Unescaped newlines are forbidden
129
52.5M
        if(c == '\n') {
130
3
            parser->error = CJ5_ERROR_INVALID;
131
3
            return;
132
3
        }
133
134
        // Escape char
135
52.5M
        if(c == '\\') {
136
60.3k
            if(parser->pos + 1 >= len) {
137
7
                parser->error = CJ5_ERROR_INCOMPLETE;
138
7
                return;
139
7
            }
140
60.3k
            parser->pos++;
141
60.3k
            switch(json5[parser->pos]) {
142
319
            case '\"':
143
12.3k
            case '/':
144
26.4k
            case '\\':
145
29.5k
            case 'b':
146
34.0k
            case 'f':
147
40.8k
            case 'r':
148
41.3k
            case 'n':
149
42.6k
            case 't':
150
42.6k
                break;
151
17.3k
            case 'u': // The next four characters are an utf8 code
152
17.3k
                parser->pos++;
153
17.3k
                if(parser->pos + 4 >= len) {
154
19
                    parser->error = CJ5_ERROR_INVALID;
155
19
                    return;
156
19
                }
157
86.4k
                for(unsigned int i = 0; i < 4; i++) {
158
                    // If it isn't a hex character we have an error
159
69.2k
                    if(!(json5[parser->pos] >= 48 && json5[parser->pos] <= 57) && /* 0-9 */
160
69.2k
                       !(json5[parser->pos] >= 65 && json5[parser->pos] <= 70) && /* A-F */
161
69.2k
                       !(json5[parser->pos] >= 97 && json5[parser->pos] <= 102))  /* a-f */
162
64
                        {
163
64
                            parser->error = CJ5_ERROR_INVALID;
164
64
                            return;
165
64
                        }
166
69.1k
                    parser->pos++;
167
69.1k
                }
168
17.2k
                parser->pos--;
169
17.2k
                break;
170
288
            case '\n': // Escape break line
171
288
                parser->line++;
172
288
                parser->line_start = parser->pos;
173
288
                break;
174
3
            default:
175
3
                parser->error = CJ5_ERROR_INVALID;
176
3
                return;
177
60.3k
            }
178
60.3k
        }
179
52.5M
    }
180
181
    // The file has ended before the string terminates
182
262
    parser->error = CJ5_ERROR_INCOMPLETE;
183
262
}
184
185
// parser->pos is advanced a last time in the next iteration of the main
186
// parse-loop. So we leave parse-primitive in a state where parse->pos points to
187
// the last character of the primitive value (or the quote-character of the
188
// string).
189
static void
190
39.3M
cj5__parse_primitive(cj5__parser* parser) {
191
39.3M
    const char* json5 = parser->json5;
192
39.3M
    unsigned int len = parser->len;
193
39.3M
    unsigned int start = parser->pos;
194
195
    // String value
196
39.3M
    if(json5[start] == '\"' ||
197
39.3M
       json5[start] == '\'') {
198
939k
        cj5__parse_string(parser);
199
939k
        return;
200
939k
    }
201
202
    // Fast comparison of bool, and null.
203
    // We have to use memcpy here or we can get unaligned accesses
204
38.3M
    uint32_t fourcc = 0;
205
38.3M
    if(start + 4 < len)
206
38.3M
        memcpy(&fourcc, &json5[start], 4);
207
    
208
38.3M
    cj5_token_type type;
209
38.3M
    if(fourcc == CJ5__NULL_FOURCC) {
210
13.7k
        type = CJ5_TOKEN_NULL;
211
13.7k
        parser->pos += 3;
212
38.3M
    } else if(fourcc == CJ5__TRUE_FOURCC) {
213
431
        type = CJ5_TOKEN_BOOL;
214
431
        parser->pos += 3;
215
38.3M
    } else if(fourcc == CJ5__FALSE_FOURCC) {
216
        // "false" has five characters
217
561
        type = CJ5_TOKEN_BOOL;
218
561
        if(start + 4 >= len || json5[start+4] != 'e') {
219
19
            parser->error = CJ5_ERROR_INVALID;
220
19
            return;
221
19
        }
222
542
        parser->pos += 4;
223
38.3M
    } else {
224
        // Numbers are checked for basic compatibility.
225
        // But they are fully parsed only in the cj5_get_XXX functions.
226
38.3M
        type = CJ5_TOKEN_NUMBER;
227
88.1M
        for(; parser->pos < len; parser->pos++) {
228
88.1M
            if(!cj5__isnum(json5[parser->pos]) &&
229
88.1M
               !(json5[parser->pos] == '.') &&
230
88.1M
               !cj5__islowerchar(json5[parser->pos]) && 
231
88.1M
               !cj5__isupperchar(json5[parser->pos]) &&
232
88.1M
               !(json5[parser->pos] == '+') && !(json5[parser->pos] == '-')) {
233
38.3M
                break;
234
38.3M
            }
235
88.1M
        }
236
38.3M
        parser->pos--; // Point to the last character that is still inside the
237
                       // primitive value
238
38.3M
    }
239
240
38.3M
    cj5_token *token = cj5__alloc_token(parser);
241
38.3M
    if(token) {
242
19.0M
        token->type = type;
243
19.0M
        token->start = start;
244
19.0M
        token->end = parser->pos;
245
19.0M
        token->size = parser->pos - start + 1;
246
19.0M
        token->parent_id = parser->curr_tok_idx;
247
19.0M
    }
248
38.3M
}
249
250
static void
251
2.67M
cj5__parse_key(cj5__parser* parser) {
252
2.67M
    const char* json5 = parser->json5;
253
2.67M
    unsigned int start = parser->pos;
254
2.67M
    cj5_token* token;
255
256
    // Key is a a normal string
257
2.67M
    if(json5[start] == '\"' || json5[start] == '\'') {
258
228k
        cj5__parse_string(parser);
259
228k
        return;
260
228k
    }
261
262
    // An unquoted key. Must start with a-ZA-Z_$. Can contain numbers later on.
263
2.44M
    unsigned int len = parser->len;
264
7.30M
    for(; parser->pos < len; parser->pos++) {
265
7.30M
        if(cj5__islowerchar(json5[parser->pos]) ||
266
7.30M
           cj5__isupperchar(json5[parser->pos]) ||
267
7.30M
           json5[parser->pos] == '_' || json5[parser->pos] == '$')
268
3.92M
            continue;
269
3.38M
        if(cj5__isnum(json5[parser->pos]) && parser->pos != start)
270
939k
            continue;
271
2.44M
        break;
272
3.38M
    }
273
274
    // An empty key is not allowed
275
2.44M
    if(parser->pos <= start) {
276
127
        parser->error = CJ5_ERROR_INVALID;
277
127
        return;
278
127
    }
279
280
    // Move pos to the last character within the unquoted key
281
2.44M
    parser->pos--;
282
283
2.44M
    token = cj5__alloc_token(parser);
284
2.44M
    if(token) {
285
1.23M
        token->type = CJ5_TOKEN_STRING;
286
1.23M
        token->start = start;
287
1.23M
        token->end = parser->pos;
288
1.23M
        token->size = parser->pos - start + 1;
289
1.23M
        token->parent_id = parser->curr_tok_idx;
290
1.23M
    }
291
2.44M
}
292
293
static void
294
222k
cj5__skip_comment(cj5__parser* parser) {
295
222k
    const char* json5 = parser->json5;
296
297
    // Single-line comment
298
222k
    if(json5[parser->pos] == '#') {
299
24.0k
    skip_line:
300
13.3M
        while(parser->pos < parser->len) {
301
13.3M
            if(json5[parser->pos] == '\n') {
302
24.0k
                parser->pos--; // Reparse the newline in the main parse loop
303
24.0k
                return;
304
24.0k
            }
305
13.2M
            parser->pos++;
306
13.2M
        }
307
54
        return;
308
24.0k
    }
309
310
    // Comment begins with '/' but not enough space for another character
311
208k
    if(parser->pos + 1 >= parser->len) {
312
25
        parser->error = CJ5_ERROR_INVALID;
313
25
        return;
314
25
    }
315
208k
    parser->pos++;
316
317
    // Comment begins with '//' -> single-line comment
318
208k
    if(json5[parser->pos] == '/')
319
9.78k
        goto skip_line;
320
321
    // Multi-line comments begin with '/*' and end with '*/'
322
198k
    if(json5[parser->pos] == '*') {
323
198k
        parser->pos++;
324
2.50M
        for(; parser->pos + 1 < parser->len; parser->pos++) {
325
2.50M
            if(json5[parser->pos] == '*' && json5[parser->pos + 1] == '/') {
326
198k
                parser->pos++;
327
198k
                return;
328
198k
            }
329
            // Remember we passed a newline
330
2.30M
            if(json5[parser->pos] == '\n') {
331
4.67k
                parser->line++;
332
4.67k
                parser->line_start = parser->pos;
333
4.67k
            }
334
2.30M
        }
335
198k
    }
336
337
    // Unknown comment type or the multi-line comment is not terminated
338
171
    parser->error = CJ5_ERROR_INCOMPLETE;
339
171
}
340
341
cj5_result
342
cj5_parse(const char *json5, unsigned int len,
343
          cj5_token *tokens, unsigned int max_tokens,
344
7.78k
          cj5_options *options) {
345
7.78k
    cj5_result r;
346
7.78k
    cj5__parser parser;
347
7.78k
    memset(&parser, 0x0, sizeof(parser));
348
7.78k
    parser.curr_tok_idx = 0;
349
7.78k
    parser.json5 = json5;
350
7.78k
    parser.len = len;
351
7.78k
    parser.tokens = tokens;
352
7.78k
    parser.max_tokens = max_tokens;
353
354
7.78k
    if(options)
355
0
        parser.stop_early = options->stop_early;
356
357
7.78k
    unsigned short depth = 0; // Nesting depth zero means "outside the root object"
358
7.78k
    char nesting[CJ5_MAX_NESTING]; // Contains either '\0', '{' or '[' for the
359
                                   // type of nesting at each depth. '\0'
360
                                   // indicates we are out of the root object.
361
7.78k
    char next[CJ5_MAX_NESTING];    // Next content to parse: 'k' (key), ':', 'v'
362
                                   // (value) or ',' (comma).
363
7.78k
    next[0] = 'v';  // The root is a "value" (object, array or primitive). If we
364
                    // detect a colon after the first value then everything is
365
                    // wrapped into a "virtual root object" and the parsing is
366
                    // restarted.
367
7.78k
    nesting[0] = 0; // Becomes '{' if there is a virtual root object
368
369
7.78k
    cj5_token *token = NULL; // The current token
370
371
12.0k
 start_parsing:
372
85.4M
    for(; parser.pos < len; parser.pos++) {
373
85.4M
        char c = json5[parser.pos];
374
85.4M
        switch(c) {
375
651k
        case '\n': // Skip newline
376
651k
            parser.line++;
377
651k
            parser.line_start = parser.pos;
378
651k
            break;
379
380
5.92k
        case '\r': // Skip whitespace
381
26.8k
        case '\t':
382
46.1k
        case ' ':
383
46.1k
            break;
384
385
14.2k
        case '#': // Skip comment
386
222k
        case '/':
387
222k
            cj5__skip_comment(&parser);
388
222k
            if(parser.error != CJ5_ERROR_NONE &&
389
222k
               parser.error != CJ5_ERROR_OVERFLOW)
390
196
                goto finish;
391
222k
            break;
392
393
222k
        case '{': // Open an object or array
394
276k
        case '[':
395
            // Check the nesting depth
396
276k
            if(depth + 1 >= CJ5_MAX_NESTING) {
397
3
                parser.error = CJ5_ERROR_INVALID;
398
3
                goto finish;
399
3
            }
400
401
            // Correct next?
402
276k
            if(next[depth] != 'v') {
403
38
                parser.error = CJ5_ERROR_INVALID;
404
38
                goto finish;
405
38
            }
406
407
276k
            depth++; // Increase the nesting depth
408
276k
            nesting[depth] = c; // Set the nesting type
409
276k
            next[depth] = (c == '{') ? 'k' : 'v'; // next is either a key or a value
410
411
            // Create a token for the object or array
412
276k
            token = cj5__alloc_token(&parser);
413
276k
            if(token) {
414
149k
                token->parent_id = parser.curr_tok_idx;
415
149k
                token->type = (c == '{') ? CJ5_TOKEN_OBJECT : CJ5_TOKEN_ARRAY;
416
149k
                token->start = parser.pos;
417
149k
                token->size = 0;
418
149k
                parser.curr_tok_idx = parser.token_count - 1; // The new curr_tok_idx
419
                                                              // is for this token
420
149k
            }
421
276k
            break;
422
423
208k
        case '}': // Close an object or array
424
273k
        case ']':
425
            // Check the nesting depth. Note that a "virtual root object" at
426
            // depth zero must not be closed.
427
273k
            if(depth == 0) {
428
28
                parser.error = CJ5_ERROR_INVALID;
429
28
                goto finish;
430
28
            }
431
432
            // Check and adjust the nesting. Note that ']' - '[' == 2 and '}' -
433
            // '{' == 2. Arrays can always be closed. Objects can only close
434
            // when a key or a comma is expected.
435
273k
            if(c - nesting[depth] != 2 ||
436
273k
               (c == '}' && next[depth] != 'k' && next[depth] != ',')) {
437
15
                parser.error = CJ5_ERROR_INVALID;
438
15
                goto finish;
439
15
            }
440
441
273k
            if(token) {
442
                // Finalize the current token
443
146k
                token->end = parser.pos;
444
445
                // Move to the parent and increase the parent size. Omit this
446
                // when we leave the root (parent the same as the current
447
                // token).
448
146k
                if(parser.curr_tok_idx != token->parent_id) {
449
143k
                    parser.curr_tok_idx = token->parent_id;
450
143k
                    token = &tokens[token->parent_id];
451
143k
                    token->size++;
452
143k
                }
453
146k
            }
454
455
            // Step one level up
456
273k
            depth--;
457
273k
            next[depth] = (depth == 0) ? 0 : ','; // zero if we step out the root
458
                                                  // object. then we do not look for
459
                                                  // another element.
460
461
            // The first element was successfully parsed. Stop early or try to
462
            // parse the full input string?
463
273k
            if(depth == 0 && parser.stop_early)
464
0
                goto finish;
465
466
273k
            break;
467
468
2.67M
        case ':': // Colon (between key and value)
469
2.67M
            if(next[depth] != ':') {
470
3.73k
                parser.error = CJ5_ERROR_INVALID;
471
3.73k
                goto finish;
472
3.73k
            }
473
2.67M
            next[depth] = 'v';
474
2.67M
            break;
475
476
39.3M
        case ',': // Comma
477
39.3M
            if(next[depth] != ',') {
478
20
                parser.error = CJ5_ERROR_INVALID;
479
20
                goto finish;
480
20
            }
481
39.3M
            next[depth] = (nesting[depth] == '{') ? 'k' : 'v';
482
39.3M
            break;
483
484
41.9M
        default: // Value or key
485
41.9M
            if(next[depth] == 'v') {
486
39.3M
                cj5__parse_primitive(&parser); // Parse primitive value
487
39.3M
                if(nesting[depth] != 0) {
488
                    // Parent is object or array
489
39.2M
                    if(token)
490
35.6M
                        token->size++;
491
39.2M
                    next[depth] = ',';
492
39.2M
                } else {
493
                    // The current value was the root element. Don't look for
494
                    // any next element.
495
4.21k
                    next[depth] = 0;
496
497
                    // The first element was successfully parsed. Stop early or try to
498
                    // parse the full input string?
499
4.21k
                    if(parser.stop_early)
500
0
                        goto finish;
501
4.21k
                }
502
39.3M
            } else if(next[depth] == 'k') {
503
2.67M
                cj5__parse_key(&parser);
504
2.67M
                if(token)
505
2.55M
                    token->size++; // Keys count towards the length
506
2.67M
                next[depth] = ':';
507
2.67M
            } else {
508
271
                parser.error = CJ5_ERROR_INVALID;
509
271
            }
510
511
41.9M
            if(parser.error && parser.error != CJ5_ERROR_OVERFLOW)
512
775
                goto finish;
513
514
41.9M
            break;
515
85.4M
        }
516
85.4M
    }
517
518
    // Are we back to the initial nesting depth?
519
7.20k
    if(depth != 0) {
520
154
        parser.error = CJ5_ERROR_INCOMPLETE;
521
154
        goto finish;
522
154
    }
523
524
    // Close the virtual root object if there is one
525
7.04k
    if(nesting[0] == '{' && parser.error != CJ5_ERROR_OVERFLOW) {
526
        // Check the we end after a complete key-value pair (or dangling comma)
527
3.66k
        if(next[0] != 'k' && next[0] != ',')
528
98
            parser.error = CJ5_ERROR_INVALID;
529
3.66k
        tokens[0].end = parser.pos - 1;
530
3.66k
    }
531
532
12.0k
 finish:
533
    // If parsing failed at the initial nesting depth, create a virtual root object
534
    // and restart parsing.
535
12.0k
    if(parser.error != CJ5_ERROR_NONE &&
536
12.0k
       parser.error != CJ5_ERROR_OVERFLOW &&
537
12.0k
       depth == 0 && nesting[0] != '{') {
538
4.21k
        parser.token_count = 0;
539
4.21k
        token = cj5__alloc_token(&parser);
540
4.21k
        if(token) {
541
4.21k
            token->parent_id = 0;
542
4.21k
            token->type = CJ5_TOKEN_OBJECT;
543
4.21k
            token->start = 0;
544
4.21k
            token->size = 0;
545
546
4.21k
            nesting[0] = '{';
547
4.21k
            next[0] = 'k';
548
549
4.21k
            parser.curr_tok_idx = 0;
550
4.21k
            parser.pos = 0;
551
4.21k
            parser.error = CJ5_ERROR_NONE;
552
4.21k
            goto start_parsing;
553
4.21k
        }
554
4.21k
    }
555
556
7.78k
    memset(&r, 0x0, sizeof(r));
557
7.78k
    r.error = parser.error;
558
7.78k
    r.error_line = parser.line;
559
7.78k
    r.error_col = parser.pos - parser.line_start;
560
7.78k
    r.num_tokens = parser.token_count; // How many tokens (would) have been
561
                                       // consumed by the parser?
562
563
    // Not a single token was parsed -> return an error
564
7.78k
    if(r.num_tokens == 0)
565
26
        r.error = CJ5_ERROR_INCOMPLETE;
566
567
    // Set the tokens and original string only if successfully parsed
568
7.78k
    if(r.error == CJ5_ERROR_NONE) {
569
6.44k
        r.tokens = tokens;
570
6.44k
        r.json5 = json5;
571
6.44k
    }
572
573
7.78k
    return r;
574
12.0k
}
575
576
cj5_error_code
577
0
cj5_get_bool(const cj5_result *r, unsigned int tok_index, bool *out) {
578
0
    const cj5_token *token = &r->tokens[tok_index];
579
0
    if(token->type != CJ5_TOKEN_BOOL)
580
0
        return CJ5_ERROR_INVALID;
581
0
    *out = (r->json5[token->start] == 't');
582
0
    return CJ5_ERROR_NONE;
583
0
}
584
585
cj5_error_code
586
0
cj5_get_float(const cj5_result *r, unsigned int tok_index, double *out) {
587
0
    const cj5_token *token = &r->tokens[tok_index];
588
0
    if(token->type != CJ5_TOKEN_NUMBER)
589
0
        return CJ5_ERROR_INVALID;
590
591
0
    const char *tokstr = &r->json5[token->start];
592
0
    size_t toksize = token->end - token->start + 1;
593
0
    if(toksize == 0)
594
0
        return CJ5_ERROR_INVALID;
595
596
    // Skip prefixed +/-
597
0
    bool neg = false;
598
0
    if(tokstr[0] == '+' || tokstr[0] == '-') {
599
0
        neg = (tokstr[0] == '-');
600
0
        tokstr++;
601
0
        toksize--;
602
0
    }
603
604
    // Detect prefixed inf/nan
605
0
    if(strncmp(tokstr, "Infinity", toksize) == 0) {
606
0
        *out = neg ? -INFINITY : INFINITY;
607
0
        return CJ5_ERROR_NONE;
608
0
    } else if(strncmp(tokstr, "NaN", toksize) == 0) {
609
0
        *out = NAN;
610
0
        return CJ5_ERROR_NONE;
611
0
    }
612
613
    // reset the +/- detection and parse
614
0
    tokstr = &r->json5[token->start];
615
0
    toksize = token->end - token->start + 1;
616
0
    size_t parsed = parseDouble(tokstr, toksize, out);
617
618
    // There must only be whitespace between the end of the parsed number and
619
    // the end of the token
620
0
    for(size_t i = parsed; i < toksize; i++) {
621
0
        if(tokstr[i] != ' ' && tokstr[i] -'\t' >= 5)
622
0
            return CJ5_ERROR_INVALID;
623
0
    }
624
625
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
626
0
}
627
628
cj5_error_code
629
cj5_get_int(const cj5_result *r, unsigned int tok_index,
630
0
            int64_t *out) {
631
0
    const cj5_token *token = &r->tokens[tok_index];
632
0
    if(token->type != CJ5_TOKEN_NUMBER)
633
0
        return CJ5_ERROR_INVALID;
634
0
    size_t parsed = parseInt64(&r->json5[token->start], token->size, out);
635
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
636
0
}
637
638
cj5_error_code
639
cj5_get_uint(const cj5_result *r, unsigned int tok_index,
640
0
             uint64_t *out) {
641
0
    const cj5_token *token = &r->tokens[tok_index];
642
0
    if(token->type != CJ5_TOKEN_NUMBER)
643
0
        return CJ5_ERROR_INVALID;
644
0
    size_t parsed = parseUInt64(&r->json5[token->start], token->size, out);
645
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
646
0
}
647
648
static const uint32_t SURROGATE_OFFSET = 0x10000u - (0xD800u << 10) - 0xDC00;
649
650
static cj5_error_code
651
1.96k
parse_codepoint(const char *pos, uint32_t *out_utf) {
652
1.96k
    uint32_t utf = 0;
653
9.74k
    for(unsigned int i = 0; i < 4; i++) {
654
7.80k
        char byte = pos[i];
655
7.80k
        if(cj5__isnum(byte)) {
656
3.45k
            byte = (char)(byte - '0');
657
4.35k
        } else if(cj5__isrange(byte, 'a', 'f')) {
658
1.47k
            byte = (char)(byte - ('a' - 10));
659
2.88k
        } else if(cj5__isrange(byte, 'A', 'F')) {
660
2.86k
            byte = (char)(byte - ('A' - 10));
661
2.86k
        } else {
662
20
            return CJ5_ERROR_INVALID;
663
20
        }
664
7.78k
        utf = (utf << 4) | ((uint8_t)byte & 0xF);
665
7.78k
    }
666
1.94k
    *out_utf = utf;
667
1.94k
    return CJ5_ERROR_NONE;
668
1.96k
}
669
670
cj5_error_code
671
cj5_get_str(const cj5_result *r, unsigned int tok_index,
672
153k
            char *buf, unsigned int *buflen) {
673
153k
    const cj5_token *token = &r->tokens[tok_index];
674
153k
    if(token->type != CJ5_TOKEN_STRING)
675
0
        return CJ5_ERROR_INVALID;
676
677
153k
    const char *pos = &r->json5[token->start];
678
153k
    const char *end = &r->json5[token->end + 1];
679
153k
    unsigned int outpos = 0;
680
3.68M
    for(; pos < end; pos++) {
681
3.53M
        uint8_t c = (uint8_t)*pos;
682
683
        // Process an escape character
684
3.53M
        if(c == '\\') {
685
8.69k
            if(pos + 1 >= end)
686
0
                return CJ5_ERROR_INCOMPLETE;
687
8.69k
            pos++;
688
8.69k
            c = (uint8_t)*pos;
689
8.69k
            switch(c) {
690
196
            case '\"': buf[outpos++] = '\"'; break;
691
1.27k
            case '\\': buf[outpos++] = '\\'; break;
692
196
            case '\n': buf[outpos++] = '\n'; break; // escape newline
693
1.24k
            case '/':  buf[outpos++] = '/';  break;
694
1.29k
            case 'b':  buf[outpos++] = '\b'; break;
695
201
            case 'f':  buf[outpos++] = '\f'; break;
696
2.32k
            case 'r':  buf[outpos++] = '\r'; break;
697
208
            case 'n':  buf[outpos++] = '\n'; break;
698
209
            case 't':  buf[outpos++] = '\t'; break;
699
1.54k
            case 'u': {
700
                // Parse the unicode code point
701
1.54k
                if(pos + 4 >= end)
702
0
                    return CJ5_ERROR_INCOMPLETE;
703
1.54k
                pos++;
704
1.54k
                uint32_t utf;
705
1.54k
                cj5_error_code err = parse_codepoint(pos, &utf);
706
1.54k
                if(err != CJ5_ERROR_NONE)
707
0
                    return err;
708
1.54k
                pos += 3;
709
710
1.54k
                if(0xD800 <= utf && utf <= 0xDBFF) {
711
                    // Parse a surrogate pair
712
449
                    if(pos + 6 >= end)
713
16
                        return CJ5_ERROR_INVALID;
714
433
                    if(pos[1] != '\\' && pos[3] != 'u')
715
19
                        return CJ5_ERROR_INVALID;
716
414
                    pos += 3;
717
414
                    uint32_t trail;
718
414
                    err = parse_codepoint(pos, &trail);
719
414
                    if(err != CJ5_ERROR_NONE)
720
20
                        return err;
721
394
                    pos += 3;
722
394
                    utf = (utf << 10) + trail + SURROGATE_OFFSET;
723
1.09k
                } else if(0xDC00 <= utf && utf <= 0xDFFF) {
724
                    // Invalid Unicode '\\u%04X'
725
16
                    return CJ5_ERROR_INVALID;
726
16
                }
727
                
728
                // Write the utf8 bytes of the code point
729
1.47k
                if(utf <= 0x7F) { // Plain ASCII
730
220
                    buf[outpos++] = (char)utf;
731
1.25k
                } else if(utf <= 0x07FF) { // 2-byte unicode
732
243
                    buf[outpos++] = (char)(((utf >> 6) & 0x1F) | 0xC0);
733
243
                    buf[outpos++] = (char)(((utf >> 0) & 0x3F) | 0x80);
734
1.01k
                } else if(utf <= 0xFFFF) { // 3-byte unicode
735
619
                    buf[outpos++] = (char)(((utf >> 12) & 0x0F) | 0xE0);
736
619
                    buf[outpos++] = (char)(((utf >>  6) & 0x3F) | 0x80);
737
619
                    buf[outpos++] = (char)(((utf >>  0) & 0x3F) | 0x80);
738
619
                } else if(utf <= 0x10FFFF) { // 4-byte unicode
739
387
                    buf[outpos++] = (char)(((utf >> 18) & 0x07) | 0xF0);
740
387
                    buf[outpos++] = (char)(((utf >> 12) & 0x3F) | 0x80);
741
387
                    buf[outpos++] = (char)(((utf >>  6) & 0x3F) | 0x80);
742
387
                    buf[outpos++] = (char)(((utf >>  0) & 0x3F) | 0x80);
743
387
                } else {
744
7
                    return CJ5_ERROR_INVALID; // Not a utf8 string
745
7
                }
746
1.46k
                break;
747
1.47k
            }
748
1.46k
            default:
749
0
                return CJ5_ERROR_INVALID;
750
8.69k
            }
751
8.62k
            continue;
752
8.69k
        }
753
754
        // Unprintable ascii characters must be escaped. JSON5 allows nested
755
        // quotes if the quote character is not the same as the surrounding
756
        // quote character, e.g. 'this is my "quote"'. This logic is in the
757
        // token parsing code and not in this "string extraction" method.
758
3.52M
        if(c < ' '   || c == 127)
759
29
            return CJ5_ERROR_INVALID;
760
761
        // Ascii character or utf8 byte
762
3.52M
        buf[outpos++] = (char)c;
763
3.52M
    }
764
765
    // Terminate with \0
766
153k
    buf[outpos] = 0;
767
768
    // Set the output length
769
153k
    if(buflen)
770
153k
        *buflen = outpos;
771
153k
    return CJ5_ERROR_NONE;
772
153k
}
773
774
void
775
0
cj5_skip(const cj5_result *r, unsigned int *tok_index) {
776
0
    unsigned int idx = *tok_index;
777
0
    unsigned int end = r->tokens[idx].end;
778
0
    do { idx++; } while(idx < r->num_tokens &&
779
0
                        r->tokens[idx].start < end);
780
0
    *tok_index = idx;
781
0
}
782
783
cj5_error_code
784
cj5_find(const cj5_result *r, unsigned int *tok_index,
785
0
         const char *key) {
786
    // It has to be an object
787
0
    unsigned int idx = *tok_index;
788
0
    if(r->tokens[idx].type != CJ5_TOKEN_OBJECT)
789
0
        return CJ5_ERROR_INVALID;
790
0
    unsigned int size = r->tokens[idx].size;
791
792
    // Skip to the first key
793
0
    idx++;
794
795
    // Size is number of keys + number of values
796
0
    for(unsigned int i = 0; i < size; i += 2) {
797
        // Key has to be a string
798
0
        if(r->tokens[idx].type != CJ5_TOKEN_STRING)
799
0
            return CJ5_ERROR_INVALID;
800
801
        // Return the index to the value if the key matches
802
0
        const char *keystart = &r->json5[r->tokens[idx].start];
803
0
        size_t keysize = r->tokens[idx].end - r->tokens[idx].start + 1;
804
0
        if(strncmp(key, keystart, keysize) == 0) {
805
0
            *tok_index = idx + 1;
806
0
            return CJ5_ERROR_NONE;
807
0
        }
808
809
        // Skip over the value
810
0
        idx++;
811
0
        cj5_skip(r, &idx);
812
0
    }
813
0
    return CJ5_ERROR_NOTFOUND;
814
0
}