cJSON.c 66.0 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 46
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
47
#include <locale.h>
48

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

K
Kevin Branigan 已提交
56 57
#include "cJSON.h"

M
Max Bruckner 已提交
58
/* define our own boolean type */
59 60
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)
M
Max Bruckner 已提交
61

62 63 64 65 66
typedef struct {
    const unsigned char *json;
    size_t position;
} error;
static error global_error = { NULL, 0 };
K
Kevin Branigan 已提交
67

68
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
M
Max Bruckner 已提交
69
{
70
    return (const char*) (global_error.json + global_error.position);
M
Max Bruckner 已提交
71
}
K
Kevin Branigan 已提交
72

73
/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
M
Max Bruckner 已提交
74
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 5) || (CJSON_VERSION_PATCH != 6)
75 76 77
    #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif

78
CJSON_PUBLIC(const char*) cJSON_Version(void)
79 80 81 82 83 84 85
{
    static char version[15];
    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

    return version;
}

86 87
/* 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 已提交
88
{
89
    if ((string1 == NULL) || (string2 == NULL))
M
Max Bruckner 已提交
90
    {
91
        return 1;
M
Max Bruckner 已提交
92
    }
93

94
    if (string1 == string2)
M
Max Bruckner 已提交
95
    {
96
        return 0;
M
Max Bruckner 已提交
97
    }
98 99

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
100
    {
101
        if (*string1 == '\0')
M
Max Bruckner 已提交
102 103 104 105 106
        {
            return 0;
        }
    }

107
    return tolower(*string1) - tolower(*string2);
K
Kevin Branigan 已提交
108 109
}

110 111 112 113 114 115 116 117
typedef struct internal_hooks
{
    void *(*allocate)(size_t size);
    void (*deallocate)(void *pointer);
    void *(*reallocate)(void *pointer, size_t size);
} internal_hooks;

static internal_hooks global_hooks = { malloc, free, realloc };
K
Kevin Branigan 已提交
118

M
Max Bruckner 已提交
119
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
120
{
M
Max Bruckner 已提交
121
    size_t length = 0;
122
    unsigned char *copy = NULL;
K
Kevin Branigan 已提交
123

M
Max Bruckner 已提交
124
    if (string == NULL)
125 126 127 128
    {
        return NULL;
    }

M
Max Bruckner 已提交
129 130
    length = strlen((const char*)string) + sizeof("");
    if (!(copy = (unsigned char*)hooks->allocate(length)))
M
Max Bruckner 已提交
131
    {
132
        return NULL;
M
Max Bruckner 已提交
133
    }
M
Max Bruckner 已提交
134
    memcpy(copy, string, length);
M
Max Bruckner 已提交
135 136

    return copy;
K
Kevin Branigan 已提交
137 138
}

139
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
K
Kevin Branigan 已提交
140
{
M
Max Bruckner 已提交
141
    if (hooks == NULL)
M
Max Bruckner 已提交
142 143
    {
        /* Reset hooks */
144 145 146
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
K
Kevin Branigan 已提交
147 148 149
        return;
    }

150
    global_hooks.allocate = malloc;
M
Max Bruckner 已提交
151 152
    if (hooks->malloc_fn != NULL)
    {
153
        global_hooks.allocate = hooks->malloc_fn;
M
Max Bruckner 已提交
154 155
    }

156
    global_hooks.deallocate = free;
M
Max Bruckner 已提交
157 158
    if (hooks->free_fn != NULL)
    {
159
        global_hooks.deallocate = hooks->free_fn;
M
Max Bruckner 已提交
160 161 162
    }

    /* use realloc only if both free and malloc are used */
163 164
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
M
Max Bruckner 已提交
165
    {
166
        global_hooks.reallocate = realloc;
M
Max Bruckner 已提交
167
    }
K
Kevin Branigan 已提交
168 169 170
}

/* Internal constructor. */
171
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
K
Kevin Branigan 已提交
172
{
173
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
M
Max Bruckner 已提交
174 175
    if (node)
    {
176
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
177 178 179
    }

    return node;
K
Kevin Branigan 已提交
180 181 182
}

/* Delete a cJSON structure. */
M
Max Bruckner 已提交
183
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
K
Kevin Branigan 已提交
184
{
M
Max Bruckner 已提交
185
    cJSON *next = NULL;
M
Max Bruckner 已提交
186
    while (item != NULL)
M
Max Bruckner 已提交
187
    {
M
Max Bruckner 已提交
188 189
        next = item->next;
        if (!(item->type & cJSON_IsReference) && (item->child != NULL))
M
Max Bruckner 已提交
190
        {
M
Max Bruckner 已提交
191
            cJSON_Delete(item->child);
M
Max Bruckner 已提交
192
        }
M
Max Bruckner 已提交
193
        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
M
Max Bruckner 已提交
194
        {
M
Max Bruckner 已提交
195
            global_hooks.deallocate(item->valuestring);
M
Max Bruckner 已提交
196
        }
M
Max Bruckner 已提交
197
        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
M
Max Bruckner 已提交
198
        {
M
Max Bruckner 已提交
199
            global_hooks.deallocate(item->string);
M
Max Bruckner 已提交
200
        }
M
Max Bruckner 已提交
201 202
        global_hooks.deallocate(item);
        item = next;
M
Max Bruckner 已提交
203
    }
K
Kevin Branigan 已提交
204 205
}

206 207 208 209 210 211 212
/* get the decimal point character of the current locale */
static unsigned char get_decimal_point(void)
{
    struct lconv *lconv = localeconv();
    return (unsigned char) lconv->decimal_point[0];
}

M
Max Bruckner 已提交
213 214 215 216 217
typedef struct
{
    const unsigned char *content;
    size_t length;
    size_t offset;
218
    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
219
    internal_hooks hooks;
M
Max Bruckner 已提交
220 221 222 223 224 225 226 227 228 229
} 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 已提交
230
/* Parse the input text to generate a number, and populate the result into item. */
231
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
232
{
233
    double number = 0;
234
    unsigned char *after_end = NULL;
235 236 237
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;
M
Max Bruckner 已提交
238

M
Max Bruckner 已提交
239
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
240
    {
241
        return false;
242 243
    }

244
    /* copy the number into a temporary buffer and replace '.' with the decimal point
M
Max Bruckner 已提交
245 246 247
     * 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++)
248
    {
M
Max Bruckner 已提交
249
        switch (buffer_at_offset(input_buffer)[i])
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        {
            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 已提交
265
                number_c_string[i] = buffer_at_offset(input_buffer)[i];
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                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 已提交
281
    {
282
        return false; /* parse_error */
M
Max Bruckner 已提交
283 284
    }

285
    item->valuedouble = number;
M
Max Bruckner 已提交
286

287
    /* use saturation in case of overflow */
288
    if (number >= INT_MAX)
289 290 291
    {
        item->valueint = INT_MAX;
    }
292
    else if (number <= INT_MIN)
293 294 295 296 297
    {
        item->valueint = INT_MIN;
    }
    else
    {
298
        item->valueint = (int)number;
299
    }
300

M
Max Bruckner 已提交
301 302
    item->type = cJSON_Number;

M
Max Bruckner 已提交
303
    input_buffer->offset += (size_t)(after_end - number_c_string);
304
    return true;
K
Kevin Branigan 已提交
305 306
}

307
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
308
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
309 310 311 312 313 314 315 316 317 318 319
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
320
        object->valueint = (int)number;
321 322 323 324 325
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
326 327
typedef struct
{
328
    unsigned char *buffer;
329 330
    size_t length;
    size_t offset;
M
Max Bruckner 已提交
331
    size_t depth; /* current nesting depth (for formatted printing) */
332
    cJSON_bool noalloc;
M
Max Bruckner 已提交
333
    cJSON_bool format; /* is this print a formatted print */
334
    internal_hooks hooks;
M
Max Bruckner 已提交
335
} printbuffer;
336

M
Max Bruckner 已提交
337
/* realloc printbuffer if necessary to have at least "needed" bytes more */
338
static unsigned char* ensure(printbuffer * const p, size_t needed)
339
{
340
    unsigned char *newbuffer = NULL;
341 342
    size_t newsize = 0;

343
    if ((p == NULL) || (p->buffer == NULL))
344 345 346 347
    {
        return NULL;
    }

M
Max Bruckner 已提交
348 349 350 351 352 353
    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

354
    if (needed > INT_MAX)
M
Max Bruckner 已提交
355
    {
356
        /* sizes bigger than INT_MAX are currently not supported */
357
        return NULL;
M
Max Bruckner 已提交
358
    }
359

360
    needed += p->offset + 1;
M
Max Bruckner 已提交
361 362 363 364 365
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

366 367 368 369
    if (p->noalloc) {
        return NULL;
    }

370
    /* calculate new buffer size */
M
Max Bruckner 已提交
371
    if (needed > (INT_MAX / 2))
372 373 374 375 376 377 378 379 380 381 382
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
383 384 385 386
    else
    {
        newsize = needed * 2;
    }
387

388
    if (p->hooks.reallocate != NULL)
M
Max Bruckner 已提交
389
    {
M
Max Bruckner 已提交
390
        /* reallocate with realloc if available */
391
        newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
M
Max Bruckner 已提交
392
    }
M
Max Bruckner 已提交
393
    else
M
Max Bruckner 已提交
394
    {
M
Max Bruckner 已提交
395
        /* otherwise reallocate manually */
396
        newbuffer = (unsigned char*)p->hooks.allocate(newsize);
M
Max Bruckner 已提交
397 398
        if (!newbuffer)
        {
399
            p->hooks.deallocate(p->buffer);
M
Max Bruckner 已提交
400 401 402 403 404 405 406
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
407
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
408
        }
409
        p->hooks.deallocate(p->buffer);
M
Max Bruckner 已提交
410 411 412 413 414
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
415 416
}

417 418
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
419
{
420 421
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
422
    {
423
        return;
M
Max Bruckner 已提交
424
    }
425
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
426

427
    buffer->offset += strlen((const char*)buffer_pointer);
428 429 430
}

/* Render the number nicely from the given item into a string. */
431
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
432
{
M
Max Bruckner 已提交
433
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
434
    double d = item->valuedouble;
435
    int length = 0;
436
    size_t i = 0;
437
    unsigned char number_buffer[26]; /* temporary buffer to print the number into */
438
    unsigned char decimal_point = get_decimal_point();
439
    double test;
M
Max Bruckner 已提交
440

M
Max Bruckner 已提交
441
    if (output_buffer == NULL)
M
Max Bruckner 已提交
442
    {
443
        return false;
M
Max Bruckner 已提交
444
    }
M
Max Bruckner 已提交
445

446 447 448
    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
449
        length = sprintf((char*)number_buffer, "null");
450 451 452
    }
    else
    {
453 454 455 456 457 458 459 460 461
        /* 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 已提交
462
    }
463

464 465
    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
466
    {
467
        return false;
468 469
    }

470
    /* reserve appropriate space in the output */
471
    output_pointer = ensure(output_buffer, (size_t)length);
472 473 474
    if (output_pointer == NULL)
    {
        return false;
475 476
    }

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    /* 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;

493
    return true;
K
Kevin Branigan 已提交
494 495
}

M
Max Bruckner 已提交
496
/* parse 4 digit hexadecimal number */
497
static unsigned parse_hex4(const unsigned char * const input)
498
{
M
Max Bruckner 已提交
499
    unsigned int h = 0;
500
    size_t i = 0;
M
Max Bruckner 已提交
501

502
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
503
    {
504
        /* parse digit */
505
        if ((input[i] >= '0') && (input[i] <= '9'))
506
        {
507
            h += (unsigned int) input[i] - '0';
508
        }
509
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
510
        {
511
            h += (unsigned int) 10 + input[i] - 'A';
512
        }
513
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
514
        {
515
            h += (unsigned int) 10 + input[i] - 'a';
516 517 518 519 520
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
521

522 523 524 525 526
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
527 528 529
    }

    return h;
530 531
}

532 533
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
534
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 已提交
535
{
536 537 538
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
539
    unsigned char utf8_length = 0;
540
    unsigned char utf8_position = 0;
541
    unsigned char sequence_length = 0;
542
    unsigned char first_byte_mark = 0;
543 544 545 546 547 548

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

550 551 552
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

553
    /* check that the code is valid */
554
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
M
Max Bruckner 已提交
555
    {
556
        goto fail;
M
Max Bruckner 已提交
557
    }
M
Max Bruckner 已提交
558

559 560
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
561
    {
562 563 564 565 566
        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 已提交
567
        {
568 569
            /* input ends unexpectedly */
            goto fail;
M
Max Bruckner 已提交
570
        }
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

        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 已提交
595
    }
M
Max Bruckner 已提交
596

597 598 599 600 601 602 603 604 605 606 607 608
    /* 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;
609
        first_byte_mark = 0xC0; /* 11000000 */
610 611 612 613 614
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
615
        first_byte_mark = 0xE0; /* 11100000 */
616 617 618 619 620
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
621
        first_byte_mark = 0xF0; /* 11110000 */
622 623
    }
    else
M
Max Bruckner 已提交
624
    {
625
        /* invalid unicode codepoint */
626
        goto fail;
M
Max Bruckner 已提交
627 628
    }

629
    /* encode as utf8 */
630 631 632 633 634
    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;
635
    }
636 637 638 639 640 641 642 643
    /* 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);
644
    }
645

646 647 648 649 650 651 652 653 654
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
655
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
656
{
M
Max Bruckner 已提交
657 658
    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
659 660 661 662
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
M
Max Bruckner 已提交
663
    if (buffer_at_offset(input_buffer)[0] != '\"')
664 665 666 667 668 669 670 671
    {
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
672
        while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
673 674 675 676
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
M
Max Bruckner 已提交
677
                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
678 679 680 681 682 683 684 685 686
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
687
        if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
688 689 690 691 692
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
M
Max Bruckner 已提交
693
        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
694
        output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
695 696 697 698 699 700 701
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
702
    /* loop through the string literal */
703
    while (input_pointer < input_end)
M
Max Bruckner 已提交
704
    {
705
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
706
        {
707
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
708 709 710 711
        }
        /* escape sequence */
        else
        {
712
            unsigned char sequence_length = 2;
M
Max Bruckner 已提交
713 714 715 716 717
            if ((input_end - input_pointer) < 1)
            {
                goto fail;
            }

718
            switch (input_pointer[1])
M
Max Bruckner 已提交
719 720
            {
                case 'b':
721
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
722 723
                    break;
                case 'f':
724
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
725 726
                    break;
                case 'n':
727
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
728 729
                    break;
                case 'r':
730
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
731 732
                    break;
                case 't':
733
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
734
                    break;
735 736 737
                case '\"':
                case '\\':
                case '/':
738
                    *output_pointer++ = input_pointer[1];
739
                    break;
740 741

                /* UTF-16 literal */
M
Max Bruckner 已提交
742
                case 'u':
743
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
744
                    if (sequence_length == 0)
M
Max Bruckner 已提交
745
                    {
746
                        /* failed to convert UTF16-literal to UTF-8 */
747
                        goto fail;
M
Max Bruckner 已提交
748 749
                    }
                    break;
750

M
Max Bruckner 已提交
751
                default:
752
                    goto fail;
M
Max Bruckner 已提交
753
            }
754
            input_pointer += sequence_length;
M
Max Bruckner 已提交
755 756
        }
    }
757 758 759

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

761
    item->type = cJSON_String;
762
    item->valuestring = (char*)output;
763

M
Max Bruckner 已提交
764 765 766
    input_buffer->offset = (size_t) (input_end - input_buffer->content);
    input_buffer->offset++;

767
    return true;
768 769

fail:
770
    if (output != NULL)
771
    {
772
        input_buffer->hooks.deallocate(output);
773 774
    }

775 776 777 778 779
    if (input_pointer != NULL)
    {
        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
    }

780
    return false;
K
Kevin Branigan 已提交
781 782 783
}

/* Render the cstring provided to an escaped version that can be printed. */
784
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
785
{
786 787 788
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
789 790 791
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
792

793
    if (output_buffer == NULL)
M
Max Bruckner 已提交
794
    {
795
        return false;
M
Max Bruckner 已提交
796 797 798
    }

    /* empty string */
799
    if (input == NULL)
M
Max Bruckner 已提交
800
    {
801
        output = ensure(output_buffer, sizeof("\"\""));
802
        if (output == NULL)
M
Max Bruckner 已提交
803
        {
804
            return false;
M
Max Bruckner 已提交
805
        }
806
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
807

808
        return true;
M
Max Bruckner 已提交
809 810 811
    }

    /* set "flag" to 1 if something needs to be escaped */
812
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
813
    {
M
Max Bruckner 已提交
814
        switch (*input_pointer)
M
Max Bruckner 已提交
815
        {
M
Max Bruckner 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
            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 已提交
833 834
        }
    }
M
Max Bruckner 已提交
835
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
836

837
    output = ensure(output_buffer, output_length + sizeof("\"\""));
838
    if (output == NULL)
M
Max Bruckner 已提交
839
    {
840
        return false;
M
Max Bruckner 已提交
841 842
    }

M
Max Bruckner 已提交
843 844
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
845
    {
M
Max Bruckner 已提交
846 847 848 849 850
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

851
        return true;
M
Max Bruckner 已提交
852 853
    }

M
Max Bruckner 已提交
854 855
    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
856
    /* copy the string */
M
Max Bruckner 已提交
857
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
858
    {
859
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
860 861
        {
            /* normal character, copy */
M
Max Bruckner 已提交
862
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
863 864 865 866
        }
        else
        {
            /* character needs to be escaped */
867
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
868
            switch (*input_pointer)
M
Max Bruckner 已提交
869 870
            {
                case '\\':
M
Max Bruckner 已提交
871
                    *output_pointer = '\\';
M
Max Bruckner 已提交
872 873
                    break;
                case '\"':
M
Max Bruckner 已提交
874
                    *output_pointer = '\"';
M
Max Bruckner 已提交
875 876
                    break;
                case '\b':
M
Max Bruckner 已提交
877
                    *output_pointer = 'b';
M
Max Bruckner 已提交
878 879
                    break;
                case '\f':
M
Max Bruckner 已提交
880
                    *output_pointer = 'f';
M
Max Bruckner 已提交
881 882
                    break;
                case '\n':
M
Max Bruckner 已提交
883
                    *output_pointer = 'n';
M
Max Bruckner 已提交
884 885
                    break;
                case '\r':
M
Max Bruckner 已提交
886
                    *output_pointer = 'r';
M
Max Bruckner 已提交
887 888
                    break;
                case '\t':
M
Max Bruckner 已提交
889
                    *output_pointer = 't';
M
Max Bruckner 已提交
890 891 892
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
893 894
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
895 896 897 898
                    break;
            }
        }
    }
M
Max Bruckner 已提交
899 900
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
901

902
    return true;
K
Kevin Branigan 已提交
903
}
M
Max Bruckner 已提交
904

M
Max Bruckner 已提交
905
/* Invoke print_string_ptr (which is useful) on an item. */
906
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
M
Max Bruckner 已提交
907
{
908
    return print_string_ptr((unsigned char*)item->valuestring, p);
M
Max Bruckner 已提交
909
}
K
Kevin Branigan 已提交
910 911

/* Predeclare these prototypes. */
912 913 914 915 916 917
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 已提交
918 919

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
920
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
M
Max Bruckner 已提交
921
{
M
Max Bruckner 已提交
922 923 924 925 926
    if ((buffer == NULL) || (buffer->content == NULL))
    {
        return NULL;
    }

M
Max Bruckner 已提交
927 928 929 930 931 932
    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
    {
       buffer->offset++;
    }

    if (buffer->offset == buffer->length)
M
Max Bruckner 已提交
933
    {
M
Max Bruckner 已提交
934
        buffer->offset--;
M
Max Bruckner 已提交
935 936
    }

M
Max Bruckner 已提交
937
    return buffer;
M
Max Bruckner 已提交
938
}
K
Kevin Branigan 已提交
939 940

/* Parse an object - create a new root, and populate. */
941
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
942
{
943
    parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
944
    cJSON *item = NULL;
945 946 947 948

    /* reset error position */
    global_error.json = NULL;
    global_error.position = 0;
949 950

    if (value == NULL)
M
Max Bruckner 已提交
951
    {
952
        goto fail;
M
Max Bruckner 已提交
953 954
    }

M
Max Bruckner 已提交
955 956 957
    buffer.content = (const unsigned char*)value;
    buffer.length = strlen((const char*)value) + sizeof("");
    buffer.offset = 0;
958
    buffer.hooks = global_hooks;
M
Max Bruckner 已提交
959

960 961 962 963
    item = cJSON_New_Item(&global_hooks);
    if (item == NULL) /* memory fail */
    {
        goto fail;
M
Max Bruckner 已提交
964 965
    }

966
    if (!parse_value(item, buffer_skip_whitespace(&buffer)))
M
Max Bruckner 已提交
967 968
    {
        /* parse failure. ep is set. */
969
        goto fail;
M
Max Bruckner 已提交
970 971 972 973 974
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
975 976
        buffer_skip_whitespace(&buffer);
        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
M
Max Bruckner 已提交
977
        {
978
            goto fail;
M
Max Bruckner 已提交
979 980 981 982
        }
    }
    if (return_parse_end)
    {
983
        *return_parse_end = (const char*)buffer_at_offset(&buffer);
M
Max Bruckner 已提交
984 985
    }

986
    return item;
987 988 989 990 991 992 993

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

994 995
    if (value != NULL)
    {
996 997 998 999
        error local_error;
        local_error.json = (const unsigned char*)value;
        local_error.position = 0;

1000 1001
        if (buffer.offset < buffer.length)
        {
1002
            local_error.position = buffer.offset;
1003 1004 1005
        }
        else if (buffer.length > 0)
        {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
            local_error.position = buffer.length - 1;
        }

        if (return_parse_end != NULL)
        {
            *return_parse_end = (const char*)local_error.json + local_error.position;
        }
        else
        {
            global_error = local_error;
1016
        }
M
Max Bruckner 已提交
1017 1018
    }

1019
    return NULL;
K
Kevin Branigan 已提交
1020
}
M
Max Bruckner 已提交
1021

1022
/* Default options for cJSON_Parse */
1023
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
1024 1025 1026
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
1027

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

1030
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1031 1032 1033 1034 1035 1036 1037
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
1038
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
1039
    buffer->format = format;
1040
    buffer->hooks = *hooks;
M
Max Bruckner 已提交
1041 1042 1043 1044 1045 1046
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
1047
    if (!print_value(item, buffer))
M
Max Bruckner 已提交
1048 1049 1050
    {
        goto fail;
    }
1051
    update_offset(buffer);
M
Max Bruckner 已提交
1052

1053 1054
    /* check if reallocate is available */
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
1055
    {
1056 1057 1058 1059 1060
        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->length);
        buffer->buffer = NULL;
        if (printed == NULL) {
            goto fail;
        }
M
Max Bruckner 已提交
1061
    }
1062 1063 1064 1065 1066 1067 1068
    else /* otherwise copy the JSON over to a new buffer */
    {
        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
        if (printed == NULL)
        {
            goto fail;
        }
1069
        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
1070
        printed[buffer->offset] = '\0'; /* just to be sure */
M
Max Bruckner 已提交
1071

1072 1073 1074
        /* free the buffer */
        hooks->deallocate(buffer->buffer);
    }
M
Max Bruckner 已提交
1075 1076 1077 1078 1079 1080

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
1081
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
1082 1083 1084 1085
    }

    if (printed != NULL)
    {
1086
        hooks->deallocate(printed);
M
Max Bruckner 已提交
1087 1088 1089 1090 1091
    }

    return NULL;
}

K
Kevin Branigan 已提交
1092
/* Render a cJSON item/entity/structure to text. */
1093
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
1094
{
1095
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
1096 1097
}

1098
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
1099
{
1100
    return (char*)print(item, false, &global_hooks);
1101
}
1102

1103
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
1104
{
1105
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
M
Max Bruckner 已提交
1106 1107 1108

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
1109
        return NULL;
M
Max Bruckner 已提交
1110 1111
    }

1112
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
1113 1114
    if (!p.buffer)
    {
1115
        return NULL;
1116
    }
M
Max Bruckner 已提交
1117 1118

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
1119
    p.offset = 0;
1120
    p.noalloc = false;
M
Max Bruckner 已提交
1121
    p.format = fmt;
1122
    p.hooks = global_hooks;
M
Max Bruckner 已提交
1123

1124
    if (!print_value(item, &p))
1125
    {
1126
        global_hooks.deallocate(p.buffer);
1127 1128 1129 1130
        return NULL;
    }

    return (char*)p.buffer;
1131 1132
}

1133
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
1134
{
1135
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
M
Max Bruckner 已提交
1136

1137
    if ((len < 0) || (buf == NULL))
M
Max Bruckner 已提交
1138 1139 1140 1141
    {
        return false;
    }

1142
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
1143
    p.length = (size_t)len;
1144
    p.offset = 0;
1145
    p.noalloc = true;
M
Max Bruckner 已提交
1146
    p.format = fmt;
1147
    p.hooks = global_hooks;
M
Max Bruckner 已提交
1148

1149
    return print_value(item, &p);
1150
}
K
Kevin Branigan 已提交
1151 1152

/* Parser core - when encountering text, process appropriately. */
1153
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1154
{
M
Max Bruckner 已提交
1155
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
M
Max Bruckner 已提交
1156
    {
1157
        return false; /* no input */
M
Max Bruckner 已提交
1158 1159 1160
    }

    /* parse the different types of values */
1161
    /* null */
M
Max Bruckner 已提交
1162
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
M
Max Bruckner 已提交
1163 1164
    {
        item->type = cJSON_NULL;
M
Max Bruckner 已提交
1165
        input_buffer->offset += 4;
1166
        return true;
M
Max Bruckner 已提交
1167
    }
1168
    /* false */
M
Max Bruckner 已提交
1169
    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
M
Max Bruckner 已提交
1170 1171
    {
        item->type = cJSON_False;
M
Max Bruckner 已提交
1172
        input_buffer->offset += 5;
1173
        return true;
M
Max Bruckner 已提交
1174
    }
1175
    /* true */
M
Max Bruckner 已提交
1176
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
M
Max Bruckner 已提交
1177 1178 1179
    {
        item->type = cJSON_True;
        item->valueint = 1;
M
Max Bruckner 已提交
1180
        input_buffer->offset += 4;
1181
        return true;
M
Max Bruckner 已提交
1182
    }
1183
    /* string */
M
Max Bruckner 已提交
1184
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
M
Max Bruckner 已提交
1185
    {
1186
        return parse_string(item, input_buffer);
M
Max Bruckner 已提交
1187
    }
1188
    /* number */
M
Max Bruckner 已提交
1189
    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 已提交
1190
    {
M
Max Bruckner 已提交
1191
        return parse_number(item, input_buffer);
M
Max Bruckner 已提交
1192
    }
1193
    /* array */
M
Max Bruckner 已提交
1194
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
M
Max Bruckner 已提交
1195
    {
1196
        return parse_array(item, input_buffer);
M
Max Bruckner 已提交
1197
    }
1198
    /* object */
M
Max Bruckner 已提交
1199
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
M
Max Bruckner 已提交
1200
    {
1201
        return parse_object(item, input_buffer);
M
Max Bruckner 已提交
1202 1203
    }

M
Max Bruckner 已提交
1204

1205
    return false;
K
Kevin Branigan 已提交
1206 1207 1208
}

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

M
Max Bruckner 已提交
1213
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1214
    {
1215
        return false;
M
Max Bruckner 已提交
1216
    }
M
Max Bruckner 已提交
1217 1218

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1219
    {
M
Max Bruckner 已提交
1220
        case cJSON_NULL:
1221
            output = ensure(output_buffer, 5);
1222
            if (output == NULL)
M
Max Bruckner 已提交
1223
            {
1224
                return false;
M
Max Bruckner 已提交
1225
            }
1226 1227 1228
            strcpy((char*)output, "null");
            return true;

M
Max Bruckner 已提交
1229
        case cJSON_False:
1230
            output = ensure(output_buffer, 6);
1231
            if (output == NULL)
M
Max Bruckner 已提交
1232
            {
1233
                return false;
M
Max Bruckner 已提交
1234
            }
1235 1236 1237
            strcpy((char*)output, "false");
            return true;

M
Max Bruckner 已提交
1238
        case cJSON_True:
1239
            output = ensure(output_buffer, 5);
1240
            if (output == NULL)
M
Max Bruckner 已提交
1241
            {
1242
                return false;
M
Max Bruckner 已提交
1243
            }
1244 1245 1246
            strcpy((char*)output, "true");
            return true;

M
Max Bruckner 已提交
1247
        case cJSON_Number:
1248
            return print_number(item, output_buffer);
1249

M
Max Bruckner 已提交
1250
        case cJSON_Raw:
M
Max Bruckner 已提交
1251
        {
M
Max Bruckner 已提交
1252 1253
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1254
            {
M
Max Bruckner 已提交
1255
                if (!output_buffer->noalloc)
1256
                {
1257
                    output_buffer->hooks.deallocate(output_buffer->buffer);
1258
                }
1259
                return false;
M
Max Bruckner 已提交
1260
            }
1261

1262
            raw_length = strlen(item->valuestring) + sizeof("");
1263
            output = ensure(output_buffer, raw_length);
1264
            if (output == NULL)
M
Max Bruckner 已提交
1265
            {
1266
                return false;
1267
            }
1268 1269
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1270
        }
1271

M
Max Bruckner 已提交
1272
        case cJSON_String:
1273
            return print_string(item, output_buffer);
1274

M
Max Bruckner 已提交
1275
        case cJSON_Array:
1276
            return print_array(item, output_buffer);
1277

M
Max Bruckner 已提交
1278
        case cJSON_Object:
1279
            return print_object(item, output_buffer);
1280

M
Max Bruckner 已提交
1281
        default:
1282
            return false;
M
Max Bruckner 已提交
1283
    }
K
Kevin Branigan 已提交
1284 1285 1286
}

/* Build an array from input text. */
1287
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1288
{
1289
    cJSON *head = NULL; /* head of the linked list */
1290 1291
    cJSON *current_item = NULL;

1292 1293 1294 1295 1296 1297
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1298
    if (buffer_at_offset(input_buffer)[0] != '[')
M
Max Bruckner 已提交
1299
    {
1300
        /* not an array */
1301
        goto fail;
M
Max Bruckner 已提交
1302
    }
K
Kevin Branigan 已提交
1303

M
Max Bruckner 已提交
1304 1305 1306
    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 已提交
1307
    {
1308
        /* empty array */
1309
        goto success;
M
Max Bruckner 已提交
1310
    }
K
Kevin Branigan 已提交
1311

M
Max Bruckner 已提交
1312 1313 1314 1315 1316 1317 1318
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1319
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1320
    input_buffer->offset--;
M
Max Bruckner 已提交
1321
    /* loop through the comma separated array elements */
1322
    do
M
Max Bruckner 已提交
1323
    {
1324
        /* allocate next item */
1325
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
1326
        if (new_item == NULL)
M
Max Bruckner 已提交
1327
        {
1328
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1329
        }
1330 1331 1332

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1333
        {
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
            /* 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 已提交
1346 1347
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1348
        if (!parse_value(current_item, input_buffer))
1349 1350
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1351
        }
M
Max Bruckner 已提交
1352
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1353
    }
M
Max Bruckner 已提交
1354
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
M
Max Bruckner 已提交
1355

M
Max Bruckner 已提交
1356
    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
M
Max Bruckner 已提交
1357
    {
1358
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1359 1360
    }

1361
success:
1362 1363
    input_buffer->depth--;

1364
    item->type = cJSON_Array;
1365
    item->child = head;
1366

M
Max Bruckner 已提交
1367 1368
    input_buffer->offset++;

1369
    return true;
K
Kevin Branigan 已提交
1370

1371
fail:
1372
    if (head != NULL)
1373
    {
1374
        cJSON_Delete(head);
1375 1376
    }

1377
    return false;
K
Kevin Branigan 已提交
1378 1379 1380
}

/* Render an array to text */
1381
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
1382
{
M
Max Bruckner 已提交
1383
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1384
    size_t length = 0;
M
Max Bruckner 已提交
1385
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1386

M
Max Bruckner 已提交
1387
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1388
    {
1389
        return false;
M
Max Bruckner 已提交
1390 1391
    }

M
Max Bruckner 已提交
1392 1393
    /* Compose the output array. */
    /* opening square bracket */
1394
    output_pointer = ensure(output_buffer, 1);
M
Max Bruckner 已提交
1395
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1396
    {
1397
        return false;
M
Max Bruckner 已提交
1398 1399
    }

M
Max Bruckner 已提交
1400 1401
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1402
    output_buffer->depth++;
M
Max Bruckner 已提交
1403

M
Max Bruckner 已提交
1404
    while (current_element != NULL)
M
Max Bruckner 已提交
1405
    {
1406
        if (!print_value(current_element, output_buffer))
M
Max Bruckner 已提交
1407
        {
1408
            return false;
M
Max Bruckner 已提交
1409
        }
1410
        update_offset(output_buffer);
M
Max Bruckner 已提交
1411
        if (current_element->next)
M
Max Bruckner 已提交
1412
        {
M
Max Bruckner 已提交
1413
            length = (size_t) (output_buffer->format ? 2 : 1);
1414
            output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1415
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1416
            {
1417
                return false;
M
Max Bruckner 已提交
1418
            }
M
Max Bruckner 已提交
1419
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1420
            if(output_buffer->format)
M
Max Bruckner 已提交
1421
            {
M
Max Bruckner 已提交
1422
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1423
            }
M
Max Bruckner 已提交
1424 1425
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1426
        }
M
Max Bruckner 已提交
1427
        current_element = current_element->next;
M
Max Bruckner 已提交
1428 1429
    }

1430
    output_pointer = ensure(output_buffer, 2);
M
Max Bruckner 已提交
1431
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1432
    {
1433
        return false;
M
Max Bruckner 已提交
1434
    }
M
Max Bruckner 已提交
1435 1436
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1437
    output_buffer->depth--;
M
Max Bruckner 已提交
1438

1439
    return true;
K
Kevin Branigan 已提交
1440 1441 1442
}

/* Build an object from the text. */
1443
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
1444
{
1445
    cJSON *head = NULL; /* linked list head */
1446 1447
    cJSON *current_item = NULL;

1448 1449 1450 1451 1452 1453
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1454
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
M
Max Bruckner 已提交
1455
    {
1456
        goto fail; /* not an object */
M
Max Bruckner 已提交
1457 1458
    }

M
Max Bruckner 已提交
1459 1460 1461
    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 已提交
1462
    {
1463
        goto success; /* empty object */
M
Max Bruckner 已提交
1464 1465
    }

M
Max Bruckner 已提交
1466 1467 1468 1469 1470 1471 1472
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1473
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1474
    input_buffer->offset--;
1475 1476
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1477
    {
1478
        /* allocate next item */
1479
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
1480 1481 1482 1483
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1484

1485 1486
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1487
        {
1488 1489 1490 1491 1492 1493 1494 1495 1496
            /* 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 已提交
1497 1498
        }

1499
        /* parse the name of the child */
M
Max Bruckner 已提交
1500 1501
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1502
        if (!parse_string(current_item, input_buffer))
M
Max Bruckner 已提交
1503
        {
1504
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1505
        }
M
Max Bruckner 已提交
1506
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1507

1508 1509 1510
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1511

M
Max Bruckner 已提交
1512
        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
M
Max Bruckner 已提交
1513
        {
1514
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1515
        }
1516 1517

        /* parse the value */
M
Max Bruckner 已提交
1518 1519
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1520
        if (!parse_value(current_item, input_buffer))
M
Max Bruckner 已提交
1521
        {
1522
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1523
        }
M
Max Bruckner 已提交
1524
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1525
    }
M
Max Bruckner 已提交
1526
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
1527

M
Max Bruckner 已提交
1528
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
M
Max Bruckner 已提交
1529
    {
1530
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1531 1532
    }

1533
success:
1534 1535
    input_buffer->depth--;

1536
    item->type = cJSON_Object;
1537
    item->child = head;
1538

M
Max Bruckner 已提交
1539
    input_buffer->offset++;
1540
    return true;
1541 1542

fail:
1543
    if (head != NULL)
1544
    {
1545
        cJSON_Delete(head);
1546 1547
    }

1548
    return false;
K
Kevin Branigan 已提交
1549 1550 1551
}

/* Render an object to text. */
1552
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
1553
{
M
Max Bruckner 已提交
1554
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1555
    size_t length = 0;
M
Max Bruckner 已提交
1556
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1557

M
Max Bruckner 已提交
1558
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1559
    {
1560
        return false;
M
Max Bruckner 已提交
1561 1562
    }

M
Max Bruckner 已提交
1563
    /* Compose the output: */
M
Max Bruckner 已提交
1564
    length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
1565
    output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1566
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1567
    {
1568
        return false;
M
Max Bruckner 已提交
1569 1570
    }

M
Max Bruckner 已提交
1571
    *output_pointer++ = '{';
M
Max Bruckner 已提交
1572
    output_buffer->depth++;
M
Max Bruckner 已提交
1573
    if (output_buffer->format)
M
Max Bruckner 已提交
1574
    {
M
Max Bruckner 已提交
1575
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1576
    }
M
Max Bruckner 已提交
1577
    output_buffer->offset += length;
M
Max Bruckner 已提交
1578

M
Max Bruckner 已提交
1579
    while (current_item)
M
Max Bruckner 已提交
1580
    {
M
Max Bruckner 已提交
1581
        if (output_buffer->format)
M
Max Bruckner 已提交
1582
        {
M
Max Bruckner 已提交
1583
            size_t i;
1584
            output_pointer = ensure(output_buffer, output_buffer->depth);
M
Max Bruckner 已提交
1585
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1586
            {
1587
                return false;
M
Max Bruckner 已提交
1588
            }
M
Max Bruckner 已提交
1589
            for (i = 0; i < output_buffer->depth; i++)
M
Max Bruckner 已提交
1590
            {
M
Max Bruckner 已提交
1591
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1592
            }
M
Max Bruckner 已提交
1593
            output_buffer->offset += output_buffer->depth;
M
Max Bruckner 已提交
1594 1595
        }

M
Max Bruckner 已提交
1596
        /* print key */
1597
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
M
Max Bruckner 已提交
1598
        {
1599
            return false;
M
Max Bruckner 已提交
1600
        }
M
Max Bruckner 已提交
1601
        update_offset(output_buffer);
M
Max Bruckner 已提交
1602

M
Max Bruckner 已提交
1603
        length = (size_t) (output_buffer->format ? 2 : 1);
1604
        output_pointer = ensure(output_buffer, length);
M
Max Bruckner 已提交
1605
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1606
        {
1607
            return false;
M
Max Bruckner 已提交
1608
        }
M
Max Bruckner 已提交
1609
        *output_pointer++ = ':';
M
Max Bruckner 已提交
1610
        if (output_buffer->format)
M
Max Bruckner 已提交
1611
        {
M
Max Bruckner 已提交
1612
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1613
        }
M
Max Bruckner 已提交
1614
        output_buffer->offset += length;
M
Max Bruckner 已提交
1615

M
Max Bruckner 已提交
1616
        /* print value */
1617
        if (!print_value(current_item, output_buffer))
M
Max Bruckner 已提交
1618
        {
1619
            return false;
M
Max Bruckner 已提交
1620
        }
M
Max Bruckner 已提交
1621
        update_offset(output_buffer);
M
Max Bruckner 已提交
1622

M
Max Bruckner 已提交
1623
        /* print comma if not last */
M
Max Bruckner 已提交
1624
        length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0));
1625
        output_pointer = ensure(output_buffer, length + 1);
M
Max Bruckner 已提交
1626
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1627
        {
1628
            return false;
M
Max Bruckner 已提交
1629
        }
M
Max Bruckner 已提交
1630
        if (current_item->next)
M
Max Bruckner 已提交
1631
        {
M
Max Bruckner 已提交
1632
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1633 1634
        }

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

M
Max Bruckner 已提交
1642
        current_item = current_item->next;
M
Max Bruckner 已提交
1643
    }
M
Max Bruckner 已提交
1644

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

1662
    return true;
K
Kevin Branigan 已提交
1663 1664 1665
}

/* Get Array size/item / object item. */
1666
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1667
{
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    cJSON *child = NULL;
    size_t size = 0;

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

    child = array->child;

    while(child != NULL)
M
Max Bruckner 已提交
1679
    {
1680 1681
        size++;
        child = child->next;
M
Max Bruckner 已提交
1682
    }
1683 1684 1685

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

1686
    return (int)size;
M
Max Bruckner 已提交
1687 1688
}

M
Max Bruckner 已提交
1689
static cJSON* get_array_item(const cJSON *array, size_t index)
M
Max Bruckner 已提交
1690
{
M
Max Bruckner 已提交
1691 1692 1693
    cJSON *current_child = NULL;

    if (array == NULL)
M
Max Bruckner 已提交
1694
    {
M
Max Bruckner 已提交
1695
        return NULL;
M
Max Bruckner 已提交
1696 1697
    }

M
Max Bruckner 已提交
1698 1699 1700 1701 1702 1703 1704 1705
    current_child = array->child;
    while ((current_child != NULL) && (index > 0))
    {
        index--;
        current_child = current_child->next;
    }

    return current_child;
M
Max Bruckner 已提交
1706 1707
}

M
Max Bruckner 已提交
1708
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
M
Max Bruckner 已提交
1709
{
M
Max Bruckner 已提交
1710
    if (index < 0)
M
Max Bruckner 已提交
1711
    {
M
Max Bruckner 已提交
1712
        return NULL;
M
Max Bruckner 已提交
1713
    }
M
Max Bruckner 已提交
1714

M
Max Bruckner 已提交
1715
    return get_array_item(array, (size_t)index);
M
Max Bruckner 已提交
1716 1717
}

1718
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
1719 1720 1721
{
    cJSON *current_element = NULL;

1722
    if ((object == NULL) || (name == NULL))
1723 1724 1725 1726 1727
    {
        return NULL;
    }

    current_element = object->child;
1728
    if (case_sensitive)
1729
    {
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
        while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
        {
            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;
        }
1741 1742 1743 1744 1745
    }

    return current_element;
}

1746
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
1747 1748 1749 1750 1751 1752 1753 1754 1755
{
    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);
}

1756
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1757 1758 1759
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1760 1761

/* Utility for array list handling. */
M
Max Bruckner 已提交
1762 1763 1764 1765 1766 1767
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1768
/* Utility for handling references. */
1769
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1770
{
1771 1772
    cJSON *reference = NULL;
    if (item == NULL)
M
Max Bruckner 已提交
1773
    {
1774
        return NULL;
M
Max Bruckner 已提交
1775
    }
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787

    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 已提交
1788
}
K
Kevin Branigan 已提交
1789 1790

/* Add item to array/object. */
1791
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1792
{
1793 1794 1795
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1796 1797 1798
    {
        return;
    }
1799 1800 1801 1802

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1803 1804 1805 1806 1807 1808 1809
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1810
        while (child->next)
M
Max Bruckner 已提交
1811
        {
1812
            child = child->next;
M
Max Bruckner 已提交
1813
        }
1814
        suffix_object(child, item);
M
Max Bruckner 已提交
1815 1816 1817
    }
}

1818
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1819
{
1820 1821 1822 1823 1824
    if (item == NULL)
    {
        return;
    }

1825
    /* call cJSON_AddItemToObjectCS for code reuse */
1826
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1827 1828
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1829 1830
}

1831 1832 1833
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
1834
#ifdef __GNUC__
1835
#pragma GCC diagnostic ignored "-Wcast-qual"
1836 1837
#endif

1838
/* Add an item to an object with constant string as key */
1839
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1840
{
1841
    if ((item == NULL) || (string == NULL))
1842 1843 1844 1845 1846
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1847
        global_hooks.deallocate(item->string);
1848 1849 1850 1851 1852
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}
1853 1854 1855
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1856

1857
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1858
{
1859 1860 1861 1862 1863
    if (array == NULL)
    {
        return;
    }

1864
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1865 1866
}

1867
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1868
{
1869 1870 1871 1872 1873
    if ((object == NULL) || (string == NULL))
    {
        return;
    }

1874
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1875 1876
}

M
Max Bruckner 已提交
1877
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
1878
{
M
Max Bruckner 已提交
1879
    if ((parent == NULL) || (item == NULL))
1880
    {
1881
        return NULL;
1882
    }
M
Max Bruckner 已提交
1883 1884

    if (item->prev != NULL)
1885 1886
    {
        /* not the first element */
M
Max Bruckner 已提交
1887
        item->prev->next = item->next;
1888
    }
M
Max Bruckner 已提交
1889
    if (item->next != NULL)
1890
    {
M
Max Bruckner 已提交
1891 1892
        /* not the last element */
        item->next->prev = item->prev;
1893
    }
M
Max Bruckner 已提交
1894 1895

    if (item == parent->child)
1896
    {
M
Max Bruckner 已提交
1897 1898
        /* first element */
        parent->child = item->next;
1899 1900
    }
    /* make sure the detached item doesn't point anywhere anymore */
M
Max Bruckner 已提交
1901 1902
    item->prev = NULL;
    item->next = NULL;
1903

M
Max Bruckner 已提交
1904
    return item;
1905
}
M
Max Bruckner 已提交
1906

1907
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1908 1909 1910 1911 1912 1913
{
    if (which < 0)
    {
        return NULL;
    }

M
Max Bruckner 已提交
1914
    return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
M
Max Bruckner 已提交
1915
}
K
Kevin Branigan 已提交
1916

1917
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1918 1919 1920 1921
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1922
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1923
{
1924
    cJSON *to_detach = cJSON_GetObjectItem(object, string);
1925

1926 1927 1928 1929 1930 1931
    return cJSON_DetachItemViaPointer(object, to_detach);
}

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

1933
    return cJSON_DetachItemViaPointer(object, to_detach);
1934 1935
}

1936
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1937 1938 1939
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1940

1941 1942 1943 1944 1945
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}

K
Kevin Branigan 已提交
1946
/* Replace array/object items with new ones. */
1947
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1948
{
M
Max Bruckner 已提交
1949 1950 1951
    cJSON *after_inserted = NULL;

    if (which < 0)
1952
    {
M
Max Bruckner 已提交
1953
        return;
1954
    }
M
Max Bruckner 已提交
1955 1956 1957

    after_inserted = get_array_item(array, (size_t)which);
    if (after_inserted == NULL)
1958 1959 1960 1961
    {
        cJSON_AddItemToArray(array, newitem);
        return;
    }
M
Max Bruckner 已提交
1962 1963 1964 1965 1966

    newitem->next = after_inserted;
    newitem->prev = after_inserted->prev;
    after_inserted->prev = newitem;
    if (after_inserted == array->child)
1967 1968 1969 1970 1971 1972 1973 1974 1975
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
}

M
Max Bruckner 已提交
1976
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
1977
{
1978
    if ((parent == NULL) || (replacement == NULL) || (item == NULL))
1979
    {
M
Max Bruckner 已提交
1980
        return false;
1981
    }
M
Max Bruckner 已提交
1982

M
Max Bruckner 已提交
1983
    if (replacement == item)
1984
    {
M
Max Bruckner 已提交
1985
        return true;
1986
    }
M
Max Bruckner 已提交
1987

M
Max Bruckner 已提交
1988 1989 1990 1991
    replacement->next = item->next;
    replacement->prev = item->prev;

    if (replacement->next != NULL)
1992
    {
M
Max Bruckner 已提交
1993
        replacement->next->prev = replacement;
1994
    }
M
Max Bruckner 已提交
1995
    if (replacement->prev != NULL)
1996
    {
M
Max Bruckner 已提交
1997
        replacement->prev->next = replacement;
1998
    }
M
Max Bruckner 已提交
1999
    if (parent->child == item)
2000
    {
M
Max Bruckner 已提交
2001
        parent->child = replacement;
2002
    }
M
Max Bruckner 已提交
2003

M
Max Bruckner 已提交
2004 2005 2006
    item->next = NULL;
    item->prev = NULL;
    cJSON_Delete(item);
M
Max Bruckner 已提交
2007

M
Max Bruckner 已提交
2008
    return true;
2009
}
M
Max Bruckner 已提交
2010

2011
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
2012 2013 2014 2015 2016 2017
{
    if (which < 0)
    {
        return;
    }

M
Max Bruckner 已提交
2018
    cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
M
Max Bruckner 已提交
2019
}
2020

2021 2022
static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
{
2023
    if ((replacement == NULL) || (string == NULL))
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
    {
        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;
}

2041
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
2042
{
2043
    replace_item_in_object(object, string, newitem, false);
2044
}
2045

2046 2047
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
2048
    replace_item_in_object(object, string, newitem, true);
2049
}
K
Kevin Branigan 已提交
2050 2051

/* Create basic types: */
2052
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
2053
{
2054
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2055 2056 2057 2058 2059 2060 2061 2062
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

2063
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
2064
{
2065
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2066 2067 2068 2069 2070 2071 2072 2073
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

2074
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
2075
{
2076
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2077 2078 2079 2080 2081 2082 2083 2084
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

2085
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
2086
{
2087
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2088 2089 2090 2091 2092 2093 2094 2095
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

2096
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
2097
{
2098
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2099 2100 2101 2102
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116

        /* use saturation in case of overflow */
        if (num >= INT_MAX)
        {
            item->valueint = INT_MAX;
        }
        else if (num <= INT_MIN)
        {
            item->valueint = INT_MIN;
        }
        else
        {
            item->valueint = (int)num;
        }
M
Max Bruckner 已提交
2117 2118 2119 2120 2121
    }

    return item;
}

2122
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
2123
{
2124
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2125 2126 2127
    if(item)
    {
        item->type = cJSON_String;
2128
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
2129 2130 2131
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2132
            return NULL;
M
Max Bruckner 已提交
2133 2134 2135 2136 2137 2138
        }
    }

    return item;
}

2139
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
2140
{
2141
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2142 2143 2144
    if(item)
    {
        item->type = cJSON_Raw;
2145
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
2146 2147 2148 2149 2150 2151 2152 2153
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2154 2155
}

2156
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
2157
{
2158
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2159 2160 2161 2162 2163 2164 2165 2166
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

2167
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
2168
{
2169
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2170 2171 2172 2173 2174 2175 2176
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2177 2178

/* Create Arrays: */
2179
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
2180
{
2181
    size_t i = 0;
2182 2183
    cJSON *n = NULL;
    cJSON *p = NULL;
2184 2185
    cJSON *a = NULL;

2186
    if ((count < 0) || (numbers == NULL))
2187 2188 2189 2190 2191 2192
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2193 2194 2195 2196 2197
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2198
            return NULL;
M
Max Bruckner 已提交
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2214
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
2215
{
2216
    size_t i = 0;
2217 2218
    cJSON *n = NULL;
    cJSON *p = NULL;
2219 2220
    cJSON *a = NULL;

2221
    if ((count < 0) || (numbers == NULL))
2222 2223 2224 2225 2226 2227 2228
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2229
    {
2230
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
2231 2232 2233
        if(!n)
        {
            cJSON_Delete(a);
2234
            return NULL;
M
Max Bruckner 已提交
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2250
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
2251
{
2252
    size_t i = 0;
2253 2254
    cJSON *n = NULL;
    cJSON *p = NULL;
2255 2256
    cJSON *a = NULL;

2257
    if ((count < 0) || (numbers == NULL))
2258 2259 2260 2261 2262 2263 2264
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2265 2266 2267 2268 2269
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2270
            return NULL;
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2286
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2287
{
2288
    size_t i = 0;
2289 2290
    cJSON *n = NULL;
    cJSON *p = NULL;
2291 2292
    cJSON *a = NULL;

2293
    if ((count < 0) || (strings == NULL))
2294 2295 2296 2297 2298 2299 2300
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2301 2302 2303 2304 2305
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2306
            return NULL;
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2321 2322

/* Duplication */
2323
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2324
{
M
Max Bruckner 已提交
2325
    cJSON *newitem = NULL;
2326 2327
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2328
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2329 2330 2331 2332

    /* Bail on bad ptr */
    if (!item)
    {
2333
        goto fail;
M
Max Bruckner 已提交
2334 2335
    }
    /* Create new item */
2336
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2337 2338
    if (!newitem)
    {
2339
        goto fail;
M
Max Bruckner 已提交
2340 2341 2342 2343 2344 2345 2346
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2347
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2348 2349
        if (!newitem->valuestring)
        {
2350
            goto fail;
M
Max Bruckner 已提交
2351 2352 2353 2354
        }
    }
    if (item->string)
    {
2355
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2356 2357
        if (!newitem->string)
        {
2358
            goto fail;
M
Max Bruckner 已提交
2359 2360 2361 2362 2363 2364 2365 2366
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2367 2368
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2369
    {
2370
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2371 2372
        if (!newchild)
        {
2373
            goto fail;
M
Max Bruckner 已提交
2374
        }
2375
        if (next != NULL)
M
Max Bruckner 已提交
2376 2377
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2378 2379 2380
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2381 2382 2383 2384
        }
        else
        {
            /* Set newitem->child and move to it */
2385 2386
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2387
        }
2388
        child = child->next;
M
Max Bruckner 已提交
2389 2390 2391
    }

    return newitem;
2392 2393 2394 2395 2396 2397 2398 2399

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

    return NULL;
2400
}
2401

2402
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2403
{
2404
    unsigned char *into = (unsigned char*)json;
2405 2406 2407 2408 2409 2410

    if (json == NULL)
    {
        return;
    }

M
Max Bruckner 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
    while (*json)
    {
        if (*json == ' ')
        {
            json++;
        }
        else if (*json == '\t')
        {
            /* Whitespace characters. */
            json++;
        }
        else if (*json == '\r')
        {
            json++;
        }
        else if (*json=='\n')
        {
            json++;
        }
        else if ((*json == '/') && (json[1] == '/'))
        {
            /* double-slash comments, to end of line. */
            while (*json && (*json != '\n'))
            {
                json++;
            }
        }
        else if ((*json == '/') && (json[1] == '*'))
        {
            /* multiline comments. */
            while (*json && !((*json == '*') && (json[1] == '/')))
            {
                json++;
            }
            json += 2;
        }
        else if (*json == '\"')
        {
            /* string literals, which are \" sensitive. */
M
Max Bruckner 已提交
2450
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2451 2452 2453 2454
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2455
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2456
                }
M
Max Bruckner 已提交
2457
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2458
            }
M
Max Bruckner 已提交
2459
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2460 2461 2462 2463
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2464
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2465 2466 2467 2468 2469
        }
    }

    /* and null-terminate. */
    *into = '\0';
2470
}
2471

2472
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2473 2474 2475 2476 2477 2478 2479 2480 2481
{
    if (item == NULL)
    {
        return false;
    }

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

2482
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2483 2484 2485 2486 2487 2488 2489 2490 2491
{
    if (item == NULL)
    {
        return false;
    }

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

2492
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
{
    if (item == NULL)
    {
        return false;
    }

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


2503
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2504 2505 2506 2507 2508 2509 2510 2511
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2512
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2513 2514 2515 2516 2517 2518 2519 2520 2521
{
    if (item == NULL)
    {
        return false;
    }

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

2522
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2523 2524 2525 2526 2527 2528 2529 2530 2531
{
    if (item == NULL)
    {
        return false;
    }

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

2532
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2533 2534 2535 2536 2537 2538 2539 2540 2541
{
    if (item == NULL)
    {
        return false;
    }

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

2542
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2543 2544 2545 2546 2547 2548 2549 2550 2551
{
    if (item == NULL)
    {
        return false;
    }

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

2552
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2553 2554 2555 2556 2557 2558 2559 2560 2561
{
    if (item == NULL)
    {
        return false;
    }

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

2562
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2563 2564 2565 2566 2567 2568 2569 2570
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Raw;
}
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631

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 已提交
2632 2633 2634 2635
            cJSON *a_element = a->child;
            cJSON *b_element = b->child;

            for (; (a_element != NULL) && (b_element != NULL);)
2636 2637 2638 2639 2640
            {
                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }
M
Max Bruckner 已提交
2641 2642 2643

                a_element = a_element->next;
                b_element = b_element->next;
2644 2645
            }

2646 2647 2648 2649 2650
            /* one of the arrays is longer than the other */
            if (a_element != b_element) {
                return false;
            }

2651 2652 2653 2654 2655 2656
            return true;
        }

        case cJSON_Object:
        {
            cJSON *a_element = NULL;
2657
            cJSON *b_element = NULL;
2658 2659 2660
            cJSON_ArrayForEach(a_element, a)
            {
                /* TODO This has O(n^2) runtime, which is horrible! */
2661
                b_element = get_object_item(b, a_element->string, case_sensitive);
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
                if (b_element == NULL)
                {
                    return false;
                }

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

2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
            /* 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;
                }
            }

2689 2690 2691 2692 2693 2694 2695
            return true;
        }

        default:
            return false;
    }
}
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705

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

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