Coverage Report

Created: 2026-10-15 06:43

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