Coverage Report

Created: 2026-09-27 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541_15/deps/cj5.c
Line
Count
Source
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
4.62M
#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
1.19G
cj5__isrange(char ch, char from, char to) {
80
1.19G
    return (uint8_t)(ch - from) <= (uint8_t)(to - from);
81
1.19G
}
82
83
919M
#define cj5__isupperchar(ch) cj5__isrange(ch, 'A', 'Z')
84
1.00G
#define cj5__islowerchar(ch) cj5__isrange(ch, 'a', 'z')
85
1.07G
#define cj5__isnum(ch)       cj5__isrange(ch, '0', '9')
86
87
static cj5_token *
88
236M
cj5__alloc_token(cj5__parser *parser) {
89
236M
    cj5_token* token = NULL;
90
236M
    if(parser->token_count < parser->max_tokens) {
91
114M
        token = &parser->tokens[parser->token_count];
92
114M
        memset(token, 0x0, sizeof(cj5_token));
93
121M
    } else {
94
121M
        parser->error = CJ5_ERROR_OVERFLOW;
95
121M
    }
96
97
    // Always increase the index. So we know eventually how many token would be
98
    // required (if there are not enough).
99
236M
    parser->token_count++;
100
236M
    return token;
101
236M
}
102
103
static void
104
13.6M
cj5__parse_string(cj5__parser *parser) {
105
13.6M
    const char *json5 = parser->json5;
106
13.6M
    unsigned int len = parser->len;
107
13.6M
    unsigned int start = parser->pos;
108
13.6M
    char str_open = json5[start];
109
110
13.6M
    parser->pos++;
111
472M
    for(; parser->pos < len; parser->pos++) {
112
472M
        char c = json5[parser->pos];
113
114
        // End of string
115
472M
        if(str_open == c) {
116
13.6M
            cj5_token *token = cj5__alloc_token(parser);
117
13.6M
            if(token) {
118
7.28M
                token->type = CJ5_TOKEN_STRING;
119
7.28M
                token->start = start + 1;
120
7.28M
                token->end = parser->pos - 1;
121
7.28M
                token->size = token->end - token->start + 1;
122
7.28M
                token->parent_id = parser->curr_tok_idx;
123
7.28M
            } 
124
13.6M
            return;
125
13.6M
        }
126
127
        // Unescaped newlines are forbidden
128
458M
        if(c == '\n') {
129
207
            parser->error = CJ5_ERROR_INVALID;
130
207
            return;
131
207
        }
132
133
        // Skip escape character
134
458M
        if(c == '\\') {
135
24.2M
            if(parser->pos + 1 >= len) {
136
35
                parser->error = CJ5_ERROR_INCOMPLETE;
137
35
                return;
138
35
            }
139
24.2M
            parser->pos++;
140
24.2M
        }
141
458M
    }
142
143
    // The file has ended before the string terminates
144
4.35k
    parser->error = CJ5_ERROR_INCOMPLETE;
145
4.35k
}
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
208M
cj5__parse_primitive(cj5__parser* parser) {
153
208M
    const char* json5 = parser->json5;
154
208M
    unsigned int len = parser->len;
155
208M
    unsigned int start = parser->pos;
156
157
    // String value
158
208M
    if(json5[start] == '\"' ||
159
199M
       json5[start] == '\'') {
160
10.1M
        cj5__parse_string(parser);
161
10.1M
        return;
162
10.1M
    }
163
164
    // Fast comparison of bool, and null.
165
    // Make the comparison case-insensitive.
166
198M
    uint32_t fourcc = 0;
167
198M
    if(start + 3 < len) {
168
195M
        fourcc += (unsigned char)json5[start] | 32U;
169
195M
        fourcc += ((unsigned char)json5[start+1] | 32U) << 8;
170
195M
        fourcc += ((unsigned char)json5[start+2] | 32U) << 16;
171
195M
        fourcc += ((unsigned char)json5[start+3] | 32U) << 24;
172
195M
    }
173
    
174
198M
    cj5_token_type type;
175
198M
    if(fourcc == CJ5__NULL_FOURCC) {
176
513k
        type = CJ5_TOKEN_NULL;
177
513k
        parser->pos += 3;
178
198M
    } else if(fourcc == CJ5__TRUE_FOURCC) {
179
251k
        type = CJ5_TOKEN_BOOL;
180
251k
        parser->pos += 3;
181
197M
    } else if(fourcc == CJ5__FALSE_FOURCC) {
182
        // "false" has five characters
183
27.3k
        type = CJ5_TOKEN_BOOL;
184
27.3k
        if(start + 4 >= len || (json5[start+4] | 32) != 'e') {
185
167
            parser->error = CJ5_ERROR_INVALID;
186
167
            return;
187
167
        }
188
27.2k
        parser->pos += 4;
189
197M
    } else {
190
        // Numbers are checked for basic compatibility.
191
        // But they are fully parsed only in the cj5_get_XXX functions.
192
197M
        type = CJ5_TOKEN_NUMBER;
193
500M
        for(; parser->pos < len; parser->pos++) {
194
496M
            if(!cj5__isnum(json5[parser->pos]) &&
195
238M
               !(json5[parser->pos] == '.') &&
196
234M
               !cj5__islowerchar(json5[parser->pos]) && 
197
202M
               !cj5__isupperchar(json5[parser->pos]) &&
198
195M
               !(json5[parser->pos] == '+') && !(json5[parser->pos] == '-')) {
199
193M
                break;
200
193M
            }
201
496M
        }
202
197M
        parser->pos--; // Point to the last character that is still inside the
203
                       // primitive value
204
197M
    }
205
206
198M
    cj5_token *token = cj5__alloc_token(parser);
207
198M
    if(token) {
208
95.1M
        token->type = type;
209
95.1M
        token->start = start;
210
95.1M
        token->end = parser->pos;
211
95.1M
        token->size = parser->pos - start + 1;
212
95.1M
        token->parent_id = parser->curr_tok_idx;
213
95.1M
    }
214
198M
}
215
216
static void
217
22.8M
cj5__parse_key(cj5__parser* parser) {
218
22.8M
    const char* json5 = parser->json5;
219
22.8M
    unsigned int start = parser->pos;
220
22.8M
    cj5_token* token;
221
222
    // Key is a a normal string
223
22.8M
    if(json5[start] == '\"' || json5[start] == '\'') {
224
3.57M
        cj5__parse_string(parser);
225
3.57M
        return;
226
3.57M
    }
227
228
    // An unquoted key. Must start with a-ZA-Z_$. Can contain numbers later on.
229
19.2M
    unsigned int len = parser->len;
230
134M
    for(; parser->pos < len; parser->pos++) {
231
134M
        if(cj5__islowerchar(json5[parser->pos]) ||
232
86.1M
           cj5__isupperchar(json5[parser->pos]) ||
233
63.5M
           json5[parser->pos] == '_' || json5[parser->pos] == '$')
234
100M
            continue;
235
34.4M
        if(cj5__isnum(json5[parser->pos]) && parser->pos != start)
236
15.1M
            continue;
237
19.2M
        break;
238
34.4M
    }
239
240
    // An empty key is not allowed
241
19.2M
    if(parser->pos <= start) {
242
1.04k
        parser->error = CJ5_ERROR_INVALID;
243
1.04k
        return;
244
1.04k
    }
245
246
    // Move pos to the last character within the unquoted key
247
19.2M
    parser->pos--;
248
249
19.2M
    token = cj5__alloc_token(parser);
250
19.2M
    if(token) {
251
9.58M
        token->type = CJ5_TOKEN_STRING;
252
9.58M
        token->start = start;
253
9.58M
        token->end = parser->pos;
254
9.58M
        token->size = parser->pos - start + 1;
255
9.58M
        token->parent_id = parser->curr_tok_idx;
256
9.58M
    }
257
19.2M
}
258
259
static void
260
334k
cj5__skip_comment(cj5__parser* parser) {
261
334k
    const char* json5 = parser->json5;
262
263
    // Single-line comment
264
334k
    if(json5[parser->pos] == '#') {
265
150k
    skip_line:
266
54.0M
        while(parser->pos < parser->len) {
267
53.9M
            if(json5[parser->pos] == '\n') {
268
96.8k
                parser->pos--; // Reparse the newline in the main parse loop
269
96.8k
                return;
270
96.8k
            }
271
53.8M
            parser->pos++;
272
53.8M
        }
273
53.3k
        return;
274
150k
    }
275
276
    // Comment begins with '/' but not enough space for another character
277
283k
    if(parser->pos + 1 >= parser->len) {
278
199
        parser->error = CJ5_ERROR_INVALID;
279
199
        return;
280
199
    }
281
283k
    parser->pos++;
282
283
    // Comment begins with '//' -> single-line comment
284
283k
    if(json5[parser->pos] == '/')
285
99.2k
        goto skip_line;
286
287
    // Multi-line comments begin with '/*' and end with '*/'
288
184k
    if(json5[parser->pos] == '*') {
289
183k
        parser->pos++;
290
18.4M
        for(; parser->pos + 1 < parser->len; parser->pos++) {
291
18.4M
            if(json5[parser->pos] == '*' && json5[parser->pos + 1] == '/') {
292
183k
                parser->pos++;
293
183k
                return;
294
183k
            }
295
18.4M
        }
296
183k
    }
297
298
    // Unknown comment type or the multi-line comment is not terminated
299
1.00k
    parser->error = CJ5_ERROR_INCOMPLETE;
300
1.00k
}
301
302
cj5_result
303
cj5_parse(const char *json5, unsigned int len,
304
          cj5_token *tokens, unsigned int max_tokens,
305
5.07M
          cj5_options *options) {
306
5.07M
    cj5_result r;
307
5.07M
    cj5__parser parser;
308
5.07M
    memset(&parser, 0x0, sizeof(parser));
309
5.07M
    parser.curr_tok_idx = 0;
310
5.07M
    parser.json5 = json5;
311
5.07M
    parser.len = len;
312
5.07M
    parser.tokens = tokens;
313
5.07M
    parser.max_tokens = max_tokens;
314
315
5.07M
    if(options)
316
5.06M
        parser.stop_early = options->stop_early;
317
318
5.07M
    unsigned short depth = 0; // Nesting depth zero means "outside the root object"
319
5.07M
    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
5.07M
    char next[CJ5_MAX_NESTING];    // Next content to parse: 'k' (key), ':', 'v'
323
                                   // (value) or ',' (comma).
324
5.07M
    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
5.07M
    nesting[0] = 0; // Becomes '{' if there is a virtual root object
329
330
5.07M
    cj5_token *token = NULL; // The current token
331
332
5.15M
 start_parsing:
333
479M
    for(; parser.pos < len; parser.pos++) {
334
474M
        char c = json5[parser.pos];
335
474M
        switch(c) {
336
909k
        case '\n': // Skip newline and whitespace
337
2.31M
        case '\r':
338
3.82M
        case '\t':
339
4.14M
        case ' ':
340
4.14M
            break;
341
342
50.9k
        case '#': // Skip comment
343
334k
        case '/':
344
334k
            cj5__skip_comment(&parser);
345
334k
            if(parser.error != CJ5_ERROR_NONE &&
346
43.7k
               parser.error != CJ5_ERROR_OVERFLOW)
347
1.20k
                goto finish;
348
333k
            break;
349
350
4.21M
        case '{': // Open an object or array
351
4.62M
        case '[':
352
            // Check the nesting depth
353
4.62M
            if(depth + 1 >= CJ5_MAX_NESTING) {
354
24
                parser.error = CJ5_ERROR_INVALID;
355
24
                goto finish;
356
24
            }
357
358
            // Correct next?
359
4.62M
            if(next[depth] != 'v') {
360
268
                parser.error = CJ5_ERROR_INVALID;
361
268
                goto finish;
362
268
            }
363
364
4.62M
            depth++; // Increase the nesting depth
365
4.62M
            nesting[depth] = c; // Set the nesting type
366
4.62M
            next[depth] = (c == '{') ? 'k' : 'v'; // next is either a key or a value
367
368
            // Create a token for the object or array
369
4.62M
            token = cj5__alloc_token(&parser);
370
4.62M
            if(token) {
371
2.50M
                token->parent_id = parser.curr_tok_idx;
372
2.50M
                token->type = (c == '{') ? CJ5_TOKEN_OBJECT : CJ5_TOKEN_ARRAY;
373
2.50M
                token->start = parser.pos;
374
2.50M
                token->size = 0;
375
2.50M
                parser.curr_tok_idx = parser.token_count - 1; // The new curr_tok_idx
376
                                                              // is for this token
377
2.50M
            }
378
4.62M
            break;
379
380
4.20M
        case '}': // Close an object or array
381
4.54M
        case ']':
382
            // Check the nesting depth. Note that a "virtual root object" at
383
            // depth zero must not be closed.
384
4.54M
            if(depth == 0) {
385
148
                parser.error = CJ5_ERROR_INVALID;
386
148
                goto finish;
387
148
            }
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
4.54M
            if(c - nesting[depth] != 2 ||
393
4.54M
               (c == '}' && next[depth] != 'k' && next[depth] != ',')) {
394
107
                parser.error = CJ5_ERROR_INVALID;
395
107
                goto finish;
396
107
            }
397
398
4.54M
            if(token) {
399
                // Finalize the current token
400
2.41M
                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
2.41M
                if(parser.curr_tok_idx != token->parent_id) {
406
2.35M
                    parser.curr_tok_idx = token->parent_id;
407
2.35M
                    token = &tokens[token->parent_id];
408
2.35M
                    token->size++;
409
2.35M
                }
410
2.41M
            }
411
412
            // Step one level up
413
4.54M
            depth--;
414
4.54M
            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
4.54M
            if(depth == 0 && parser.stop_early)
421
33.0k
                goto finish;
422
423
4.51M
            break;
424
425
22.8M
        case ':': // Colon (between key and value)
426
22.8M
            if(next[depth] != ':') {
427
76.3k
                parser.error = CJ5_ERROR_INVALID;
428
76.3k
                goto finish;
429
76.3k
            }
430
22.8M
            next[depth] = 'v';
431
22.8M
            break;
432
433
206M
        case ',': // Comma
434
206M
            if(next[depth] != ',') {
435
179
                parser.error = CJ5_ERROR_INVALID;
436
179
                goto finish;
437
179
            }
438
206M
            next[depth] = (nesting[depth] == '{') ? 'k' : 'v';
439
206M
            break;
440
441
231M
        default: // Value or key
442
231M
            if(next[depth] == 'v') {
443
208M
                cj5__parse_primitive(&parser); // Parse primitive value
444
208M
                if(nesting[depth] != 0) {
445
                    // Parent is object or array
446
203M
                    if(token)
447
185M
                        token->size++;
448
203M
                    next[depth] = ',';
449
203M
                } else {
450
                    // The current value was the root element. Don't look for
451
                    // any next element.
452
5.00M
                    next[depth] = 0;
453
454
                    // The first element was successfully parsed. Stop early or try to
455
                    // parse the full input string?
456
5.00M
                    if(parser.stop_early)
457
0
                        goto finish;
458
5.00M
                }
459
208M
            } else if(next[depth] == 'k') {
460
22.8M
                cj5__parse_key(&parser);
461
22.8M
                if(token)
462
19.0M
                    token->size++; // Keys count towards the length
463
22.8M
                next[depth] = ':';
464
22.8M
            } else {
465
2.73k
                parser.error = CJ5_ERROR_INVALID;
466
2.73k
            }
467
468
231M
            if(parser.error && parser.error != CJ5_ERROR_OVERFLOW)
469
8.54k
                goto finish;
470
471
231M
            break;
472
474M
        }
473
474M
    }
474
475
    // Are we back to the initial nesting depth?
476
5.03M
    if(depth != 0) {
477
1.65k
        parser.error = CJ5_ERROR_INCOMPLETE;
478
1.65k
        goto finish;
479
1.65k
    }
480
481
    // Close the virtual root object if there is one
482
5.03M
    if(nesting[0] == '{' && parser.error != CJ5_ERROR_OVERFLOW) {
483
        // Check the we end after a complete key-value pair (or dangling comma)
484
75.3k
        if(next[0] != 'k' && next[0] != ',')
485
471
            parser.error = CJ5_ERROR_INVALID;
486
75.3k
        tokens[0].end = parser.pos - 1;
487
75.3k
    }
488
489
5.15M
 finish:
490
    // If parsing failed at the initial nesting depth, create a virtual root object
491
    // and restart parsing.
492
5.15M
    if(parser.error != CJ5_ERROR_NONE &&
493
92.6k
       parser.error != CJ5_ERROR_OVERFLOW &&
494
88.9k
       depth == 0 && nesting[0] != '{') {
495
80.7k
        parser.token_count = 0;
496
80.7k
        token = cj5__alloc_token(&parser);
497
80.7k
        if(token) {
498
80.7k
            token->parent_id = 0;
499
80.7k
            token->type = CJ5_TOKEN_OBJECT;
500
80.7k
            token->start = 0;
501
80.7k
            token->size = 0;
502
503
80.7k
            nesting[0] = '{';
504
80.7k
            next[0] = 'k';
505
506
80.7k
            parser.curr_tok_idx = 0;
507
80.7k
            parser.pos = 0;
508
80.7k
            parser.error = CJ5_ERROR_NONE;
509
80.7k
            goto start_parsing;
510
80.7k
        }
511
80.7k
    }
512
513
5.07M
    memset(&r, 0x0, sizeof(r));
514
5.07M
    r.error = parser.error;
515
5.07M
    r.error_pos = parser.pos;
516
5.07M
    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
5.07M
    if(r.num_tokens == 0)
521
420
        r.error = CJ5_ERROR_INCOMPLETE;
522
523
    // Set the tokens and original string only if successfully parsed
524
5.07M
    if(r.error == CJ5_ERROR_NONE) {
525
5.06M
        r.tokens = tokens;
526
5.06M
        r.json5 = json5;
527
5.06M
    }
528
529
5.07M
    return r;
530
5.15M
}
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
2.17M
parse_codepoint(const char *pos, uint32_t *out_utf) {
608
2.17M
    uint32_t utf = 0;
609
10.8M
    for(unsigned int i = 0; i < 4; i++) {
610
8.71M
        char byte = pos[i];
611
8.71M
        if(cj5__isnum(byte)) {
612
6.46M
            byte = (char)(byte - '0');
613
6.46M
        } else if(cj5__isrange(byte, 'a', 'f')) {
614
2.20M
            byte = (char)(byte - ('a' - 10));
615
2.20M
        } else if(cj5__isrange(byte, 'A', 'F')) {
616
38.3k
            byte = (char)(byte - ('A' - 10));
617
38.3k
        } else {
618
2.29k
            return CJ5_ERROR_INVALID;
619
2.29k
        }
620
8.71M
        utf = (utf << 4) | ((uint8_t)byte & 0xF);
621
8.71M
    }
622
2.17M
    *out_utf = utf;
623
2.17M
    return CJ5_ERROR_NONE;
624
2.17M
}
625
626
cj5_error_code
627
cj5_get_str(const cj5_result *r, unsigned int tok_index,
628
1.55M
            char *buf, unsigned int *buflen) {
629
1.55M
    const cj5_token *token = &r->tokens[tok_index];
630
1.55M
    if(token->type != CJ5_TOKEN_STRING) {
631
1
        buf[0] = 0;
632
1
        if(buflen)
633
1
            *buflen = 0;
634
1
        return CJ5_ERROR_INVALID;
635
1
    }
636
637
1.55M
    const char *pos = &r->json5[token->start];
638
1.55M
    const char *end = &r->json5[token->end + 1];
639
1.55M
    unsigned int outpos = 0;
640
1.55M
    cj5_error_code error = CJ5_ERROR_NONE;
641
187M
    for(; pos < end; pos++) {
642
186M
        uint8_t c = (uint8_t)*pos;
643
        // Unprintable ascii characters must be escaped
644
186M
        if(c < ' ' || c == 127) {
645
5.24k
            error = CJ5_ERROR_INVALID;
646
5.24k
            goto done;
647
5.24k
        }
648
649
        // Unescaped Ascii character or utf8 byte
650
186M
        if(c != '\\') {
651
167M
            buf[outpos++] = (char)c;
652
167M
            continue;
653
167M
        }
654
655
        // End of input before the escaped character
656
18.8M
        if(pos + 1 >= end) {
657
0
            error = CJ5_ERROR_INCOMPLETE;
658
0
            goto done;
659
0
        }
660
661
        // Process escaped character
662
18.8M
        pos++;
663
18.8M
        c = (uint8_t)*pos;
664
18.8M
        switch(c) {
665
15.3k
        case 'b': buf[outpos++] = '\b'; break;
666
28.8k
        case 'f': buf[outpos++] = '\f'; break;
667
7.93k
        case 'r': buf[outpos++] = '\r'; break;
668
149k
        case 'n': buf[outpos++] = '\n'; break;
669
35.1k
        case 't': buf[outpos++] = '\t'; break;
670
16.4M
        default:  buf[outpos++] = (char)c; break;
671
2.16M
        case 'u': {
672
            // Parse a unicode code point
673
2.16M
            if(pos + 4 >= end) {
674
321
                error = CJ5_ERROR_INCOMPLETE;
675
321
                goto done;
676
321
            }
677
2.16M
            pos++;
678
2.16M
            uint32_t utf;
679
2.16M
            error = parse_codepoint(pos, &utf);
680
2.16M
            if(error != CJ5_ERROR_NONE)
681
966
                goto done;
682
2.16M
            pos += 3;
683
684
            // Parse a surrogate pair
685
2.16M
            if(0xd800 <= utf && utf <= 0xdfff) {
686
14.2k
                if(pos + 6 >= end) {
687
334
                    error = CJ5_ERROR_INVALID;
688
334
                    goto done;
689
334
                }
690
13.8k
                if(pos[1] != '\\' && pos[2] != 'u') {
691
309
                    error = CJ5_ERROR_INVALID;
692
309
                    goto done;
693
309
                }
694
13.5k
                pos += 3;
695
13.5k
                uint32_t utf2;
696
13.5k
                error = parse_codepoint(pos, &utf2);
697
13.5k
                if(error != CJ5_ERROR_NONE)
698
1.33k
                    goto done;
699
12.2k
                pos += 3;
700
                // High or low surrogate pair
701
12.2k
                utf = (utf <= 0xdbff) ?
702
5.40k
                    (utf << 10) + utf2 + SURROGATE_OFFSET :
703
12.2k
                    (utf2 << 10) + utf + SURROGATE_OFFSET;
704
12.2k
            }
705
706
            // Write the utf8 bytes of the code point
707
2.16M
            unsigned len = utf8_from_codepoint((unsigned char*)buf + outpos, utf);
708
2.16M
            if(len == 0) {
709
640
                error = CJ5_ERROR_INVALID; // Not a utf8 string
710
640
                goto done;
711
640
            }
712
2.16M
            outpos += len;
713
2.16M
            break;
714
2.16M
        }
715
18.8M
        }
716
18.8M
    }
717
718
1.55M
 done:
719
    // Always leave buf as a valid, NUL-terminated string, even when decoding
720
    // fails midway. Callers still must check the returned error code.
721
1.55M
    buf[outpos] = 0;
722
723
    // Set the output length
724
1.55M
    if(buflen)
725
1.55M
        *buflen = outpos;
726
1.55M
    return error;
727
1.55M
}
728
729
void
730
9.48k
cj5_skip(const cj5_result *r, unsigned int *tok_index) {
731
9.48k
    unsigned int idx = *tok_index;
732
9.48k
    unsigned int end = r->tokens[idx].end;
733
11.8k
    do { idx++; } while(idx < r->num_tokens &&
734
9.22k
                        r->tokens[idx].start < end);
735
9.48k
    *tok_index = idx;
736
9.48k
}
737
738
cj5_error_code
739
cj5_find(const cj5_result *r, unsigned int *tok_index,
740
0
         const char *key) {
741
    // It has to be an object
742
0
    unsigned int idx = *tok_index;
743
0
    if(r->tokens[idx].type != CJ5_TOKEN_OBJECT)
744
0
        return CJ5_ERROR_INVALID;
745
0
    unsigned int size = r->tokens[idx].size;
746
747
    // Skip to the first key
748
0
    idx++;
749
750
    // Size is number of keys + number of values
751
0
    for(unsigned int i = 0; i < size; i += 2) {
752
        // Key has to be a string
753
0
        if(r->tokens[idx].type != CJ5_TOKEN_STRING)
754
0
            return CJ5_ERROR_INVALID;
755
756
        // Return the index to the value if the key matches
757
0
        const char *keystart = &r->json5[r->tokens[idx].start];
758
0
        size_t keysize = r->tokens[idx].end - r->tokens[idx].start + 1;
759
0
        if(strncmp(key, keystart, keysize) == 0) {
760
0
            *tok_index = idx + 1;
761
0
            return CJ5_ERROR_NONE;
762
0
        }
763
764
        // Skip over the value
765
0
        idx++;
766
0
        cj5_skip(r, &idx);
767
0
    }
768
0
    return CJ5_ERROR_NOTFOUND;
769
0
}