cJSON.c 72.4 KB
Newer Older
K
Kevin Branigan 已提交
1
/*
M
Max Bruckner 已提交
2
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
K
Kevin Branigan 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

/* cJSON */
/* JSON parser in C. */

26 27 28 29 30
/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif

31
#ifdef __GNUC__
32
#pragma GCC visibility push(default)
33
#endif
34 35 36 37 38
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif
39

K
Kevin Branigan 已提交
40 41 42 43 44 45
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
46 47

#ifdef ENABLE_LOCALES
48
#include <locale.h>
49
#endif
50

51 52 53
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
54
#ifdef __GNUC__
55
#pragma GCC visibility pop
56
#endif
57

K
Kevin Branigan 已提交
58 59
#include "cJSON.h"

M
Max Bruckner 已提交
60
/* define our own boolean type */
61 62 63
#ifdef true
#undef true
#endif
64
#define true ((cJSON_bool)1)
65 66 67 68

#ifdef false
#undef false
#endif
69
#define false ((cJSON_bool)0)
M
Max Bruckner 已提交
70

71 72 73 74 75
typedef struct {
    const unsigned char *json;
    size_t position;
} error;
static error global_error = { NULL, 0 };
K
Kevin Branigan 已提交
76

77
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
M
Max Bruckner 已提交
78
{
79
    return (const char*) (global_error.json + global_error.position);
M
Max Bruckner 已提交
80
}
K
Kevin Branigan 已提交
81

M
Max Bruckner 已提交
82 83 84 85 86 87 88 89
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) {
    if (!cJSON_IsString(item)) {
        return NULL;
    }

    return item->valuestring;
}

90
/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
M
Max Bruckner 已提交
91
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 10)
92 93 94
    #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif

95
CJSON_PUBLIC(const char*) cJSON_Version(void)
96 97 98 99 100 101 102
{
    static char version[15];
    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

    return version;
}

103 104
/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
K
Kevin Branigan 已提交
105
{
106
    if ((string1 == NULL) || (string2 == NULL))
M
Max Bruckner 已提交
107
    {
108
        return 1;
M
Max Bruckner 已提交
109
    }
110

111
    if (string1 == string2)
M
Max Bruckner 已提交
112
    {
113
        return 0;
M
Max Bruckner 已提交
114
    }
115 116

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
117
    {
118
        if (*string1 == '\0')
M
Max Bruckner 已提交
119 120 121 122 123
        {
            return 0;
        }
    }

124
    return tolower(*string1) - tolower(*string2);
K
Kevin Branigan 已提交
125 126
}

127 128
typedef struct internal_hooks
{
129 130 131
    void *(CJSON_CDECL *allocate)(size_t size);
    void (CJSON_CDECL *deallocate)(void *pointer);
    void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
132 133
} internal_hooks;

M
Max Bruckner 已提交
134 135
#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dillimport '...' is not static */
136
static void * CJSON_CDECL internal_malloc(size_t size)
M
Max Bruckner 已提交
137 138 139
{
    return malloc(size);
}
140
static void CJSON_CDECL internal_free(void *pointer)
M
Max Bruckner 已提交
141 142 143
{
    free(pointer);
}
144
static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
M
Max Bruckner 已提交
145 146 147 148 149 150 151 152 153
{
    return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif

154 155 156
/* strlen of character literals resolved at compile time */
#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))

M
Max Bruckner 已提交
157
static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
K
Kevin Branigan 已提交
158

M
Max Bruckner 已提交
159
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
160
{
M
Max Bruckner 已提交
161
    size_t length = 0;
162
    unsigned char *copy = NULL;
K
Kevin Branigan 已提交
163

M
Max Bruckner 已提交
164
    if (string == NULL)
165 166 167 168
    {
        return NULL;
    }

M
Max Bruckner 已提交
169
    length = strlen((const char*)string) + sizeof("");
170 171
    copy = (unsigned char*)hooks->allocate(length);
    if (copy == NULL)
M
Max Bruckner 已提交
172
    {
173
        return NULL;
M
Max Bruckner 已提交
174
    }
M
Max Bruckner 已提交
175
    memcpy(copy, string, length);
M
Max Bruckner 已提交
176 177

    return copy;
K
Kevin Branigan 已提交
178 179
}

180
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
K
Kevin Branigan 已提交
181
{
M
Max Bruckner 已提交
182
    if (hooks == NULL)
M
Max Bruckner 已提交
183 184
    {
        /* Reset hooks */
185 186 187
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
K
Kevin Branigan 已提交
188 189 190
        return;
    }

191
    global_hooks.allocate = malloc;
M
Max Bruckner 已提交
192 193
    if (hooks->malloc_fn != NULL)
    {
194
        global_hooks.allocate = hooks->malloc_fn;
M
Max Bruckner 已提交
195 196
    }

197
    global_hooks.deallocate = free;
M
Max Bruckner 已提交
198 199
    if (hooks->free_fn != NULL)
    {
200
        global_hooks.deallocate = hooks->free_fn;
M
Max Bruckner 已提交
201 202 203
    }

    /* use realloc only if both free and malloc are used */
204 205
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
M
Max Bruckner 已提交
206
    {
207
        global_hooks.reallocate = realloc;
M
Max Bruckner 已提交
208
    }
K
Kevin Branigan 已提交
209 210 211
}

/* Internal constructor. */
212
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
K
Kevin Branigan 已提交
213
{
214
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
M
Max Bruckner 已提交
215 216
    if (node)
    {
217
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
218 219 220
    }

    return node;
K
Kevin Branigan 已提交
221 222 223
}

/* Delete a cJSON structure. */
M
Max Bruckner 已提交
224
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
K
Kevin Branigan 已提交
225
{
M
Max Bruckner 已提交
226
    cJSON *next = NULL;
M
Max Bruckner 已提交
227
    while (item != NULL)
M
Max Bruckner 已提交
228
    {
M
Max Bruckner 已提交
229 230
        next = item->next;
        if (!(item->type & cJSON_IsReference) && (item->child != NULL))
M
Max Bruckner 已提交
231
        {
M
Max Bruckner 已提交
232
            cJSON_Delete(item->child);
M
Max Bruckner 已提交
233
        }
M
Max Bruckner 已提交
234
        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
M
Max Bruckner 已提交
235
        {
M
Max Bruckner 已提交
236
            global_hooks.deallocate(item->valuestring);
M
Max Bruckner 已提交
237
        }
M
Max Bruckner 已提交
238
        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
M
Max Bruckner 已提交
239
        {
M
Max Bruckner 已提交
240
            global_hooks.deallocate(item->string);
M
Max Bruckner 已提交
241
        }
M
Max Bruckner 已提交
242 243
        global_hooks.deallocate(item);
        item = next;
M
Max Bruckner 已提交
244
    }
K
Kevin Branigan 已提交
245 246
}

247 248 249
/* get the decimal point character of the current locale */
static unsigned char get_decimal_point(void)
{
250
#ifdef ENABLE_LOCALES
251 252
    struct lconv *lconv = localeconv();
    return (unsigned char) lconv->decimal_point[0];
253
#else
254
    return '.';
255
#endif
256 257
}

M
Max Bruckner 已提交
258 259 260 261 262
typedef struct
{
    const unsigned char *content;
    size_t length;
    size_t offset;
263
    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
264
    internal_hooks hooks;
M
Max Bruckner 已提交
265 266 267 268 269 270 271 272 273 274
} parse_buffer;

/* check if the given size is left to read in a given parse buffer (starting with 1) */
#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
/* check if the buffer can be accessed at the given index (starting with 0) */
#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
/* get a pointer to the buffer at the position */
#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)

K
Kevin Branigan 已提交
275
/* Parse the input text to generate a number, and populate the result into item. */
276
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
277
{
278
    double number = 0;
279
    unsigned char *after_end = NULL;
280 281 282
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;
M
Max Bruckner 已提交
283

M
Max Bruckner 已提交
284
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
285
    {
286
        return false;
287 288
    }

289
    /* copy the number into a temporary buffer and replace '.' with the decimal point
M
Max Bruckner 已提交
290 291 292
     * of the current locale (for strtod)
     * This also takes care of '\0' not necessarily being available for marking the end of the input */
    for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
293
    {
M
Max Bruckner 已提交
294
        switch (buffer_at_offset(input_buffer)[i])
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '+':
            case '-':
            case 'e':
            case 'E':
M
Max Bruckner 已提交
310
                number_c_string[i] = buffer_at_offset(input_buffer)[i];
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                break;

            case '.':
                number_c_string[i] = decimal_point;
                break;

            default:
                goto loop_end;
        }
    }
loop_end:
    number_c_string[i] = '\0';

    number = strtod((const char*)number_c_string, (char**)&after_end);
    if (number_c_string == after_end)
M
Max Bruckner 已提交
326
    {
327
        return false; /* parse_error */
M
Max Bruckner 已提交
328 329
    }

330
    item->valuedouble = number;
M
Max Bruckner 已提交
331

332
    /* use saturation in case of overflow */
333
    if (number >= INT_MAX)
334 335 336
    {
        item->valueint = INT_MAX;
    }
337
    else if (number <= (double)INT_MIN)
338 339 340 341 342
    {
        item->valueint = INT_MIN;
    }
    else
    {
343
        item->valueint = (int)number;
344
    }
345

M
Max Bruckner 已提交
346 347
    item->type = cJSON_Number;

M
Max Bruckner 已提交
348
    input_buffer->offset += (size_t)(after_end - number_c_string);
349
    return true;
K
Kevin Branigan 已提交
350 351
}

352
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
353
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
354 355 356 357 358
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
359
    else if (number <= (double)INT_MIN)
360 361 362 363 364
    {
        object->valueint = INT_MIN;
    }
    else
    {
365
        object->valueint = (int)number;
366 367 368 369 370
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
371 372
typedef struct
{
373
    unsigned char *buffer;
374 375
    size_t length;
    size_t offset;
M
Max Bruckner 已提交
376
    size_t depth; /* current nesting depth (for formatted printing) */
377
    cJSON_bool noalloc;
M
Max Bruckner 已提交
378
    cJSON_bool format; /* is this print a formatted print */
379
    internal_hooks hooks;
M
Max Bruckner 已提交
380
} printbuffer;
381

M
Max Bruckner 已提交
382
/* realloc printbuffer if necessary to have at least "needed" bytes more */
383
static unsigned char* ensure(printbuffer * const p, size_t needed)
384
{
385
    unsigned char *newbuffer = NULL;
386 387
    size_t newsize = 0;

388
    if ((p == NULL) || (p->buffer == NULL))
389 390 391 392
    {
        return NULL;
    }

M
Max Bruckner 已提交
393 394 395 396 397 398
    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

399
    if (needed > INT_MAX)
M
Max Bruckner 已提交
400
    {
401
        /* sizes bigger than INT_MAX are currently not supported */
402
        return NULL;
M
Max Bruckner 已提交
403
    }
404

405
    needed += p->offset + 1;
M
Max Bruckner 已提交
406 407 408 409 410
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

411 412 413 414
    if (p->noalloc) {
        return NULL;
    }

415
    /* calculate new buffer size */
M
Max Bruckner 已提交
416
    if (needed > (INT_MAX / 2))
417 418 419 420 421 422 423 424 425 426 427
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
428 429 430 431
    else
    {
        newsize = needed * 2;
    }
432

433
    if (p->hooks.reallocate != NULL)
M
Max Bruckner 已提交
434
    {
M
Max Bruckner 已提交
435
        /* reallocate with realloc if available */
436
        newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
437 438 439 440 441 442 443 444
        if (newbuffer == NULL)
        {
            p->hooks.deallocate(p->buffer);
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
M
Max Bruckner 已提交
445
    }
M
Max Bruckner 已提交
446
    else
M
Max Bruckner 已提交
447
    {
M
Max Bruckner 已提交
448
        /* otherwise reallocate manually */
449
        newbuffer = (unsigned char*)p->hooks.allocate(newsize);
M
Max Bruckner 已提交
450 451
        if (!newbuffer)
        {
452
            p->hooks.deallocate(p->buffer);
M
Max Bruckner 已提交
453 454 455 456 457 458 459
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
460
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
461
        }
462
        p->hooks.deallocate(p->buffer);
M
Max Bruckner 已提交
463 464 465 466 467
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
468 469
}

470 471
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
472
{
473 474
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
475
    {
476
        return;
M
Max Bruckner 已提交
477
    }
478
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
479

480
    buffer->offset += strlen((const char*)buffer_pointer);
481 482 483
}

/* Render the number nicely from the given item into a string. */
484
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
485
{
M
Max Bruckner 已提交
486
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
487
    double d = item->valuedouble;
488
    int length = 0;
489
    size_t i = 0;
490
    unsigned char number_buffer[26]; /* temporary buffer to print the number into */
491
    unsigned char decimal_point = get_decimal_point();
492
    double test;
M
Max Bruckner 已提交
493

M
Max Bruckner 已提交
494
    if (output_buffer == NULL)
M
Max Bruckner 已提交
495
    {
496
        return false;
M
Max Bruckner 已提交
497
    }
M
Max Bruckner 已提交
498

499 500 501
    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
502
        length = sprintf((char*)number_buffer, "null");
503 504 505
    }
    else
    {
506 507 508 509 510 511 512 513 514
        /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
        length = sprintf((char*)number_buffer, "%1.15g", d);

        /* Check whether the original double can be recovered */
        if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d))
        {
            /* If not, print with 17 decimal places of precision */
            length = sprintf((char*)number_buffer, "%1.17g", d);
        }
M
Max Bruckner 已提交
515
    }
516

517 518
    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
519
    {
520
        return false;
521 522
    }

523
    /* reserve appropriate space in the output */
524
    output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
525 526 527
    if (output_pointer == NULL)
    {
        return false;
528 529
    }

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    /* copy the printed number to the output and replace locale
     * dependent decimal point with '.' */
    for (i = 0; i < ((size_t)length); i++)
    {
        if (number_buffer[i] == decimal_point)
        {
            output_pointer[i] = '.';
            continue;
        }

        output_pointer[i] = number_buffer[i];
    }
    output_pointer[i] = '\0';

    output_buffer->offset += (size_t)length;

546
    return true;
K
Kevin Branigan 已提交
547 548
}

M
Max Bruckner 已提交
549
/* parse 4 digit hexadecimal number */
550
static unsigned parse_hex4(const unsigned char * const input)
551
{
M
Max Bruckner 已提交
552
    unsigned int h = 0;
553
    size_t i = 0;
M
Max Bruckner 已提交
554

555
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
556
    {
557
        /* parse digit */
558
        if ((input[i] >= '0') && (input[i] <= '9'))
559
        {
560
            h += (unsigned int) input[i] - '0';
561
        }
562
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
563
        {
564
            h += (unsigned int) 10 + input[i] - 'A';
565
        }
566
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
567
        {
568
            h += (unsigned int) 10 + input[i] - 'a';
569 570 571 572 573
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
574

575 576 577 578 579
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
580 581 582
    }

    return h;
583 584
}

585 586
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
587
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
M
Max Bruckner 已提交
588
{
589 590 591
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
592
    unsigned char utf8_length = 0;
593
    unsigned char utf8_position = 0;
594
    unsigned char sequence_length = 0;
595
    unsigned char first_byte_mark = 0;
596 597 598 599 600 601

    if ((input_end - first_sequence) < 6)
    {
        /* input ends unexpectedly */
        goto fail;
    }
M
Max Bruckner 已提交
602

603 604 605
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

606
    /* check that the code is valid */
607
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
M
Max Bruckner 已提交
608
    {
609
        goto fail;
M
Max Bruckner 已提交
610
    }
M
Max Bruckner 已提交
611

612 613
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
614
    {
615 616 617 618 619
        const unsigned char *second_sequence = first_sequence + 6;
        unsigned int second_code = 0;
        sequence_length = 12; /* \uXXXX\uXXXX */

        if ((input_end - second_sequence) < 6)
M
Max Bruckner 已提交
620
        {
621 622
            /* input ends unexpectedly */
            goto fail;
M
Max Bruckner 已提交
623
        }
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

        if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
        {
            /* missing second half of the surrogate pair */
            goto fail;
        }

        /* get the second utf16 sequence */
        second_code = parse_hex4(second_sequence + 2);
        /* check that the code is valid */
        if ((second_code < 0xDC00) || (second_code > 0xDFFF))
        {
            /* invalid second half of the surrogate pair */
            goto fail;
        }


        /* calculate the unicode codepoint from the surrogate pair */
        codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
    }
    else
    {
        sequence_length = 6; /* \uXXXX */
        codepoint = first_code;
M
Max Bruckner 已提交
648
    }
M
Max Bruckner 已提交
649

650 651 652 653 654 655 656 657 658 659 660 661
    /* encode as UTF-8
     * takes at maximum 4 bytes to encode:
     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
    if (codepoint < 0x80)
    {
        /* normal ascii, encoding 0xxxxxxx */
        utf8_length = 1;
    }
    else if (codepoint < 0x800)
    {
        /* two bytes, encoding 110xxxxx 10xxxxxx */
        utf8_length = 2;
662
        first_byte_mark = 0xC0; /* 11000000 */
663 664 665 666 667
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
668
        first_byte_mark = 0xE0; /* 11100000 */
669 670 671 672 673
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
674
        first_byte_mark = 0xF0; /* 11110000 */
675 676
    }
    else
M
Max Bruckner 已提交
677
    {
678
        /* invalid unicode codepoint */
679
        goto fail;
M
Max Bruckner 已提交
680 681
    }

682
    /* encode as utf8 */
683 684 685 686 687
    for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
    {
        /* 10xxxxxx */
        (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
        codepoint >>= 6;
688
    }
689 690 691 692 693 694 695 696
    /* encode first byte */
    if (utf8_length > 1)
    {
        (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
    }
    else
    {
        (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
697
    }
698

699 700 701 702 703 704 705 706 707
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
708
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
709
{
M
Max Bruckner 已提交
710 711
    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
712 713 714 715
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
M
Max Bruckner 已提交
716
    if (buffer_at_offset(input_buffer)[0] != '\"')
717 718 719 720 721 722 723 724
    {
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
725
        while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
726 727 728 729
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
M
Max Bruckner 已提交
730
                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
731 732 733 734 735 736 737 738 739
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
740
        if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
741 742 743 744 745
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
M
Max Bruckner 已提交
746
        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
747
        output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
748 749 750 751 752 753 754
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
755
    /* loop through the string literal */
756
    while (input_pointer < input_end)
M
Max Bruckner 已提交
757
    {
758
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
759
        {
760
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
761 762 763 764
        }
        /* escape sequence */
        else
        {
765
            unsigned char sequence_length = 2;
M
Max Bruckner 已提交
766 767 768 769 770
            if ((input_end - input_pointer) < 1)
            {
                goto fail;
            }

771
            switch (input_pointer[1])
M
Max Bruckner 已提交
772 773
            {
                case 'b':
774
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
775 776
                    break;
                case 'f':
777
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
778 779
                    break;
                case 'n':
780
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
781 782
                    break;
                case 'r':
783
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
784 785
                    break;
                case 't':
786
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
787
                    break;
788 789 790
                case '\"':
                case '\\':
                case '/':
791
                    *output_pointer++ = input_pointer[1];
792
                    break;
793 794

                /* UTF-16 literal */
M
Max Bruckner 已提交
795
                case 'u':
796
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
797
                    if (sequence_length == 0)
M
Max Bruckner 已提交
798
                    {
799
                        /* failed to convert UTF16-literal to UTF-8 */
800
                        goto fail;
M
Max Bruckner 已提交
801 802
                    }
                    break;
803

M
Max Bruckner 已提交
804
                default:
805
                    goto fail;
M
Max Bruckner 已提交
806
            }
807
            input_pointer += sequence_length;
M
Max Bruckner 已提交
808 809
        }
    }
810 811 812

    /* zero terminate the output */
    *output_pointer = '\0';
M
Max Bruckner 已提交
813

814
    item->type = cJSON_String;
815
    item->valuestring = (char*)output;
816

M
Max Bruckner 已提交
817 818 819
    input_buffer->offset = (size_t) (input_end - input_buffer->content);
    input_buffer->offset++;

820
    return true;
821 822

fail:
823
    if (output != NULL)
824
    {
825
        input_buffer->hooks.deallocate(output);
826 827
    }

828 829 830 831 832
    if (input_pointer != NULL)
    {
        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
    }

833
    return false;
K
Kevin Branigan 已提交
834 835 836
}

/* Render the cstring provided to an escaped version that can be printed. */
837
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
838
{
839 840 841
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
842 843 844
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
845

846
    if (output_buffer == NULL)
M
Max Bruckner 已提交
847
    {
848
        return false;
M
Max Bruckner 已提交
849 850 851
    }

    /* empty string */
852
    if (input == NULL)
M
Max Bruckner 已提交
853
    {
854
        output = ensure(output_buffer, sizeof("\"\""));
855
        if (output == NULL)
M
Max Bruckner 已提交
856
        {
857
            return false;
M
Max Bruckner 已提交
858
        }
859
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
860

861
        return true;
M
Max Bruckner 已提交
862 863 864
    }

    /* set "flag" to 1 if something needs to be escaped */
865
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
866
    {
M
Max Bruckner 已提交
867
        switch (*input_pointer)
M
Max Bruckner 已提交
868
        {
M
Max Bruckner 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
            case '\"':
            case '\\':
            case '\b':
            case '\f':
            case '\n':
            case '\r':
            case '\t':
                /* one character escape sequence */
                escape_characters++;
                break;
            default:
                if (*input_pointer < 32)
                {
                    /* UTF-16 escape sequence uXXXX */
                    escape_characters += 5;
                }
                break;
M
Max Bruckner 已提交
886 887
        }
    }
M
Max Bruckner 已提交
888
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
889

890
    output = ensure(output_buffer, output_length + sizeof("\"\""));
891
    if (output == NULL)
M
Max Bruckner 已提交
892
    {
893
        return false;
M
Max Bruckner 已提交
894 895
    }

M
Max Bruckner 已提交
896 897
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
898
    {
M
Max Bruckner 已提交
899 900 901 902 903
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

904
        return true;
M
Max Bruckner 已提交
905 906
    }

M
Max Bruckner 已提交
907 908
    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
909
    /* copy the string */
M
Max Bruckner 已提交
910
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
911
    {
912
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
913 914
        {
            /* normal character, copy */
M
Max Bruckner 已提交
915
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
916 917 918 919
        }
        else
        {
            /* character needs to be escaped */
920
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
921
            switch (*input_pointer)
M
Max Bruckner 已提交
922 923
            {
                case '\\':
M
Max Bruckner 已提交
924
                    *output_pointer = '\\';
M
Max Bruckner 已提交
925 926
                    break;
                case '\"':
M
Max Bruckner 已提交
927
                    *output_pointer = '\"';
M
Max Bruckner 已提交
928 929
                    break;
                case '\b':
M
Max Bruckner 已提交
930
                    *output_pointer = 'b';
M
Max Bruckner 已提交
931 932
                    break;
                case '\f':
M
Max Bruckner 已提交
933
                    *output_pointer = 'f';
M
Max Bruckner 已提交
934 935
                    break;
                case '\n':
M
Max Bruckner 已提交
936
                    *output_pointer = 'n';
M
Max Bruckner 已提交
937 938
                    break;
                case '\r':
M
Max Bruckner 已提交
939
                    *output_pointer = 'r';
M
Max Bruckner 已提交
940 941
                    break;
                case '\t':
M
Max Bruckner 已提交
942
                    *output_pointer = 't';
M
Max Bruckner 已提交
943 944 945
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
946 947
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
948 949 950 951
                    break;
            }
        }
    }
M
Max Bruckner 已提交
952 953
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
954

955
    return true;
K
Kevin Branigan 已提交
956
}
M
Max Bruckner 已提交
957

M
Max Bruckner 已提交
958
/* Invoke print_string_ptr (which is useful) on an item. */
959
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
M
Max Bruckner 已提交
960
{
961
    return print_string_ptr((unsigned char*)item->valuestring, p);
M
Max Bruckner 已提交
962
}
K
Kevin Branigan 已提交
963 964

/* Predeclare these prototypes. */
965 966 967 968 969 970
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
K
Kevin Branigan 已提交
971 972

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
973
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
M
Max Bruckner 已提交
974
{
M
Max Bruckner 已提交
975 976 977 978 979
    if ((buffer == NULL) || (buffer->content == NULL))
    {
        return NULL;
    }

M
Max Bruckner 已提交
980 981 982 983 984 985
    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
    {
       buffer->offset++;
    }

    if (buffer->offset == buffer->length)
M
Max Bruckner 已提交
986
    {
M
Max Bruckner 已提交
987
        buffer->offset--;
M
Max Bruckner 已提交
988 989
    }

M
Max Bruckner 已提交
990
    return buffer;
M
Max Bruckner 已提交
991
}
K
Kevin Branigan 已提交
992

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
{
    if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
    {
        return NULL;
    }

    if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
    {
        buffer->offset += 3;
    }

    return buffer;
}

K
Kevin Branigan 已提交
1009
/* Parse an object - create a new root, and populate. */
1010
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
1011
{
1012
    parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
1013
    cJSON *item = NULL;
1014 1015 1016 1017

    /* reset error position */
    global_error.json = NULL;
    global_error.position = 0;
1018 1019

    if (value == NULL)
M
Max Bruckner 已提交
1020
    {
1021
        goto fail;
M
Max Bruckner 已提交
1022 1023
    }

M
Max Bruckner 已提交
1024 1025 1026
    buffer.content = (const unsigned char*)value;
    buffer.length = strlen((const char*)value) + sizeof("");
    buffer.offset = 0;
1027
    buffer.hooks = global_hooks;
M
Max Bruckner 已提交
1028

1029 1030 1031 1032
    item = cJSON_New_Item(&global_hooks);
    if (item == NULL) /* memory fail */
    {
        goto fail;
M
Max Bruckner 已提交
1033 1034
    }

1035
    if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
M
Max Bruckner 已提交
1036 1037
    {
        /* parse failure. ep is set. */
1038
        goto fail;
M
Max Bruckner 已提交
1039 1040 1041 1042 1043
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
1044 1045
        buffer_skip_whitespace(&buffer);
        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
M
Max Bruckner 已提交
1046
        {
1047
            goto fail;
M
Max Bruckner 已提交
1048 1049 1050 1051
        }
    }
    if (return_parse_end)
    {
1052
        *return_parse_end = (const char*)buffer_at_offset(&buffer);
M
Max Bruckner 已提交
1053 1054
    }

1055
    return item;
1056 1057 1058 1059 1060 1061 1062

fail:
    if (item != NULL)
    {
        cJSON_Delete(item);
    }

1063 1064
    if (value != NULL)
    {
1065 1066 1067 1068
        error local_error;
        local_error.json = (const unsigned char*)value;
        local_error.position = 0;

1069 1070
        if (buffer.offset < buffer.length)
        {
1071
            local_error.position = buffer.offset;
1072 1073 1074
        }
        else if (buffer.length > 0)
        {
1075 1076 1077 1078 1079 1080 1081
            local_error.position = buffer.length - 1;
        }

        if (return_parse_end != NULL)
        {
            *return_parse_end = (const char*)local_error.json + local_error.position;
        }
Y
yangfl 已提交
1082

1083
        global_error = local_error;
M
Max Bruckner 已提交
1084 1085
    }

1086
    return NULL;
K
Kevin Branigan 已提交
1087
}
M
Max Bruckner 已提交
1088

1089
/* Default options for cJSON_Parse */
1090
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
1091 1092 1093
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
1094

1095
#define cjson_min(a, b) ((a < b) ? a : b)
M
Max Bruckner 已提交
1096

1097
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1098
{
1099
    static const size_t default_buffer_size = 256;
M
Max Bruckner 已提交
1100 1101 1102 1103 1104 1105
    printbuffer buffer[1];
    unsigned char *printed = NULL;

    memset(buffer, 0, sizeof(buffer));

    /* create buffer */
1106 1107
    buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
    buffer->length = default_buffer_size;
M
Max Bruckner 已提交
1108
    buffer->format = format;
1109
    buffer->hooks = *hooks;
M
Max Bruckner 已提交
1110 1111 1112 1113 1114 1115
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
1116
    if (!print_value(item, buffer))
M
Max Bruckner 已提交
1117 1118 1119
    {
        goto fail;
    }
1120
    update_offset(buffer);
M
Max Bruckner 已提交
1121

1122 1123
    /* check if reallocate is available */
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
1124
    {
1125
        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
1126 1127 1128
        if (printed == NULL) {
            goto fail;
        }
1129
        buffer->buffer = NULL;
M
Max Bruckner 已提交
1130
    }
1131 1132 1133 1134 1135 1136 1137
    else /* otherwise copy the JSON over to a new buffer */
    {
        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
        if (printed == NULL)
        {
            goto fail;
        }
1138
        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
1139
        printed[buffer->offset] = '\0'; /* just to be sure */
M
Max Bruckner 已提交
1140

1141 1142 1143
        /* free the buffer */
        hooks->deallocate(buffer->buffer);
    }
M
Max Bruckner 已提交
1144 1145 1146 1147 1148 1149

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
1150
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
1151 1152 1153 1154
    }

    if (printed != NULL)
    {
1155
        hooks->deallocate(printed);
M
Max Bruckner 已提交
1156 1157 1158 1159 1160
    }

    return NULL;
}

K
Kevin Branigan 已提交
1161
/* Render a cJSON item/entity/structure to text. */
1162
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
1163
{
1164
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
1165 1166
}

1167
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
1168
{
1169
    return (char*)print(item, false, &global_hooks);
1170
}
1171

1172
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
1173
{
1174
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
M
Max Bruckner 已提交
1175 1176 1177

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
1178
        return NULL;
M
Max Bruckner 已提交
1179 1180
    }

1181
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
1182 1183
    if (!p.buffer)
    {
1184
        return NULL;
1185
    }
M
Max Bruckner 已提交
1186 1187

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
1188
    p.offset = 0;
1189
    p.noalloc = false;
M
Max Bruckner 已提交
1190
    p.format = fmt;
1191
    p.hooks = global_hooks;
M
Max Bruckner 已提交
1192

1193
    if (!print_value(item, &p))
1194
    {
1195
        global_hooks.deallocate(p.buffer);
1196 1197 1198 1199
        return NULL;
    }

    return (char*)p.buffer;
1200 1201
}

1202
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
1203
{
1204
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
M
Max Bruckner 已提交
1205

1206
    if ((len < 0) || (buf == NULL))
M
Max Bruckner 已提交
1207 1208 1209 1210
    {
        return false;
    }

1211
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
1212
    p.length = (size_t)len;
1213
    p.offset = 0;
1214
    p.noalloc = true;
M
Max Bruckner 已提交
1215
    p.format = fmt;
1216
    p.hooks = global_hooks;
M
Max Bruckner 已提交
1217

1218
    return print_value(item, &p);
1219
}
K
Kevin Branigan 已提交
1220 1221

/* Parser core - when encountering text, process appropriately. */
1222
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1223
{
M
Max Bruckner 已提交
1224
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
M
Max Bruckner 已提交
1225
    {
1226
        return false; /* no input */
M
Max Bruckner 已提交
1227 1228 1229
    }

    /* parse the different types of values */
1230
    /* null */
M
Max Bruckner 已提交
1231
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
M
Max Bruckner 已提交
1232 1233
    {
        item->type = cJSON_NULL;
M
Max Bruckner 已提交
1234
        input_buffer->offset += 4;
1235
        return true;
M
Max Bruckner 已提交
1236
    }
1237
    /* false */
M
Max Bruckner 已提交
1238
    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
M
Max Bruckner 已提交
1239 1240
    {
        item->type = cJSON_False;
M
Max Bruckner 已提交
1241
        input_buffer->offset += 5;
1242
        return true;
M
Max Bruckner 已提交
1243
    }
1244
    /* true */
M
Max Bruckner 已提交
1245
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
M
Max Bruckner 已提交
1246 1247 1248
    {
        item->type = cJSON_True;
        item->valueint = 1;
M
Max Bruckner 已提交
1249
        input_buffer->offset += 4;
1250
        return true;
M
Max Bruckner 已提交
1251
    }
1252
    /* string */
M
Max Bruckner 已提交
1253
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
M
Max Bruckner 已提交
1254
    {
1255
        return parse_string(item, input_buffer);
M
Max Bruckner 已提交
1256
    }
1257
    /* number */
M
Max Bruckner 已提交
1258
    if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
M
Max Bruckner 已提交
1259
    {
M
Max Bruckner 已提交
1260
        return parse_number(item, input_buffer);
M
Max Bruckner 已提交
1261
    }
1262
    /* array */
M
Max Bruckner 已提交
1263
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
M
Max Bruckner 已提交
1264
    {
1265
        return parse_array(item, input_buffer);
M
Max Bruckner 已提交
1266
    }
1267
    /* object */
M
Max Bruckner 已提交
1268
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
M
Max Bruckner 已提交
1269
    {
1270
        return parse_object(item, input_buffer);
M
Max Bruckner 已提交
1271 1272
    }

1273
    return false;
K
Kevin Branigan 已提交
1274 1275 1276
}

/* Render a value to text. */
1277
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
1278
{
M
Max Bruckner 已提交
1279
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1280

M
Max Bruckner 已提交
1281
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1282
    {
1283
        return false;
M
Max Bruckner 已提交
1284
    }
M
Max Bruckner 已提交
1285 1286

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1287
    {
M
Max Bruckner 已提交
1288
        case cJSON_NULL:
1289
            output = ensure(output_buffer, 5);
1290
            if (output == NULL)
M
Max Bruckner 已提交
1291
            {
1292
                return false;
M
Max Bruckner 已提交
1293
            }
1294 1295 1296
            strcpy((char*)output, "null");
            return true;

M
Max Bruckner 已提交
1297
        case cJSON_False:
1298
            output = ensure(output_buffer, 6);
1299
            if (output == NULL)
M
Max Bruckner 已提交
1300
            {
1301
                return false;
M
Max Bruckner 已提交
1302
            }
1303 1304 1305
            strcpy((char*)output, "false");
            return true;

M
Max Bruckner 已提交
1306
        case cJSON_True:
1307
            output = ensure(output_buffer, 5);
1308
            if (output == NULL)
M
Max Bruckner 已提交
1309
            {
1310
                return false;
M
Max Bruckner 已提交
1311
            }
1312 1313 1314
            strcpy((char*)output, "true");
            return true;

M
Max Bruckner 已提交
1315
        case cJSON_Number:
1316
            return print_number(item, output_buffer);
1317

M
Max Bruckner 已提交
1318
        case cJSON_Raw:
M
Max Bruckner 已提交
1319
        {
M
Max Bruckner 已提交
1320 1321
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1322
            {
1323
                return false;
M
Max Bruckner 已提交
1324
            }
1325

1326
            raw_length = strlen(item->valuestring) + sizeof("");
1327
            output = ensure(output_buffer, raw_length);
1328
            if (output == NULL)
M
Max Bruckner 已提交
1329
            {
1330
                return false;
1331
            }
1332 1333
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1334
        }
1335

M
Max Bruckner 已提交
1336
        case cJSON_String:
1337
            return print_string(item, output_buffer);
1338

M
Max Bruckner 已提交
1339
        case cJSON_Array:
1340
            return print_array(item, output_buffer);
1341

M
Max Bruckner 已提交
1342
        case cJSON_Object:
1343
            return print_object(item, output_buffer);
1344

M
Max Bruckner 已提交
1345
        default:
1346
            return false;
M
Max Bruckner 已提交
1347
    }
K
Kevin Branigan 已提交
1348 1349 1350
}

/* Build an array from input text. */
1351
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1352
{
1353
    cJSON *head = NULL; /* head of the linked list */
1354 1355
    cJSON *current_item = NULL;

1356 1357 1358 1359 1360 1361
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1362
    if (buffer_at_offset(input_buffer)[0] != '[')
M
Max Bruckner 已提交
1363
    {
1364
        /* not an array */
1365
        goto fail;
M
Max Bruckner 已提交
1366
    }
K
Kevin Branigan 已提交
1367

M
Max Bruckner 已提交
1368 1369 1370
    input_buffer->offset++;
    buffer_skip_whitespace(input_buffer);
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
M
Max Bruckner 已提交
1371
    {
1372
        /* empty array */
1373
        goto success;
M
Max Bruckner 已提交
1374
    }
K
Kevin Branigan 已提交
1375

M
Max Bruckner 已提交
1376 1377 1378 1379 1380 1381 1382
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1383
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1384
    input_buffer->offset--;
M
Max Bruckner 已提交
1385
    /* loop through the comma separated array elements */
1386
    do
M
Max Bruckner 已提交
1387
    {
1388
        /* allocate next item */
1389
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
1390
        if (new_item == NULL)
M
Max Bruckner 已提交
1391
        {
1392
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1393
        }
1394 1395 1396

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1397
        {
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
        }

        /* parse next value */
M
Max Bruckner 已提交
1410 1411
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1412
        if (!parse_value(current_item, input_buffer))
1413 1414
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1415
        }
M
Max Bruckner 已提交
1416
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1417
    }
M
Max Bruckner 已提交
1418
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
M
Max Bruckner 已提交
1419

M
Max Bruckner 已提交
1420
    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
M
Max Bruckner 已提交
1421
    {
1422
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1423 1424
    }

1425
success:
1426 1427
    input_buffer->depth--;

1428
    item->type = cJSON_Array;
1429
    item->child = head;
1430

M
Max Bruckner 已提交
1431 1432
    input_buffer->offset++;

1433
    return true;
K
Kevin Branigan 已提交
1434

1435
fail:
1436
    if (head != NULL)
1437
    {
1438
        cJSON_Delete(head);
1439 1440
    }

1441
    return false;
K
Kevin Branigan 已提交
1442 1443 1444
}

/* Render an array to text */
1445
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
1446
{
M
Max Bruckner 已提交
1447
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1448
    size_t length = 0;
M
Max Bruckner 已提交
1449
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1450

M
Max Bruckner 已提交
1451
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1452
    {
1453
        return false;
M
Max Bruckner 已提交
1454 1455
    }

M
Max Bruckner 已提交
1456 1457
    /* Compose the output array. */
    /* opening square bracket */
1458
    output_pointer = ensure(output_buffer, 1);
M
Max Bruckner 已提交
1459
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1460
    {
1461
        return false;
M
Max Bruckner 已提交
1462 1463
    }

M
Max Bruckner 已提交
1464 1465
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1466
    output_buffer->depth++;
M
Max Bruckner 已提交
1467

M
Max Bruckner 已提交
1468
    while (current_element != NULL)
M
Max Bruckner 已提交
1469
    {
1470
        if (!print_value(current_element, output_buffer))
M
Max Bruckner 已提交
1471
        {
1472
            return false;
M
Max Bruckner 已提交
1473
        }
1474
        update_offset(output_buffer);
M
Max Bruckner 已提交
1475
        if (current_element->next)
M
Max Bruckner 已提交
1476
        {
M
Max Bruckner 已提交
1477
            length = (size_t) (output_buffer->format ? 2 : 1);
1478
            output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1479
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1480
            {
1481
                return false;
M
Max Bruckner 已提交
1482
            }
M
Max Bruckner 已提交
1483
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1484
            if(output_buffer->format)
M
Max Bruckner 已提交
1485
            {
M
Max Bruckner 已提交
1486
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1487
            }
M
Max Bruckner 已提交
1488 1489
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1490
        }
M
Max Bruckner 已提交
1491
        current_element = current_element->next;
M
Max Bruckner 已提交
1492 1493
    }

1494
    output_pointer = ensure(output_buffer, 2);
M
Max Bruckner 已提交
1495
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1496
    {
1497
        return false;
M
Max Bruckner 已提交
1498
    }
M
Max Bruckner 已提交
1499 1500
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1501
    output_buffer->depth--;
M
Max Bruckner 已提交
1502

1503
    return true;
K
Kevin Branigan 已提交
1504 1505 1506
}

/* Build an object from the text. */
1507
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1508
{
1509
    cJSON *head = NULL; /* linked list head */
1510 1511
    cJSON *current_item = NULL;

1512 1513 1514 1515 1516 1517
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1518
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
M
Max Bruckner 已提交
1519
    {
1520
        goto fail; /* not an object */
M
Max Bruckner 已提交
1521 1522
    }

M
Max Bruckner 已提交
1523 1524 1525
    input_buffer->offset++;
    buffer_skip_whitespace(input_buffer);
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
M
Max Bruckner 已提交
1526
    {
1527
        goto success; /* empty object */
M
Max Bruckner 已提交
1528 1529
    }

M
Max Bruckner 已提交
1530 1531 1532 1533 1534 1535 1536
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1537
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1538
    input_buffer->offset--;
1539 1540
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1541
    {
1542
        /* allocate next item */
1543
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
1544 1545 1546 1547
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1548

1549 1550
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1551
        {
1552 1553 1554 1555 1556 1557 1558 1559 1560
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
M
Max Bruckner 已提交
1561 1562
        }

1563
        /* parse the name of the child */
M
Max Bruckner 已提交
1564 1565
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1566
        if (!parse_string(current_item, input_buffer))
M
Max Bruckner 已提交
1567
        {
1568
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1569
        }
M
Max Bruckner 已提交
1570
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1571

1572 1573 1574
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1575

M
Max Bruckner 已提交
1576
        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
M
Max Bruckner 已提交
1577
        {
1578
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1579
        }
1580 1581

        /* parse the value */
M
Max Bruckner 已提交
1582 1583
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1584
        if (!parse_value(current_item, input_buffer))
M
Max Bruckner 已提交
1585
        {
1586
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1587
        }
M
Max Bruckner 已提交
1588
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1589
    }
M
Max Bruckner 已提交
1590
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
1591

M
Max Bruckner 已提交
1592
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
M
Max Bruckner 已提交
1593
    {
1594
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1595 1596
    }

1597
success:
1598 1599
    input_buffer->depth--;

1600
    item->type = cJSON_Object;
1601
    item->child = head;
1602

M
Max Bruckner 已提交
1603
    input_buffer->offset++;
1604
    return true;
1605 1606

fail:
1607
    if (head != NULL)
1608
    {
1609
        cJSON_Delete(head);
1610 1611
    }

1612
    return false;
K
Kevin Branigan 已提交
1613 1614 1615
}

/* Render an object to text. */
1616
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
1617
{
M
Max Bruckner 已提交
1618
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1619
    size_t length = 0;
M
Max Bruckner 已提交
1620
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1621

M
Max Bruckner 已提交
1622
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1623
    {
1624
        return false;
M
Max Bruckner 已提交
1625 1626
    }

M
Max Bruckner 已提交
1627
    /* Compose the output: */
M
Max Bruckner 已提交
1628
    length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
1629
    output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1630
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1631
    {
1632
        return false;
M
Max Bruckner 已提交
1633 1634
    }

M
Max Bruckner 已提交
1635
    *output_pointer++ = '{';
M
Max Bruckner 已提交
1636
    output_buffer->depth++;
M
Max Bruckner 已提交
1637
    if (output_buffer->format)
M
Max Bruckner 已提交
1638
    {
M
Max Bruckner 已提交
1639
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1640
    }
M
Max Bruckner 已提交
1641
    output_buffer->offset += length;
M
Max Bruckner 已提交
1642

M
Max Bruckner 已提交
1643
    while (current_item)
M
Max Bruckner 已提交
1644
    {
M
Max Bruckner 已提交
1645
        if (output_buffer->format)
M
Max Bruckner 已提交
1646
        {
M
Max Bruckner 已提交
1647
            size_t i;
1648
            output_pointer = ensure(output_buffer, output_buffer->depth);
M
Max Bruckner 已提交
1649
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1650
            {
1651
                return false;
M
Max Bruckner 已提交
1652
            }
M
Max Bruckner 已提交
1653
            for (i = 0; i < output_buffer->depth; i++)
M
Max Bruckner 已提交
1654
            {
M
Max Bruckner 已提交
1655
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1656
            }
M
Max Bruckner 已提交
1657
            output_buffer->offset += output_buffer->depth;
M
Max Bruckner 已提交
1658 1659
        }

M
Max Bruckner 已提交
1660
        /* print key */
1661
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
M
Max Bruckner 已提交
1662
        {
1663
            return false;
M
Max Bruckner 已提交
1664
        }
M
Max Bruckner 已提交
1665
        update_offset(output_buffer);
M
Max Bruckner 已提交
1666

M
Max Bruckner 已提交
1667
        length = (size_t) (output_buffer->format ? 2 : 1);
1668
        output_pointer = ensure(output_buffer, length);
M
Max Bruckner 已提交
1669
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1670
        {
1671
            return false;
M
Max Bruckner 已提交
1672
        }
M
Max Bruckner 已提交
1673
        *output_pointer++ = ':';
M
Max Bruckner 已提交
1674
        if (output_buffer->format)
M
Max Bruckner 已提交
1675
        {
M
Max Bruckner 已提交
1676
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1677
        }
M
Max Bruckner 已提交
1678
        output_buffer->offset += length;
M
Max Bruckner 已提交
1679

M
Max Bruckner 已提交
1680
        /* print value */
1681
        if (!print_value(current_item, output_buffer))
M
Max Bruckner 已提交
1682
        {
1683
            return false;
M
Max Bruckner 已提交
1684
        }
M
Max Bruckner 已提交
1685
        update_offset(output_buffer);
M
Max Bruckner 已提交
1686

M
Max Bruckner 已提交
1687
        /* print comma if not last */
1688
        length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
1689
        output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1690
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1691
        {
1692
            return false;
M
Max Bruckner 已提交
1693
        }
M
Max Bruckner 已提交
1694
        if (current_item->next)
M
Max Bruckner 已提交
1695
        {
M
Max Bruckner 已提交
1696
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1697 1698
        }

M
Max Bruckner 已提交
1699
        if (output_buffer->format)
M
Max Bruckner 已提交
1700
        {
M
Max Bruckner 已提交
1701
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1702
        }
M
Max Bruckner 已提交
1703 1704
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1705

M
Max Bruckner 已提交
1706
        current_item = current_item->next;
M
Max Bruckner 已提交
1707
    }
M
Max Bruckner 已提交
1708

1709
    output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
M
Max Bruckner 已提交
1710
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1711
    {
1712
        return false;
M
Max Bruckner 已提交
1713
    }
M
Max Bruckner 已提交
1714
    if (output_buffer->format)
M
Max Bruckner 已提交
1715
    {
M
Max Bruckner 已提交
1716
        size_t i;
M
Max Bruckner 已提交
1717
        for (i = 0; i < (output_buffer->depth - 1); i++)
M
Max Bruckner 已提交
1718
        {
M
Max Bruckner 已提交
1719
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1720 1721
        }
    }
M
Max Bruckner 已提交
1722 1723
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1724
    output_buffer->depth--;
M
Max Bruckner 已提交
1725

1726
    return true;
K
Kevin Branigan 已提交
1727 1728 1729
}

/* Get Array size/item / object item. */
1730
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1731
{
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    cJSON *child = NULL;
    size_t size = 0;

    if (array == NULL)
    {
        return 0;
    }

    child = array->child;

    while(child != NULL)
M
Max Bruckner 已提交
1743
    {
1744 1745
        size++;
        child = child->next;
M
Max Bruckner 已提交
1746
    }
1747 1748 1749

    /* FIXME: Can overflow here. Cannot be fixed without breaking the API */

1750
    return (int)size;
M
Max Bruckner 已提交
1751 1752
}

M
Max Bruckner 已提交
1753
static cJSON* get_array_item(const cJSON *array, size_t index)
M
Max Bruckner 已提交
1754
{
M
Max Bruckner 已提交
1755 1756 1757
    cJSON *current_child = NULL;

    if (array == NULL)
M
Max Bruckner 已提交
1758
    {
M
Max Bruckner 已提交
1759
        return NULL;
M
Max Bruckner 已提交
1760 1761
    }

M
Max Bruckner 已提交
1762 1763 1764 1765 1766 1767 1768 1769
    current_child = array->child;
    while ((current_child != NULL) && (index > 0))
    {
        index--;
        current_child = current_child->next;
    }

    return current_child;
M
Max Bruckner 已提交
1770 1771
}

M
Max Bruckner 已提交
1772
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
M
Max Bruckner 已提交
1773
{
M
Max Bruckner 已提交
1774
    if (index < 0)
M
Max Bruckner 已提交
1775
    {
M
Max Bruckner 已提交
1776
        return NULL;
M
Max Bruckner 已提交
1777
    }
M
Max Bruckner 已提交
1778

M
Max Bruckner 已提交
1779
    return get_array_item(array, (size_t)index);
M
Max Bruckner 已提交
1780 1781
}

1782
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
1783 1784 1785
{
    cJSON *current_element = NULL;

1786
    if ((object == NULL) || (name == NULL))
1787 1788 1789 1790 1791
    {
        return NULL;
    }

    current_element = object->child;
1792
    if (case_sensitive)
1793
    {
1794
        while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
        {
            current_element = current_element->next;
        }
    }
    else
    {
        while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
        {
            current_element = current_element->next;
        }
1805 1806
    }

1807 1808 1809 1810
    if ((current_element == NULL) || (current_element->string == NULL)) {
        return NULL;
    }

1811 1812 1813
    return current_element;
}

1814
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
1815 1816 1817 1818 1819 1820 1821 1822 1823
{
    return get_object_item(object, string, false);
}

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
{
    return get_object_item(object, string, true);
}

1824
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1825 1826 1827
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1828 1829

/* Utility for array list handling. */
M
Max Bruckner 已提交
1830 1831 1832 1833 1834 1835
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1836
/* Utility for handling references. */
1837
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1838
{
1839 1840
    cJSON *reference = NULL;
    if (item == NULL)
M
Max Bruckner 已提交
1841
    {
1842
        return NULL;
M
Max Bruckner 已提交
1843
    }
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855

    reference = cJSON_New_Item(hooks);
    if (reference == NULL)
    {
        return NULL;
    }

    memcpy(reference, item, sizeof(cJSON));
    reference->string = NULL;
    reference->type |= cJSON_IsReference;
    reference->next = reference->prev = NULL;
    return reference;
M
Max Bruckner 已提交
1856
}
K
Kevin Branigan 已提交
1857

1858
static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1859
{
1860 1861 1862
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1863
    {
1864
        return false;
M
Max Bruckner 已提交
1865
    }
1866 1867 1868 1869

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1870 1871 1872 1873 1874 1875 1876
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1877
        while (child->next)
M
Max Bruckner 已提交
1878
        {
1879
            child = child->next;
M
Max Bruckner 已提交
1880
        }
1881
        suffix_object(child, item);
M
Max Bruckner 已提交
1882
    }
1883 1884 1885 1886 1887 1888 1889 1890

    return true;
}

/* Add item to array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
{
    add_item_to_array(array, item);
M
Max Bruckner 已提交
1891 1892
}

1893
#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
1894 1895
    #pragma GCC diagnostic push
#endif
1896
#ifdef __GNUC__
1897
#pragma GCC diagnostic ignored "-Wcast-qual"
1898
#endif
1899
/* helper function to cast away const */
1900
static void* cast_away_const(const void* string)
1901
{
1902
    return (void*)string;
1903 1904 1905 1906
}
#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1907

1908 1909

static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
1910
{
1911 1912 1913
    char *new_key = NULL;
    int new_type = cJSON_Invalid;

1914
    if ((object == NULL) || (string == NULL) || (item == NULL))
1915
    {
1916
        return false;
1917
    }
1918 1919

    if (constant_key)
1920
    {
1921 1922
        new_key = (char*)cast_away_const(string);
        new_type = item->type | cJSON_StringIsConst;
1923
    }
1924 1925
    else
    {
1926 1927
        new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
        if (new_key == NULL)
1928 1929 1930 1931
        {
            return false;
        }

1932
        new_type = item->type & ~cJSON_StringIsConst;
1933 1934
    }

1935 1936 1937 1938 1939 1940 1941 1942
    if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
    {
        hooks->deallocate(item->string);
    }

    item->string = new_key;
    item->type = new_type;

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    return add_item_to_array(object, item);
}

CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
    add_item_to_object(object, string, item, &global_hooks, false);
}

/* Add an item to an object with constant string as key */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
{
    add_item_to_object(object, string, item, &global_hooks, true);
1955 1956
}

1957
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1958
{
1959 1960 1961 1962 1963
    if (array == NULL)
    {
        return;
    }

1964
    add_item_to_array(array, create_reference(item, &global_hooks));
1965 1966
}

1967
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1968
{
1969 1970 1971 1972 1973
    if ((object == NULL) || (string == NULL))
    {
        return;
    }

1974
    add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
1975 1976
}

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
{
    cJSON *null = cJSON_CreateNull();
    if (add_item_to_object(object, name, null, &global_hooks, false))
    {
        return null;
    }

    cJSON_Delete(null);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
{
    cJSON *true_item = cJSON_CreateTrue();
    if (add_item_to_object(object, name, true_item, &global_hooks, false))
    {
        return true_item;
    }

    cJSON_Delete(true_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
{
    cJSON *false_item = cJSON_CreateFalse();
    if (add_item_to_object(object, name, false_item, &global_hooks, false))
    {
        return false_item;
    }

    cJSON_Delete(false_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
{
    cJSON *bool_item = cJSON_CreateBool(boolean);
    if (add_item_to_object(object, name, bool_item, &global_hooks, false))
    {
        return bool_item;
    }

    cJSON_Delete(bool_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
{
    cJSON *number_item = cJSON_CreateNumber(number);
    if (add_item_to_object(object, name, number_item, &global_hooks, false))
    {
        return number_item;
    }

    cJSON_Delete(number_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
{
    cJSON *string_item = cJSON_CreateString(string);
    if (add_item_to_object(object, name, string_item, &global_hooks, false))
    {
        return string_item;
    }

    cJSON_Delete(string_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
{
    cJSON *raw_item = cJSON_CreateRaw(raw);
    if (add_item_to_object(object, name, raw_item, &global_hooks, false))
    {
        return raw_item;
    }

    cJSON_Delete(raw_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
{
    cJSON *object_item = cJSON_CreateObject();
    if (add_item_to_object(object, name, object_item, &global_hooks, false))
    {
        return object_item;
    }

    cJSON_Delete(object_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
{
    cJSON *array = cJSON_CreateArray();
    if (add_item_to_object(object, name, array, &global_hooks, false))
    {
        return array;
    }

    cJSON_Delete(array);
    return NULL;
}

M
Max Bruckner 已提交
2085
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
2086
{
M
Max Bruckner 已提交
2087
    if ((parent == NULL) || (item == NULL))
2088
    {
2089
        return NULL;
2090
    }
M
Max Bruckner 已提交
2091 2092

    if (item->prev != NULL)
2093 2094
    {
        /* not the first element */
M
Max Bruckner 已提交
2095
        item->prev->next = item->next;
2096
    }
M
Max Bruckner 已提交
2097
    if (item->next != NULL)
2098
    {
M
Max Bruckner 已提交
2099 2100
        /* not the last element */
        item->next->prev = item->prev;
2101
    }
M
Max Bruckner 已提交
2102 2103

    if (item == parent->child)
2104
    {
M
Max Bruckner 已提交
2105 2106
        /* first element */
        parent->child = item->next;
2107 2108
    }
    /* make sure the detached item doesn't point anywhere anymore */
M
Max Bruckner 已提交
2109 2110
    item->prev = NULL;
    item->next = NULL;
2111

M
Max Bruckner 已提交
2112
    return item;
2113
}
M
Max Bruckner 已提交
2114

2115
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
2116 2117 2118 2119 2120 2121
{
    if (which < 0)
    {
        return NULL;
    }

M
Max Bruckner 已提交
2122
    return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
M
Max Bruckner 已提交
2123
}
K
Kevin Branigan 已提交
2124

2125
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
2126 2127 2128 2129
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

2130
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
2131
{
2132
    cJSON *to_detach = cJSON_GetObjectItem(object, string);
2133

2134 2135 2136 2137 2138 2139
    return cJSON_DetachItemViaPointer(object, to_detach);
}

CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
    cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
2140

2141
    return cJSON_DetachItemViaPointer(object, to_detach);
2142 2143
}

2144
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
2145 2146 2147
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
2148

2149 2150 2151 2152 2153
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}

K
Kevin Branigan 已提交
2154
/* Replace array/object items with new ones. */
2155
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
2156
{
M
Max Bruckner 已提交
2157 2158 2159
    cJSON *after_inserted = NULL;

    if (which < 0)
2160
    {
M
Max Bruckner 已提交
2161
        return;
2162
    }
M
Max Bruckner 已提交
2163 2164 2165

    after_inserted = get_array_item(array, (size_t)which);
    if (after_inserted == NULL)
2166
    {
2167
        add_item_to_array(array, newitem);
2168 2169
        return;
    }
M
Max Bruckner 已提交
2170 2171 2172 2173 2174

    newitem->next = after_inserted;
    newitem->prev = after_inserted->prev;
    after_inserted->prev = newitem;
    if (after_inserted == array->child)
2175 2176 2177 2178 2179 2180 2181 2182 2183
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
}

M
Max Bruckner 已提交
2184
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
2185
{
2186
    if ((parent == NULL) || (replacement == NULL) || (item == NULL))
2187
    {
M
Max Bruckner 已提交
2188
        return false;
2189
    }
M
Max Bruckner 已提交
2190

M
Max Bruckner 已提交
2191
    if (replacement == item)
2192
    {
M
Max Bruckner 已提交
2193
        return true;
2194
    }
M
Max Bruckner 已提交
2195

M
Max Bruckner 已提交
2196 2197 2198 2199
    replacement->next = item->next;
    replacement->prev = item->prev;

    if (replacement->next != NULL)
2200
    {
M
Max Bruckner 已提交
2201
        replacement->next->prev = replacement;
2202
    }
M
Max Bruckner 已提交
2203
    if (replacement->prev != NULL)
2204
    {
M
Max Bruckner 已提交
2205
        replacement->prev->next = replacement;
2206
    }
M
Max Bruckner 已提交
2207
    if (parent->child == item)
2208
    {
M
Max Bruckner 已提交
2209
        parent->child = replacement;
2210
    }
M
Max Bruckner 已提交
2211

M
Max Bruckner 已提交
2212 2213 2214
    item->next = NULL;
    item->prev = NULL;
    cJSON_Delete(item);
M
Max Bruckner 已提交
2215

M
Max Bruckner 已提交
2216
    return true;
2217
}
M
Max Bruckner 已提交
2218

2219
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
2220 2221 2222 2223 2224 2225
{
    if (which < 0)
    {
        return;
    }

M
Max Bruckner 已提交
2226
    cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
M
Max Bruckner 已提交
2227
}
2228

2229 2230
static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
{
2231
    if ((replacement == NULL) || (string == NULL))
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    {
        return false;
    }

    /* replace the name in the replacement */
    if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
    {
        cJSON_free(replacement->string);
    }
    replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
    replacement->type &= ~cJSON_StringIsConst;

    cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);

    return true;
}

2249
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
2250
{
2251
    replace_item_in_object(object, string, newitem, false);
2252
}
2253

2254 2255
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
2256
    replace_item_in_object(object, string, newitem, true);
2257
}
K
Kevin Branigan 已提交
2258 2259

/* Create basic types: */
2260
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
2261
{
2262
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2263 2264 2265 2266 2267 2268 2269 2270
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

2271
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
2272
{
2273
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2274 2275 2276 2277 2278 2279 2280 2281
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

2282
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
2283
{
2284
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2285 2286 2287 2288 2289 2290 2291 2292
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

2293
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
2294
{
2295
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2296 2297 2298 2299 2300 2301 2302 2303
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

2304
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
2305
{
2306
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2307 2308 2309 2310
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2311 2312 2313 2314 2315 2316

        /* use saturation in case of overflow */
        if (num >= INT_MAX)
        {
            item->valueint = INT_MAX;
        }
2317
        else if (num <= (double)INT_MIN)
2318 2319 2320 2321 2322 2323 2324
        {
            item->valueint = INT_MIN;
        }
        else
        {
            item->valueint = (int)num;
        }
M
Max Bruckner 已提交
2325 2326 2327 2328 2329
    }

    return item;
}

2330
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
2331
{
2332
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2333 2334 2335
    if(item)
    {
        item->type = cJSON_String;
2336
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
2337 2338 2339
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2340
            return NULL;
M
Max Bruckner 已提交
2341 2342 2343 2344 2345 2346
        }
    }

    return item;
}

M
Max Bruckner 已提交
2347 2348 2349 2350 2351 2352
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL)
    {
        item->type = cJSON_String | cJSON_IsReference;
2353
        item->valuestring = (char*)cast_away_const(string);
M
Max Bruckner 已提交
2354 2355 2356 2357 2358
    }

    return item;
}

2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL) {
        item->type = cJSON_Object | cJSON_IsReference;
        item->child = (cJSON*)cast_away_const(child);
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL) {
        item->type = cJSON_Array | cJSON_IsReference;
        item->child = (cJSON*)cast_away_const(child);
    }

    return item;
}

2380
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
2381
{
2382
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2383 2384 2385
    if(item)
    {
        item->type = cJSON_Raw;
2386
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
2387 2388 2389 2390 2391 2392 2393 2394
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2395 2396
}

2397
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
2398
{
2399
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2400 2401 2402 2403 2404 2405 2406 2407
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

2408
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
2409
{
2410
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2411 2412 2413 2414 2415 2416 2417
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2418 2419

/* Create Arrays: */
2420
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
2421
{
2422
    size_t i = 0;
2423 2424
    cJSON *n = NULL;
    cJSON *p = NULL;
2425 2426
    cJSON *a = NULL;

2427
    if ((count < 0) || (numbers == NULL))
2428 2429 2430 2431 2432 2433
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2434 2435 2436 2437 2438
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2439
            return NULL;
M
Max Bruckner 已提交
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2455
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
2456
{
2457
    size_t i = 0;
2458 2459
    cJSON *n = NULL;
    cJSON *p = NULL;
2460 2461
    cJSON *a = NULL;

2462
    if ((count < 0) || (numbers == NULL))
2463 2464 2465 2466 2467 2468 2469
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2470
    {
2471
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
2472 2473 2474
        if(!n)
        {
            cJSON_Delete(a);
2475
            return NULL;
M
Max Bruckner 已提交
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2491
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
2492
{
2493
    size_t i = 0;
2494 2495
    cJSON *n = NULL;
    cJSON *p = NULL;
2496 2497
    cJSON *a = NULL;

2498
    if ((count < 0) || (numbers == NULL))
2499 2500 2501 2502 2503 2504 2505
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2506 2507 2508 2509 2510
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2511
            return NULL;
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2527
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2528
{
2529
    size_t i = 0;
2530 2531
    cJSON *n = NULL;
    cJSON *p = NULL;
2532 2533
    cJSON *a = NULL;

2534
    if ((count < 0) || (strings == NULL))
2535 2536 2537 2538 2539 2540 2541
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2542 2543 2544 2545 2546
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2547
            return NULL;
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2562 2563

/* Duplication */
2564
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2565
{
M
Max Bruckner 已提交
2566
    cJSON *newitem = NULL;
2567 2568
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2569
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2570 2571 2572 2573

    /* Bail on bad ptr */
    if (!item)
    {
2574
        goto fail;
M
Max Bruckner 已提交
2575 2576
    }
    /* Create new item */
2577
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2578 2579
    if (!newitem)
    {
2580
        goto fail;
M
Max Bruckner 已提交
2581 2582 2583 2584 2585 2586 2587
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2588
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2589 2590
        if (!newitem->valuestring)
        {
2591
            goto fail;
M
Max Bruckner 已提交
2592 2593 2594 2595
        }
    }
    if (item->string)
    {
2596
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2597 2598
        if (!newitem->string)
        {
2599
            goto fail;
M
Max Bruckner 已提交
2600 2601 2602 2603 2604 2605 2606 2607
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2608 2609
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2610
    {
2611
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2612 2613
        if (!newchild)
        {
2614
            goto fail;
M
Max Bruckner 已提交
2615
        }
2616
        if (next != NULL)
M
Max Bruckner 已提交
2617 2618
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2619 2620 2621
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2622 2623 2624 2625
        }
        else
        {
            /* Set newitem->child and move to it */
2626 2627
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2628
        }
2629
        child = child->next;
M
Max Bruckner 已提交
2630 2631 2632
    }

    return newitem;
2633 2634 2635 2636 2637 2638 2639 2640

fail:
    if (newitem != NULL)
    {
        cJSON_Delete(newitem);
    }

    return NULL;
2641
}
2642

2643
static void skip_oneline_comment(char **input)
2644
{
2645
    *input += static_strlen("//");
2646

2647
    for (; (*input)[0] != '\0'; ++(*input))
2648
    {
2649 2650 2651 2652
        if ((*input)[0] == '\n') {
            *input += static_strlen("\n");
            return;
        }
2653
    }
2654 2655 2656 2657 2658
}

static void skip_multiline_comment(char **input)
{
    *input += static_strlen("/*");
2659

2660
    for (; (*input)[0] != '\0'; ++(*input))
M
Max Bruckner 已提交
2661
    {
2662
        if (((*input)[0] == '*') && ((*input)[1] == '/'))
M
Max Bruckner 已提交
2663
        {
2664 2665
            *input += static_strlen("*/");
            return;
M
Max Bruckner 已提交
2666
        }
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    }
}

static void minify_string(char **input, char **output) {
    (*output)[0] = (*input)[0];
    *input += static_strlen("\"");
    *output += static_strlen("\"");


    for (; (*input)[0] != '\0'; ++(*input), ++(*output)) {
        (*output)[0] = (*input)[0];

        if ((*input)[0] == '\"') {
            (*output)[0] = '\"';
            *input += static_strlen("\"");
            *output += static_strlen("\"");
            return;
        } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
            (*output)[1] = (*input)[1];
            *input += static_strlen("\"");
            *output += static_strlen("\"");
M
Max Bruckner 已提交
2688
        }
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
    }
}

CJSON_PUBLIC(void) cJSON_Minify(char *json)
{
    char *into = json;

    if (json == NULL)
    {
        return;
    }

    while (json[0] != '\0')
    {
        switch (json[0])
M
Max Bruckner 已提交
2704
        {
2705 2706 2707 2708
            case ' ':
            case '\t':
            case '\r':
            case '\n':
M
Max Bruckner 已提交
2709
                json++;
2710 2711 2712 2713
                break;

            case '/':
                if (json[1] == '/')
M
Max Bruckner 已提交
2714
                {
2715
                    skip_oneline_comment(&json);
M
Max Bruckner 已提交
2716
                }
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
                else if (json[1] == '*')
                {
                    skip_multiline_comment(&json);
                }
                break;

            case '\"':
                minify_string(&json, (char**)&into);
                break;

            default:
                into[0] = json[0];
                json++;
                into++;
M
Max Bruckner 已提交
2731 2732 2733 2734 2735
        }
    }

    /* and null-terminate. */
    *into = '\0';
2736
}
2737

2738
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2739 2740 2741 2742 2743 2744 2745 2746 2747
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Invalid;
}

2748
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2749 2750 2751 2752 2753 2754 2755 2756 2757
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_False;
}

2758
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xff) == cJSON_True;
}


2769
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2770 2771 2772 2773 2774 2775 2776 2777
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2778
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2779 2780 2781 2782 2783 2784 2785 2786 2787
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_NULL;
}

2788
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2789 2790 2791 2792 2793 2794 2795 2796 2797
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Number;
}

2798
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2799 2800 2801 2802 2803 2804 2805 2806 2807
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_String;
}

2808
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2809 2810 2811 2812 2813 2814 2815 2816 2817
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Array;
}

2818
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2819 2820 2821 2822 2823 2824 2825 2826 2827
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Object;
}

2828
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2829 2830 2831 2832 2833 2834 2835 2836
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Raw;
}
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897

CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
{
    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
    {
        return false;
    }

    /* check if type is valid */
    switch (a->type & 0xFF)
    {
        case cJSON_False:
        case cJSON_True:
        case cJSON_NULL:
        case cJSON_Number:
        case cJSON_String:
        case cJSON_Raw:
        case cJSON_Array:
        case cJSON_Object:
            break;

        default:
            return false;
    }

    /* identical objects are equal */
    if (a == b)
    {
        return true;
    }

    switch (a->type & 0xFF)
    {
        /* in these cases and equal type is enough */
        case cJSON_False:
        case cJSON_True:
        case cJSON_NULL:
            return true;

        case cJSON_Number:
            if (a->valuedouble == b->valuedouble)
            {
                return true;
            }
            return false;

        case cJSON_String:
        case cJSON_Raw:
            if ((a->valuestring == NULL) || (b->valuestring == NULL))
            {
                return false;
            }
            if (strcmp(a->valuestring, b->valuestring) == 0)
            {
                return true;
            }

            return false;

        case cJSON_Array:
        {
M
Max Bruckner 已提交
2898 2899 2900 2901
            cJSON *a_element = a->child;
            cJSON *b_element = b->child;

            for (; (a_element != NULL) && (b_element != NULL);)
2902 2903 2904 2905 2906
            {
                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }
M
Max Bruckner 已提交
2907 2908 2909

                a_element = a_element->next;
                b_element = b_element->next;
2910 2911
            }

2912 2913 2914 2915 2916
            /* one of the arrays is longer than the other */
            if (a_element != b_element) {
                return false;
            }

2917 2918 2919 2920 2921 2922
            return true;
        }

        case cJSON_Object:
        {
            cJSON *a_element = NULL;
2923
            cJSON *b_element = NULL;
2924 2925 2926
            cJSON_ArrayForEach(a_element, a)
            {
                /* TODO This has O(n^2) runtime, which is horrible! */
2927
                b_element = get_object_item(b, a_element->string, case_sensitive);
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
                if (b_element == NULL)
                {
                    return false;
                }

                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }
            }

2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
            /* doing this twice, once on a and b to prevent true comparison if a subset of b
             * TODO: Do this the proper way, this is just a fix for now */
            cJSON_ArrayForEach(b_element, b)
            {
                a_element = get_object_item(a, b_element->string, case_sensitive);
                if (a_element == NULL)
                {
                    return false;
                }

                if (!cJSON_Compare(b_element, a_element, case_sensitive))
                {
                    return false;
                }
            }

2955 2956 2957 2958 2959 2960 2961
            return true;
        }

        default:
            return false;
    }
}
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971

CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
{
    return global_hooks.allocate(size);
}

CJSON_PUBLIC(void) cJSON_free(void *object)
{
    global_hooks.deallocate(object);
}