Coverage Report

Created: 2025-07-12 06:53

/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, 2024 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
#include "utf8.h"
27
28
#include <math.h>
29
#include <float.h>
30
#include <string.h>
31
32
#if defined(_MSC_VER)
33
# define CJ5_INLINE __inline
34
#else
35
# define CJ5_INLINE inline
36
#endif
37
38
/* vs2008 does not have INFINITY and NAN defined */
39
#ifndef INFINITY
40
# define INFINITY ((double)(DBL_MAX+DBL_MAX))
41
#endif
42
#ifndef NAN
43
# define NAN ((double)(INFINITY-INFINITY))
44
#endif
45
46
#if defined(_MSC_VER)
47
# pragma warning(disable: 4056)
48
# pragma warning(disable: 4756)
49
#endif
50
51
/* Max nesting depth of objects and arrays */
52
504k
#define CJ5_MAX_NESTING 32
53
54
#define CJ5__FOURCC(_a, _b, _c, _d)                         \
55
    (((uint32_t)(_a) | ((uint32_t)(_b) << 8) |              \
56
      ((uint32_t)(_c) << 16) | ((uint32_t)(_d) << 24)))
57
58
static const uint32_t CJ5__NULL_FOURCC  = CJ5__FOURCC('n', 'u', 'l', 'l');
59
static const uint32_t CJ5__TRUE_FOURCC  = CJ5__FOURCC('t', 'r', 'u', 'e');
60
static const uint32_t CJ5__FALSE_FOURCC = CJ5__FOURCC('f', 'a', 'l', 's');
61
62
typedef struct {
63
    unsigned int pos;
64
    cj5_error_code error;
65
66
    const char *json5;
67
    unsigned int len;
68
69
    unsigned int curr_tok_idx;
70
71
    cj5_token *tokens;
72
    unsigned int token_count;
73
    unsigned int max_tokens;
74
75
    bool stop_early;
76
} cj5__parser;
77
78
static CJ5_INLINE bool
79
153M
cj5__isrange(char ch, char from, char to) {
80
153M
    return (uint8_t)(ch - from) <= (uint8_t)(to - from);
81
153M
}
82
83
116M
#define cj5__isupperchar(ch) cj5__isrange(ch, 'A', 'Z')
84
123M
#define cj5__islowerchar(ch) cj5__isrange(ch, 'a', 'z')
85
169M
#define cj5__isnum(ch)       cj5__isrange(ch, '0', '9')
86
87
static cj5_token *
88
35.8M
cj5__alloc_token(cj5__parser *parser) {
89
35.8M
    cj5_token* token = NULL;
90
35.8M
    if(parser->token_count < parser->max_tokens) {
91
17.2M
        token = &parser->tokens[parser->token_count];
92
17.2M
        memset(token, 0x0, sizeof(cj5_token));
93
18.6M
    } else {
94
18.6M
        parser->error = CJ5_ERROR_OVERFLOW;
95
18.6M
    }
96
97
    // Always increase the index. So we know eventually how many token would be
98
    // required (if there are not enough).
99
35.8M
    parser->token_count++;
100
35.8M
    return token;
101
35.8M
}
102
103
static void
104
5.82M
cj5__parse_string(cj5__parser *parser) {
105
5.82M
    const char *json5 = parser->json5;
106
5.82M
    unsigned int len = parser->len;
107
5.82M
    unsigned int start = parser->pos;
108
5.82M
    char str_open = json5[start];
109
110
5.82M
    parser->pos++;
111
72.7M
    for(; parser->pos < len; parser->pos++) {
112
72.7M
        char c = json5[parser->pos];
113
114
        // End of string
115
72.7M
        if(str_open == c) {
116
5.82M
            cj5_token *token = cj5__alloc_token(parser);
117
5.82M
            if(token) {
118
2.96M
                token->type = CJ5_TOKEN_STRING;
119
2.96M
                token->start = start + 1;
120
2.96M
                token->end = parser->pos - 1;
121
2.96M
                token->size = token->end - token->start + 1;
122
2.96M
                token->parent_id = parser->curr_tok_idx;
123
2.96M
            } 
124
5.82M
            return;
125
5.82M
        }
126
127
        // Unescaped newlines are forbidden
128
66.9M
        if(c == '\n') {
129
2
            parser->error = CJ5_ERROR_INVALID;
130
2
            return;
131
2
        }
132
133
        // Skip escape character
134
66.9M
        if(c == '\\') {
135
7.25M
            if(parser->pos + 1 >= len) {
136
2
                parser->error = CJ5_ERROR_INCOMPLETE;
137
2
                return;
138
2
            }
139
7.25M
            parser->pos++;
140
7.25M
        }
141
66.9M
    }
142
143
    // The file has ended before the string terminates
144
119
    parser->error = CJ5_ERROR_INCOMPLETE;
145
119
}
146
147
// parser->pos is advanced a last time in the next iteration of the main
148
// parse-loop. So we leave parse-primitive in a state where parse->pos points to
149
// the last character of the primitive value (or the quote-character of the
150
// string).
151
static void
152
34.8M
cj5__parse_primitive(cj5__parser* parser) {
153
34.8M
    const char* json5 = parser->json5;
154
34.8M
    unsigned int len = parser->len;
155
34.8M
    unsigned int start = parser->pos;
156
157
    // String value
158
34.8M
    if(json5[start] == '\"' ||
159
34.8M
       json5[start] == '\'') {
160
5.43M
        cj5__parse_string(parser);
161
5.43M
        return;
162
5.43M
    }
163
164
    // Fast comparison of bool, and null.
165
    // Make the comparison case-insensitive.
166
29.3M
    uint32_t fourcc = 0;
167
29.3M
    if(start + 3 < len) {
168
29.3M
        fourcc += json5[start] | 32;
169
29.3M
        fourcc += (json5[start+1] | 32) << 8;
170
29.3M
        fourcc += (json5[start+2] | 32) << 16;
171
29.3M
        fourcc += (json5[start+3] | 32) << 24;
172
29.3M
    }
173
    
174
29.3M
    cj5_token_type type;
175
29.3M
    if(fourcc == CJ5__NULL_FOURCC) {
176
364k
        type = CJ5_TOKEN_NULL;
177
364k
        parser->pos += 3;
178
29.0M
    } else if(fourcc == CJ5__TRUE_FOURCC) {
179
425
        type = CJ5_TOKEN_BOOL;
180
425
        parser->pos += 3;
181
29.0M
    } else if(fourcc == CJ5__FALSE_FOURCC) {
182
        // "false" has five characters
183
3.06k
        type = CJ5_TOKEN_BOOL;
184
3.06k
        if(start + 4 >= len || (json5[start+4] | 32) != 'e') {
185
20
            parser->error = CJ5_ERROR_INVALID;
186
20
            return;
187
20
        }
188
3.04k
        parser->pos += 4;
189
29.0M
    } else {
190
        // Numbers are checked for basic compatibility.
191
        // But they are fully parsed only in the cj5_get_XXX functions.
192
29.0M
        type = CJ5_TOKEN_NUMBER;
193
82.1M
        for(; parser->pos < len; parser->pos++) {
194
82.1M
            if(!cj5__isnum(json5[parser->pos]) &&
195
82.1M
               !(json5[parser->pos] == '.') &&
196
82.1M
               !cj5__islowerchar(json5[parser->pos]) && 
197
82.1M
               !cj5__isupperchar(json5[parser->pos]) &&
198
82.1M
               !(json5[parser->pos] == '+') && !(json5[parser->pos] == '-')) {
199
29.0M
                break;
200
29.0M
            }
201
82.1M
        }
202
29.0M
        parser->pos--; // Point to the last character that is still inside the
203
                       // primitive value
204
29.0M
    }
205
206
29.3M
    cj5_token *token = cj5__alloc_token(parser);
207
29.3M
    if(token) {
208
13.8M
        token->type = type;
209
13.8M
        token->start = start;
210
13.8M
        token->end = parser->pos;
211
13.8M
        token->size = parser->pos - start + 1;
212
13.8M
        token->parent_id = parser->curr_tok_idx;
213
13.8M
    }
214
29.3M
}
215
216
static void
217
478k
cj5__parse_key(cj5__parser* parser) {
218
478k
    const char* json5 = parser->json5;
219
478k
    unsigned int start = parser->pos;
220
478k
    cj5_token* token;
221
222
    // Key is a a normal string
223
478k
    if(json5[start] == '\"' || json5[start] == '\'') {
224
386k
        cj5__parse_string(parser);
225
386k
        return;
226
386k
    }
227
228
    // An unquoted key. Must start with a-ZA-Z_$. Can contain numbers later on.
229
91.5k
    unsigned int len = parser->len;
230
4.42M
    for(; parser->pos < len; parser->pos++) {
231
4.42M
        if(cj5__islowerchar(json5[parser->pos]) ||
232
4.42M
           cj5__isupperchar(json5[parser->pos]) ||
233
4.42M
           json5[parser->pos] == '_' || json5[parser->pos] == '$')
234
3.51M
            continue;
235
905k
        if(cj5__isnum(json5[parser->pos]) && parser->pos != start)
236
814k
            continue;
237
91.4k
        break;
238
905k
    }
239
240
    // An empty key is not allowed
241
91.5k
    if(parser->pos <= start) {
242
111
        parser->error = CJ5_ERROR_INVALID;
243
111
        return;
244
111
    }
245
246
    // Move pos to the last character within the unquoted key
247
91.4k
    parser->pos--;
248
249
91.4k
    token = cj5__alloc_token(parser);
250
91.4k
    if(token) {
251
59.0k
        token->type = CJ5_TOKEN_STRING;
252
59.0k
        token->start = start;
253
59.0k
        token->end = parser->pos;
254
59.0k
        token->size = parser->pos - start + 1;
255
59.0k
        token->parent_id = parser->curr_tok_idx;
256
59.0k
    }
257
91.4k
}
258
259
static void
260
3.33k
cj5__skip_comment(cj5__parser* parser) {
261
3.33k
    const char* json5 = parser->json5;
262
263
    // Single-line comment
264
3.33k
    if(json5[parser->pos] == '#') {
265
1.76k
    skip_line:
266
3.41M
        while(parser->pos < parser->len) {
267
3.41M
            if(json5[parser->pos] == '\n') {
268
1.69k
                parser->pos--; // Reparse the newline in the main parse loop
269
1.69k
                return;
270
1.69k
            }
271
3.41M
            parser->pos++;
272
3.41M
        }
273
72
        return;
274
1.76k
    }
275
276
    // Comment begins with '/' but not enough space for another character
277
2.92k
    if(parser->pos + 1 >= parser->len) {
278
34
        parser->error = CJ5_ERROR_INVALID;
279
34
        return;
280
34
    }
281
2.89k
    parser->pos++;
282
283
    // Comment begins with '//' -> single-line comment
284
2.89k
    if(json5[parser->pos] == '/')
285
1.36k
        goto skip_line;
286
287
    // Multi-line comments begin with '/*' and end with '*/'
288
1.53k
    if(json5[parser->pos] == '*') {
289
1.49k
        parser->pos++;
290
1.49M
        for(; parser->pos + 1 < parser->len; parser->pos++) {
291
1.49M
            if(json5[parser->pos] == '*' && json5[parser->pos + 1] == '/') {
292
1.41k
                parser->pos++;
293
1.41k
                return;
294
1.41k
            }
295
1.49M
        }
296
1.49k
    }
297
298
    // Unknown comment type or the multi-line comment is not terminated
299
122
    parser->error = CJ5_ERROR_INCOMPLETE;
300
122
}
301
302
cj5_result
303
cj5_parse(const char *json5, unsigned int len,
304
          cj5_token *tokens, unsigned int max_tokens,
305
12.0k
          cj5_options *options) {
306
12.0k
    cj5_result r;
307
12.0k
    cj5__parser parser;
308
12.0k
    memset(&parser, 0x0, sizeof(parser));
309
12.0k
    parser.curr_tok_idx = 0;
310
12.0k
    parser.json5 = json5;
311
12.0k
    parser.len = len;
312
12.0k
    parser.tokens = tokens;
313
12.0k
    parser.max_tokens = max_tokens;
314
315
12.0k
    if(options)
316
12.0k
        parser.stop_early = options->stop_early;
317
318
12.0k
    unsigned short depth = 0; // Nesting depth zero means "outside the root object"
319
12.0k
    char nesting[CJ5_MAX_NESTING]; // Contains either '\0', '{' or '[' for the
320
                                   // type of nesting at each depth. '\0'
321
                                   // indicates we are out of the root object.
322
12.0k
    char next[CJ5_MAX_NESTING];    // Next content to parse: 'k' (key), ':', 'v'
323
                                   // (value) or ',' (comma).
324
12.0k
    next[0] = 'v';  // The root is a "value" (object, array or primitive). If we
325
                    // detect a colon after the first value then everything is
326
                    // wrapped into a "virtual root object" and the parsing is
327
                    // restarted.
328
12.0k
    nesting[0] = 0; // Becomes '{' if there is a virtual root object
329
330
12.0k
    cj5_token *token = NULL; // The current token
331
332
17.0k
 start_parsing:
333
71.9M
    for(; parser.pos < len; parser.pos++) {
334
71.8M
        char c = json5[parser.pos];
335
71.8M
        switch(c) {
336
2.29k
        case '\n': // Skip newline and whitespace
337
4.77k
        case '\r':
338
6.10k
        case '\t':
339
6.84k
        case ' ':
340
6.84k
            break;
341
342
407
        case '#': // Skip comment
343
3.33k
        case '/':
344
3.33k
            cj5__skip_comment(&parser);
345
3.33k
            if(parser.error != CJ5_ERROR_NONE &&
346
3.33k
               parser.error != CJ5_ERROR_OVERFLOW)
347
156
                goto finish;
348
3.17k
            break;
349
350
486k
        case '{': // Open an object or array
351
504k
        case '[':
352
            // Check the nesting depth
353
504k
            if(depth + 1 >= CJ5_MAX_NESTING) {
354
3
                parser.error = CJ5_ERROR_INVALID;
355
3
                goto finish;
356
3
            }
357
358
            // Correct next?
359
504k
            if(next[depth] != 'v') {
360
34
                parser.error = CJ5_ERROR_INVALID;
361
34
                goto finish;
362
34
            }
363
364
504k
            depth++; // Increase the nesting depth
365
504k
            nesting[depth] = c; // Set the nesting type
366
504k
            next[depth] = (c == '{') ? 'k' : 'v'; // next is either a key or a value
367
368
            // Create a token for the object or array
369
504k
            token = cj5__alloc_token(&parser);
370
504k
            if(token) {
371
289k
                token->parent_id = parser.curr_tok_idx;
372
289k
                token->type = (c == '{') ? CJ5_TOKEN_OBJECT : CJ5_TOKEN_ARRAY;
373
289k
                token->start = parser.pos;
374
289k
                token->size = 0;
375
289k
                parser.curr_tok_idx = parser.token_count - 1; // The new curr_tok_idx
376
                                                              // is for this token
377
289k
            }
378
504k
            break;
379
380
485k
        case '}': // Close an object or array
381
502k
        case ']':
382
            // Check the nesting depth. Note that a "virtual root object" at
383
            // depth zero must not be closed.
384
502k
            if(depth == 0) {
385
23
                parser.error = CJ5_ERROR_INVALID;
386
23
                goto finish;
387
23
            }
388
389
            // Check and adjust the nesting. Note that ']' - '[' == 2 and '}' -
390
            // '{' == 2. Arrays can always be closed. Objects can only close
391
            // when a key or a comma is expected.
392
502k
            if(c - nesting[depth] != 2 ||
393
502k
               (c == '}' && next[depth] != 'k' && next[depth] != ',')) {
394
9
                parser.error = CJ5_ERROR_INVALID;
395
9
                goto finish;
396
9
            }
397
398
502k
            if(token) {
399
                // Finalize the current token
400
287k
                token->end = parser.pos;
401
402
                // Move to the parent and increase the parent size. Omit this
403
                // when we leave the root (parent the same as the current
404
                // token).
405
287k
                if(parser.curr_tok_idx != token->parent_id) {
406
280k
                    parser.curr_tok_idx = token->parent_id;
407
280k
                    token = &tokens[token->parent_id];
408
280k
                    token->size++;
409
280k
                }
410
287k
            }
411
412
            // Step one level up
413
502k
            depth--;
414
502k
            next[depth] = (depth == 0) ? 0 : ','; // zero if we step out the root
415
                                                  // object. then we do not look for
416
                                                  // another element.
417
418
            // The first element was successfully parsed. Stop early or try to
419
            // parse the full input string?
420
502k
            if(depth == 0 && parser.stop_early)
421
0
                goto finish;
422
423
502k
            break;
424
425
502k
        case ':': // Colon (between key and value)
426
482k
            if(next[depth] != ':') {
427
4.68k
                parser.error = CJ5_ERROR_INVALID;
428
4.68k
                goto finish;
429
4.68k
            }
430
477k
            next[depth] = 'v';
431
477k
            break;
432
433
35.0M
        case ',': // Comma
434
35.0M
            if(next[depth] != ',') {
435
12
                parser.error = CJ5_ERROR_INVALID;
436
12
                goto finish;
437
12
            }
438
35.0M
            next[depth] = (nesting[depth] == '{') ? 'k' : 'v';
439
35.0M
            break;
440
441
35.3M
        default: // Value or key
442
35.3M
            if(next[depth] == 'v') {
443
34.8M
                cj5__parse_primitive(&parser); // Parse primitive value
444
34.8M
                if(nesting[depth] != 0) {
445
                    // Parent is object or array
446
34.8M
                    if(token)
447
33.0M
                        token->size++;
448
34.8M
                    next[depth] = ',';
449
34.8M
                } else {
450
                    // The current value was the root element. Don't look for
451
                    // any next element.
452
5.06k
                    next[depth] = 0;
453
454
                    // The first element was successfully parsed. Stop early or try to
455
                    // parse the full input string?
456
5.06k
                    if(parser.stop_early)
457
0
                        goto finish;
458
5.06k
                }
459
34.8M
            } else if(next[depth] == 'k') {
460
478k
                cj5__parse_key(&parser);
461
478k
                if(token)
462
292k
                    token->size++; // Keys count towards the length
463
478k
                next[depth] = ':';
464
478k
            } else {
465
288
                parser.error = CJ5_ERROR_INVALID;
466
288
            }
467
468
35.3M
            if(parser.error && parser.error != CJ5_ERROR_OVERFLOW)
469
542
                goto finish;
470
471
35.3M
            break;
472
71.8M
        }
473
71.8M
    }
474
475
    // Are we back to the initial nesting depth?
476
11.6k
    if(depth != 0) {
477
99
        parser.error = CJ5_ERROR_INCOMPLETE;
478
99
        goto finish;
479
99
    }
480
481
    // Close the virtual root object if there is one
482
11.5k
    if(nesting[0] == '{' && parser.error != CJ5_ERROR_OVERFLOW) {
483
        // Check the we end after a complete key-value pair (or dangling comma)
484
4.68k
        if(next[0] != 'k' && next[0] != ',')
485
79
            parser.error = CJ5_ERROR_INVALID;
486
4.68k
        tokens[0].end = parser.pos - 1;
487
4.68k
    }
488
489
17.0k
 finish:
490
    // If parsing failed at the initial nesting depth, create a virtual root object
491
    // and restart parsing.
492
17.0k
    if(parser.error != CJ5_ERROR_NONE &&
493
17.0k
       parser.error != CJ5_ERROR_OVERFLOW &&
494
17.0k
       depth == 0 && nesting[0] != '{') {
495
5.05k
        parser.token_count = 0;
496
5.05k
        token = cj5__alloc_token(&parser);
497
5.05k
        if(token) {
498
5.05k
            token->parent_id = 0;
499
5.05k
            token->type = CJ5_TOKEN_OBJECT;
500
5.05k
            token->start = 0;
501
5.05k
            token->size = 0;
502
503
5.05k
            nesting[0] = '{';
504
5.05k
            next[0] = 'k';
505
506
5.05k
            parser.curr_tok_idx = 0;
507
5.05k
            parser.pos = 0;
508
5.05k
            parser.error = CJ5_ERROR_NONE;
509
5.05k
            goto start_parsing;
510
5.05k
        }
511
5.05k
    }
512
513
12.0k
    memset(&r, 0x0, sizeof(r));
514
12.0k
    r.error = parser.error;
515
12.0k
    r.error_pos = parser.pos;
516
12.0k
    r.num_tokens = parser.token_count; // How many tokens (would) have been
517
                                       // consumed by the parser?
518
519
    // Not a single token was parsed -> return an error
520
12.0k
    if(r.num_tokens == 0)
521
30
        r.error = CJ5_ERROR_INCOMPLETE;
522
523
    // Set the tokens and original string only if successfully parsed
524
12.0k
    if(r.error == CJ5_ERROR_NONE) {
525
10.7k
        r.tokens = tokens;
526
10.7k
        r.json5 = json5;
527
10.7k
    }
528
529
12.0k
    return r;
530
17.0k
}
531
532
cj5_error_code
533
0
cj5_get_bool(const cj5_result *r, unsigned int tok_index, bool *out) {
534
0
    const cj5_token *token = &r->tokens[tok_index];
535
0
    if(token->type != CJ5_TOKEN_BOOL)
536
0
        return CJ5_ERROR_INVALID;
537
0
    *out = (r->json5[token->start] == 't');
538
0
    return CJ5_ERROR_NONE;
539
0
}
540
541
cj5_error_code
542
0
cj5_get_float(const cj5_result *r, unsigned int tok_index, double *out) {
543
0
    const cj5_token *token = &r->tokens[tok_index];
544
0
    if(token->type != CJ5_TOKEN_NUMBER)
545
0
        return CJ5_ERROR_INVALID;
546
547
0
    const char *tokstr = &r->json5[token->start];
548
0
    size_t toksize = token->end - token->start + 1;
549
0
    if(toksize == 0)
550
0
        return CJ5_ERROR_INVALID;
551
552
    // Skip prefixed +/-
553
0
    bool neg = false;
554
0
    if(tokstr[0] == '+' || tokstr[0] == '-') {
555
0
        neg = (tokstr[0] == '-');
556
0
        tokstr++;
557
0
        toksize--;
558
0
    }
559
560
    // Detect prefixed inf/nan
561
0
    if(strncmp(tokstr, "Infinity", toksize) == 0) {
562
0
        *out = neg ? -INFINITY : INFINITY;
563
0
        return CJ5_ERROR_NONE;
564
0
    } else if(strncmp(tokstr, "NaN", toksize) == 0) {
565
0
        *out = NAN;
566
0
        return CJ5_ERROR_NONE;
567
0
    }
568
569
    // reset the +/- detection and parse
570
0
    tokstr = &r->json5[token->start];
571
0
    toksize = token->end - token->start + 1;
572
0
    size_t parsed = parseDouble(tokstr, toksize, out);
573
574
    // There must only be whitespace between the end of the parsed number and
575
    // the end of the token
576
0
    for(size_t i = parsed; i < toksize; i++) {
577
0
        if(tokstr[i] != ' ' && tokstr[i] -'\t' >= 5)
578
0
            return CJ5_ERROR_INVALID;
579
0
    }
580
581
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
582
0
}
583
584
cj5_error_code
585
cj5_get_int(const cj5_result *r, unsigned int tok_index,
586
0
            int64_t *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
0
    size_t parsed = parseInt64(&r->json5[token->start], token->size, out);
591
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
592
0
}
593
594
cj5_error_code
595
cj5_get_uint(const cj5_result *r, unsigned int tok_index,
596
0
             uint64_t *out) {
597
0
    const cj5_token *token = &r->tokens[tok_index];
598
0
    if(token->type != CJ5_TOKEN_NUMBER)
599
0
        return CJ5_ERROR_INVALID;
600
0
    size_t parsed = parseUInt64(&r->json5[token->start], token->size, out);
601
0
    return (parsed != 0) ? CJ5_ERROR_NONE : CJ5_ERROR_INVALID;
602
0
}
603
604
static const uint32_t SURROGATE_OFFSET = 0x10000u - (0xD800u << 10) - 0xDC00;
605
606
static cj5_error_code
607
830k
parse_codepoint(const char *pos, uint32_t *out_utf) {
608
830k
    uint32_t utf = 0;
609
4.15M
    for(unsigned int i = 0; i < 4; i++) {
610
3.32M
        char byte = pos[i];
611
3.32M
        if(cj5__isnum(byte)) {
612
2.48M
            byte = (char)(byte - '0');
613
2.48M
        } else if(cj5__isrange(byte, 'a', 'f')) {
614
835k
            byte = (char)(byte - ('a' - 10));
615
835k
        } else if(cj5__isrange(byte, 'A', 'F')) {
616
3.33k
            byte = (char)(byte - ('A' - 10));
617
3.33k
        } else {
618
16
            return CJ5_ERROR_INVALID;
619
16
        }
620
3.32M
        utf = (utf << 4) | ((uint8_t)byte & 0xF);
621
3.32M
    }
622
830k
    *out_utf = utf;
623
830k
    return CJ5_ERROR_NONE;
624
830k
}
625
626
cj5_error_code
627
cj5_get_str(const cj5_result *r, unsigned int tok_index,
628
109k
            char *buf, unsigned int *buflen) {
629
109k
    const cj5_token *token = &r->tokens[tok_index];
630
109k
    if(token->type != CJ5_TOKEN_STRING)
631
0
        return CJ5_ERROR_INVALID;
632
633
109k
    const char *pos = &r->json5[token->start];
634
109k
    const char *end = &r->json5[token->end + 1];
635
109k
    unsigned int outpos = 0;
636
30.6M
    for(; pos < end; pos++) {
637
30.5M
        uint8_t c = (uint8_t)*pos;
638
        // Unprintable ascii characters must be escaped
639
30.5M
        if(c < ' ' || c == 127)
640
23
            return CJ5_ERROR_INVALID;
641
642
        // Unescaped Ascii character or utf8 byte
643
30.5M
        if(c != '\\') {
644
24.5M
            buf[outpos++] = (char)c;
645
24.5M
            continue;
646
24.5M
        }
647
648
        // End of input before the escaped character
649
5.99M
        if(pos + 1 >= end)
650
0
            return CJ5_ERROR_INCOMPLETE;
651
652
        // Process escaped character
653
5.99M
        pos++;
654
5.99M
        c = (uint8_t)*pos;
655
5.99M
        switch(c) {
656
8.12k
        case 'b': buf[outpos++] = '\b'; break;
657
7.17k
        case 'f': buf[outpos++] = '\f'; break;
658
1.28k
        case 'r': buf[outpos++] = '\r'; break;
659
53.5k
        case 'n': buf[outpos++] = '\n'; break;
660
1.50k
        case 't': buf[outpos++] = '\t'; break;
661
5.10M
        default:  buf[outpos++] = c;    break;
662
826k
        case 'u': {
663
            // Parse a unicode code point
664
826k
            if(pos + 4 >= end)
665
1
                return CJ5_ERROR_INCOMPLETE;
666
826k
            pos++;
667
826k
            uint32_t utf;
668
826k
            cj5_error_code err = parse_codepoint(pos, &utf);
669
826k
            if(err != CJ5_ERROR_NONE)
670
8
                return err;
671
826k
            pos += 3;
672
673
            // Parse a surrogate pair
674
826k
            if(0xd800 <= utf && utf <= 0xdfff) {
675
4.15k
                if(pos + 6 >= end)
676
8
                    return CJ5_ERROR_INVALID;
677
4.14k
                if(pos[1] != '\\' && pos[2] != 'u')
678
5
                    return CJ5_ERROR_INVALID;
679
4.13k
                pos += 3;
680
4.13k
                uint32_t utf2;
681
4.13k
                err = parse_codepoint(pos, &utf2);
682
4.13k
                if(err != CJ5_ERROR_NONE)
683
8
                    return err;
684
4.12k
                pos += 3;
685
                // High or low surrogate pair
686
4.12k
                utf = (utf <= 0xdbff) ?
687
3.74k
                    (utf << 10) + utf2 + SURROGATE_OFFSET :
688
4.12k
                    (utf2 << 10) + utf + SURROGATE_OFFSET;
689
4.12k
            }
690
691
            // Write the utf8 bytes of the code point
692
826k
            unsigned len = utf8_from_codepoint((unsigned char*)buf + outpos, utf);
693
826k
            if(len == 0)
694
33
                return CJ5_ERROR_INVALID; // Not a utf8 string
695
826k
            outpos += len;
696
826k
            break;
697
826k
        }
698
5.99M
        }
699
5.99M
    }
700
701
    // Terminate with \0
702
109k
    buf[outpos] = 0;
703
704
    // Set the output length
705
109k
    if(buflen)
706
109k
        *buflen = outpos;
707
109k
    return CJ5_ERROR_NONE;
708
109k
}
709
710
void
711
0
cj5_skip(const cj5_result *r, unsigned int *tok_index) {
712
0
    unsigned int idx = *tok_index;
713
0
    unsigned int end = r->tokens[idx].end;
714
0
    do { idx++; } while(idx < r->num_tokens &&
715
0
                        r->tokens[idx].start < end);
716
0
    *tok_index = idx;
717
0
}
718
719
cj5_error_code
720
cj5_find(const cj5_result *r, unsigned int *tok_index,
721
0
         const char *key) {
722
    // It has to be an object
723
0
    unsigned int idx = *tok_index;
724
0
    if(r->tokens[idx].type != CJ5_TOKEN_OBJECT)
725
0
        return CJ5_ERROR_INVALID;
726
0
    unsigned int size = r->tokens[idx].size;
727
728
    // Skip to the first key
729
0
    idx++;
730
731
    // Size is number of keys + number of values
732
0
    for(unsigned int i = 0; i < size; i += 2) {
733
        // Key has to be a string
734
0
        if(r->tokens[idx].type != CJ5_TOKEN_STRING)
735
0
            return CJ5_ERROR_INVALID;
736
737
        // Return the index to the value if the key matches
738
0
        const char *keystart = &r->json5[r->tokens[idx].start];
739
0
        size_t keysize = r->tokens[idx].end - r->tokens[idx].start + 1;
740
0
        if(strncmp(key, keystart, keysize) == 0) {
741
0
            *tok_index = idx + 1;
742
0
            return CJ5_ERROR_NONE;
743
0
        }
744
745
        // Skip over the value
746
0
        idx++;
747
0
        cj5_skip(r, &idx);
748
0
    }
749
0
    return CJ5_ERROR_NOTFOUND;
750
0
}