cJSON.c 64.2 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
#ifdef __GNUC__
27
#pragma GCC visibility push(default)
28 29
#endif

K
Kevin Branigan 已提交
30 31 32 33 34 35 36
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
37
#include <locale.h>
38 39

#ifdef __GNUC__
40
#pragma GCC visibility pop
41
#endif
42

K
Kevin Branigan 已提交
43 44
#include "cJSON.h"

M
Max Bruckner 已提交
45
/* define our own boolean type */
46 47
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)
M
Max Bruckner 已提交
48

49 50 51 52 53
typedef struct {
    const unsigned char *json;
    size_t position;
} error;
static error global_error = { NULL, 0 };
K
Kevin Branigan 已提交
54

55
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
M
Max Bruckner 已提交
56
{
57
    return (const char*) (global_error.json + global_error.position);
M
Max Bruckner 已提交
58
}
K
Kevin Branigan 已提交
59

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

65
CJSON_PUBLIC(const char*) cJSON_Version(void)
66 67 68 69 70 71 72
{
    static char version[15];
    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

    return version;
}

73 74
/* 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 已提交
75
{
76
    if ((string1 == NULL) || (string2 == NULL))
M
Max Bruckner 已提交
77
    {
78
        return 1;
M
Max Bruckner 已提交
79
    }
80

81
    if (string1 == string2)
M
Max Bruckner 已提交
82
    {
83
        return 0;
M
Max Bruckner 已提交
84
    }
85 86

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
87
    {
88
        if (*string1 == '\0')
M
Max Bruckner 已提交
89 90 91 92 93
        {
            return 0;
        }
    }

94
    return tolower(*string1) - tolower(*string2);
K
Kevin Branigan 已提交
95 96
}

97 98 99 100 101 102 103 104
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 已提交
105

M
Max Bruckner 已提交
106
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
107
{
M
Max Bruckner 已提交
108
    size_t length = 0;
109
    unsigned char *copy = NULL;
K
Kevin Branigan 已提交
110

M
Max Bruckner 已提交
111
    if (string == NULL)
112 113 114 115
    {
        return NULL;
    }

M
Max Bruckner 已提交
116 117
    length = strlen((const char*)string) + sizeof("");
    if (!(copy = (unsigned char*)hooks->allocate(length)))
M
Max Bruckner 已提交
118
    {
119
        return NULL;
M
Max Bruckner 已提交
120
    }
M
Max Bruckner 已提交
121
    memcpy(copy, string, length);
M
Max Bruckner 已提交
122 123

    return copy;
K
Kevin Branigan 已提交
124 125
}

126
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
K
Kevin Branigan 已提交
127
{
M
Max Bruckner 已提交
128
    if (hooks == NULL)
M
Max Bruckner 已提交
129 130
    {
        /* Reset hooks */
131 132 133
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
K
Kevin Branigan 已提交
134 135 136
        return;
    }

137
    global_hooks.allocate = malloc;
M
Max Bruckner 已提交
138 139
    if (hooks->malloc_fn != NULL)
    {
140
        global_hooks.allocate = hooks->malloc_fn;
M
Max Bruckner 已提交
141 142
    }

143
    global_hooks.deallocate = free;
M
Max Bruckner 已提交
144 145
    if (hooks->free_fn != NULL)
    {
146
        global_hooks.deallocate = hooks->free_fn;
M
Max Bruckner 已提交
147 148 149
    }

    /* use realloc only if both free and malloc are used */
150 151
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
M
Max Bruckner 已提交
152
    {
153
        global_hooks.reallocate = realloc;
M
Max Bruckner 已提交
154
    }
K
Kevin Branigan 已提交
155 156 157
}

/* Internal constructor. */
158
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
K
Kevin Branigan 已提交
159
{
160
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
M
Max Bruckner 已提交
161 162
    if (node)
    {
163
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
164 165 166
    }

    return node;
K
Kevin Branigan 已提交
167 168 169
}

/* Delete a cJSON structure. */
M
Max Bruckner 已提交
170
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
K
Kevin Branigan 已提交
171
{
M
Max Bruckner 已提交
172
    cJSON *next = NULL;
M
Max Bruckner 已提交
173
    while (item != NULL)
M
Max Bruckner 已提交
174
    {
M
Max Bruckner 已提交
175 176
        next = item->next;
        if (!(item->type & cJSON_IsReference) && (item->child != NULL))
M
Max Bruckner 已提交
177
        {
M
Max Bruckner 已提交
178
            cJSON_Delete(item->child);
M
Max Bruckner 已提交
179
        }
M
Max Bruckner 已提交
180
        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
M
Max Bruckner 已提交
181
        {
M
Max Bruckner 已提交
182
            global_hooks.deallocate(item->valuestring);
M
Max Bruckner 已提交
183
        }
M
Max Bruckner 已提交
184
        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
M
Max Bruckner 已提交
185
        {
M
Max Bruckner 已提交
186
            global_hooks.deallocate(item->string);
M
Max Bruckner 已提交
187
        }
M
Max Bruckner 已提交
188 189
        global_hooks.deallocate(item);
        item = next;
M
Max Bruckner 已提交
190
    }
K
Kevin Branigan 已提交
191 192
}

193 194 195 196 197 198 199
/* 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 已提交
200 201 202 203 204
typedef struct
{
    const unsigned char *content;
    size_t length;
    size_t offset;
205
    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
M
Max Bruckner 已提交
206 207 208 209 210 211 212 213 214 215 216
} 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))
#define cannot_read(buffer, size) (!can_read(buffer, size))
/* 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 已提交
217
/* Parse the input text to generate a number, and populate the result into item. */
218
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
K
Kevin Branigan 已提交
219
{
220
    double number = 0;
221
    unsigned char *after_end = NULL;
222 223 224
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;
M
Max Bruckner 已提交
225

M
Max Bruckner 已提交
226
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
227
    {
228
        return false;
229 230
    }

231
    /* copy the number into a temporary buffer and replace '.' with the decimal point
M
Max Bruckner 已提交
232 233 234
     * 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++)
235
    {
M
Max Bruckner 已提交
236
        switch (buffer_at_offset(input_buffer)[i])
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        {
            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 已提交
252
                number_c_string[i] = buffer_at_offset(input_buffer)[i];
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                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 已提交
268
    {
269
        return false; /* parse_error */
M
Max Bruckner 已提交
270 271
    }

272
    item->valuedouble = number;
M
Max Bruckner 已提交
273

274
    /* use saturation in case of overflow */
275
    if (number >= INT_MAX)
276 277 278
    {
        item->valueint = INT_MAX;
    }
279
    else if (number <= INT_MIN)
280 281 282 283 284
    {
        item->valueint = INT_MIN;
    }
    else
    {
285
        item->valueint = (int)number;
286
    }
287

M
Max Bruckner 已提交
288 289
    item->type = cJSON_Number;

M
Max Bruckner 已提交
290
    input_buffer->offset += (size_t)(after_end - number_c_string);
291
    return true;
K
Kevin Branigan 已提交
292 293
}

294
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
295
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
296 297 298 299 300 301 302 303 304 305 306
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
307
        object->valueint = (int)number;
308 309 310 311 312
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
313 314
typedef struct
{
315
    unsigned char *buffer;
316 317
    size_t length;
    size_t offset;
M
Max Bruckner 已提交
318
    size_t depth; /* current nesting depth (for formatted printing) */
319
    cJSON_bool noalloc;
M
Max Bruckner 已提交
320
} printbuffer;
321

M
Max Bruckner 已提交
322
/* realloc printbuffer if necessary to have at least "needed" bytes more */
323
static unsigned char* ensure(printbuffer * const p, size_t needed, const internal_hooks * const hooks)
324
{
325
    unsigned char *newbuffer = NULL;
326 327
    size_t newsize = 0;

328
    if ((p == NULL) || (p->buffer == NULL))
329 330 331 332
    {
        return NULL;
    }

M
Max Bruckner 已提交
333 334 335 336 337 338
    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

339
    if (needed > INT_MAX)
M
Max Bruckner 已提交
340
    {
341
        /* sizes bigger than INT_MAX are currently not supported */
342
        return NULL;
M
Max Bruckner 已提交
343
    }
344

345
    needed += p->offset + 1;
M
Max Bruckner 已提交
346 347 348 349 350
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

351 352 353 354
    if (p->noalloc) {
        return NULL;
    }

355
    /* calculate new buffer size */
M
Max Bruckner 已提交
356
    if (needed > (INT_MAX / 2))
357 358 359 360 361 362 363 364 365 366 367
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
368 369 370 371
    else
    {
        newsize = needed * 2;
    }
372

373
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
374
    {
M
Max Bruckner 已提交
375
        /* reallocate with realloc if available */
376
        newbuffer = (unsigned char*)hooks->reallocate(p->buffer, newsize);
M
Max Bruckner 已提交
377
    }
M
Max Bruckner 已提交
378
    else
M
Max Bruckner 已提交
379
    {
M
Max Bruckner 已提交
380
        /* otherwise reallocate manually */
381
        newbuffer = (unsigned char*)hooks->allocate(newsize);
M
Max Bruckner 已提交
382 383
        if (!newbuffer)
        {
384
            hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
385 386 387 388 389 390 391
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
392
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
393
        }
394
        hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
395 396 397 398 399
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
400 401
}

402 403
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
404
{
405 406
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
407
    {
408
        return;
M
Max Bruckner 已提交
409
    }
410
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
411

412
    buffer->offset += strlen((const char*)buffer_pointer);
413 414
}

415
/* Removes trailing zeroes from the end of a printed number */
416
static int trim_trailing_zeroes(const unsigned char * const number, int length, const unsigned char decimal_point)
K
Kevin Branigan 已提交
417
{
418
    if ((number == NULL) || (length <= 0))
419
    {
420
        return -1;
421 422
    }

423
    while ((length > 0) && (number[length - 1] == '0'))
M
Max Bruckner 已提交
424
    {
425
        length--;
M
Max Bruckner 已提交
426
    }
427
    if ((length > 0) && (number[length - 1] == decimal_point))
428
    {
429 430
        /* remove trailing decimal_point */
        length--;
431 432
    }

433
    return length;
434 435 436
}

/* Render the number nicely from the given item into a string. */
437
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
438
{
M
Max Bruckner 已提交
439
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
440
    double d = item->valuedouble;
441
    int length = 0;
442
    size_t i = 0;
443
    cJSON_bool trim_zeroes = true; /* should zeroes at the end be removed? */
444 445
    unsigned char number_buffer[64]; /* temporary buffer to print the number into */
    unsigned char decimal_point = get_decimal_point();
M
Max Bruckner 已提交
446

M
Max Bruckner 已提交
447
    if (output_buffer == NULL)
M
Max Bruckner 已提交
448
    {
449
        return false;
M
Max Bruckner 已提交
450
    }
M
Max Bruckner 已提交
451

452 453 454
    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
455
        length = sprintf((char*)number_buffer, "null");
456 457 458 459
    }
    else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
    {
        /* integer */
460
        length = sprintf((char*)number_buffer, "%.0f", d);
461 462 463 464
        trim_zeroes = false; /* don't remove zeroes for "big integers" */
    }
    else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
    {
465
        length = sprintf((char*)number_buffer, "%e", d);
466 467 468 469
        trim_zeroes = false; /* don't remove zeroes in engineering notation */
    }
    else
    {
470
        length = sprintf((char*)number_buffer, "%f", d);
M
Max Bruckner 已提交
471
    }
472

473 474
    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
475
    {
476
        return false;
477 478
    }

479 480
    if (trim_zeroes)
    {
481 482 483 484 485 486 487 488 489 490 491 492
        length = trim_trailing_zeroes(number_buffer, length, decimal_point);
        if (length <= 0)
        {
            return false;
        }
    }

    /* reserve appropriate space in the output */
    output_pointer = ensure(output_buffer, (size_t)length, hooks);
    if (output_pointer == NULL)
    {
        return false;
493 494
    }

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    /* 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;

511
    return true;
K
Kevin Branigan 已提交
512 513
}

M
Max Bruckner 已提交
514
/* parse 4 digit hexadecimal number */
515
static unsigned parse_hex4(const unsigned char * const input)
516
{
M
Max Bruckner 已提交
517
    unsigned int h = 0;
518
    size_t i = 0;
M
Max Bruckner 已提交
519

520
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
521
    {
522
        /* parse digit */
523
        if ((input[i] >= '0') && (input[i] <= '9'))
524
        {
525
            h += (unsigned int) input[i] - '0';
526
        }
527
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
528
        {
529
            h += (unsigned int) 10 + input[i] - 'A';
530
        }
531
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
532
        {
533
            h += (unsigned int) 10 + input[i] - 'a';
534 535 536 537 538
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
539

540 541 542 543 544
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
545 546 547
    }

    return h;
548 549
}

550 551
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
552
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 已提交
553
{
554 555 556
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
557
    unsigned char utf8_length = 0;
558
    unsigned char utf8_position = 0;
559
    unsigned char sequence_length = 0;
560
    unsigned char first_byte_mark = 0;
561 562 563 564 565 566

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

568 569 570
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

571
    /* check that the code is valid */
572
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
M
Max Bruckner 已提交
573
    {
574
        goto fail;
M
Max Bruckner 已提交
575
    }
M
Max Bruckner 已提交
576

577 578
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
579
    {
580 581 582 583 584
        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 已提交
585
        {
586 587
            /* input ends unexpectedly */
            goto fail;
M
Max Bruckner 已提交
588
        }
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

        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 已提交
613
    }
M
Max Bruckner 已提交
614

615 616 617 618 619 620 621 622 623 624 625 626
    /* 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;
627
        first_byte_mark = 0xC0; /* 11000000 */
628 629 630 631 632
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
633
        first_byte_mark = 0xE0; /* 11100000 */
634 635 636 637 638
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
639
        first_byte_mark = 0xF0; /* 11110000 */
640 641
    }
    else
M
Max Bruckner 已提交
642
    {
643
        /* invalid unicode codepoint */
644
        goto fail;
M
Max Bruckner 已提交
645 646
    }

647
    /* encode as utf8 */
648 649 650 651 652
    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;
653
    }
654 655 656 657 658 659 660 661
    /* 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);
662
    }
663

664 665 666 667 668 669 670 671 672
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
673
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks)
674
{
M
Max Bruckner 已提交
675 676
    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
677 678 679 680
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
M
Max Bruckner 已提交
681
    if (buffer_at_offset(input_buffer)[0] != '\"')
682 683 684 685 686 687 688 689
    {
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
M
Max Bruckner 已提交
690
        while ((*input_end != '\"') && ((size_t)(input_end - input_buffer->content) < input_buffer->length))
691 692 693 694
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
M
Max Bruckner 已提交
695
                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
696 697 698 699 700 701 702 703 704
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
M
Max Bruckner 已提交
705
        if (*input_end != '\"')
706 707 708 709 710
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
M
Max Bruckner 已提交
711
        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
712
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof(""));
713 714 715 716 717 718 719
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
720
    /* loop through the string literal */
721
    while (input_pointer < input_end)
M
Max Bruckner 已提交
722
    {
723
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
724
        {
725
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
726 727 728 729
        }
        /* escape sequence */
        else
        {
730
            unsigned char sequence_length = 2;
M
Max Bruckner 已提交
731 732 733 734 735
            if ((input_end - input_pointer) < 1)
            {
                goto fail;
            }

736
            switch (input_pointer[1])
M
Max Bruckner 已提交
737 738
            {
                case 'b':
739
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
740 741
                    break;
                case 'f':
742
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
743 744
                    break;
                case 'n':
745
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
746 747
                    break;
                case 'r':
748
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
749 750
                    break;
                case 't':
751
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
752
                    break;
753 754 755
                case '\"':
                case '\\':
                case '/':
756
                    *output_pointer++ = input_pointer[1];
757
                    break;
758 759

                /* UTF-16 literal */
M
Max Bruckner 已提交
760
                case 'u':
761
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
762
                    if (sequence_length == 0)
M
Max Bruckner 已提交
763
                    {
764
                        /* failed to convert UTF16-literal to UTF-8 */
765
                        goto fail;
M
Max Bruckner 已提交
766 767
                    }
                    break;
768

M
Max Bruckner 已提交
769
                default:
770
                    goto fail;
M
Max Bruckner 已提交
771
            }
772
            input_pointer += sequence_length;
M
Max Bruckner 已提交
773 774
        }
    }
775 776 777

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

779
    item->type = cJSON_String;
780
    item->valuestring = (char*)output;
781

M
Max Bruckner 已提交
782 783 784
    input_buffer->offset = (size_t) (input_end - input_buffer->content);
    input_buffer->offset++;

785
    return true;
786 787

fail:
788
    if (output != NULL)
789
    {
790
        hooks->deallocate(output);
791 792
    }

793 794 795 796 797
    if (input_pointer != NULL)
    {
        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
    }

798
    return false;
K
Kevin Branigan 已提交
799 800 801
}

/* Render the cstring provided to an escaped version that can be printed. */
802
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
803
{
804 805 806
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
807 808 809
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
810

811
    if (output_buffer == NULL)
M
Max Bruckner 已提交
812
    {
813
        return false;
M
Max Bruckner 已提交
814 815 816
    }

    /* empty string */
817
    if (input == NULL)
M
Max Bruckner 已提交
818
    {
819
        output = ensure(output_buffer, sizeof("\"\""), hooks);
820
        if (output == NULL)
M
Max Bruckner 已提交
821
        {
822
            return false;
M
Max Bruckner 已提交
823
        }
824
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
825

826
        return true;
M
Max Bruckner 已提交
827 828 829
    }

    /* set "flag" to 1 if something needs to be escaped */
830
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
831
    {
M
Max Bruckner 已提交
832
        switch (*input_pointer)
M
Max Bruckner 已提交
833
        {
M
Max Bruckner 已提交
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
            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 已提交
851 852
        }
    }
M
Max Bruckner 已提交
853
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
854

855
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
856
    if (output == NULL)
M
Max Bruckner 已提交
857
    {
858
        return false;
M
Max Bruckner 已提交
859 860
    }

M
Max Bruckner 已提交
861 862
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
863
    {
M
Max Bruckner 已提交
864 865 866 867 868
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

869
        return true;
M
Max Bruckner 已提交
870 871
    }

M
Max Bruckner 已提交
872 873
    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
874
    /* copy the string */
M
Max Bruckner 已提交
875
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
876
    {
877
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
878 879
        {
            /* normal character, copy */
M
Max Bruckner 已提交
880
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
881 882 883 884
        }
        else
        {
            /* character needs to be escaped */
885
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
886
            switch (*input_pointer)
M
Max Bruckner 已提交
887 888
            {
                case '\\':
M
Max Bruckner 已提交
889
                    *output_pointer = '\\';
M
Max Bruckner 已提交
890 891
                    break;
                case '\"':
M
Max Bruckner 已提交
892
                    *output_pointer = '\"';
M
Max Bruckner 已提交
893 894
                    break;
                case '\b':
M
Max Bruckner 已提交
895
                    *output_pointer = 'b';
M
Max Bruckner 已提交
896 897
                    break;
                case '\f':
M
Max Bruckner 已提交
898
                    *output_pointer = 'f';
M
Max Bruckner 已提交
899 900
                    break;
                case '\n':
M
Max Bruckner 已提交
901
                    *output_pointer = 'n';
M
Max Bruckner 已提交
902 903
                    break;
                case '\r':
M
Max Bruckner 已提交
904
                    *output_pointer = 'r';
M
Max Bruckner 已提交
905 906
                    break;
                case '\t':
M
Max Bruckner 已提交
907
                    *output_pointer = 't';
M
Max Bruckner 已提交
908 909 910
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
911 912
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
913 914 915 916
                    break;
            }
        }
    }
M
Max Bruckner 已提交
917 918
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
919

920
    return true;
K
Kevin Branigan 已提交
921
}
M
Max Bruckner 已提交
922

M
Max Bruckner 已提交
923
/* Invoke print_string_ptr (which is useful) on an item. */
924
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
925
{
926
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
927
}
K
Kevin Branigan 已提交
928 929

/* Predeclare these prototypes. */
930
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks);
M
Max Bruckner 已提交
931
static cJSON_bool print_value(const cJSON * const item, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
932
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks);
M
Max Bruckner 已提交
933
static cJSON_bool print_array(const cJSON * const item, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
934
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks);
M
Max Bruckner 已提交
935
static cJSON_bool print_object(const cJSON * const item, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
K
Kevin Branigan 已提交
936 937

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
938 939 940 941 942 943 944
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
{
    if ((buffer == NULL) || (buffer->content == NULL))
    {
        return NULL;
    }

M
Max Bruckner 已提交
945 946 947 948 949 950 951 952 953
    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
    {
       buffer->offset++;
    }

    if (buffer->offset == buffer->length)
    {
        buffer->offset--;
    }
M
Max Bruckner 已提交
954 955 956 957

    return buffer;
}

K
Kevin Branigan 已提交
958
/* Parse an object - create a new root, and populate. */
959
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
960
{
961
    parse_buffer buffer = { 0, 0, 0, 0 };
962
    cJSON *item = NULL;
963 964 965 966

    /* reset error position */
    global_error.json = NULL;
    global_error.position = 0;
967 968 969 970

    if (value == NULL)
    {
        goto fail;
M
Max Bruckner 已提交
971 972
    }

M
Max Bruckner 已提交
973 974 975 976
    buffer.content = (const unsigned char*)value;
    buffer.length = strlen((const char*)value) + sizeof("");
    buffer.offset = 0;

977 978 979 980 981 982 983
    item = cJSON_New_Item(&global_hooks);
    if (item == NULL) /* memory fail */
    {
        goto fail;
    }

    if (!parse_value(item, buffer_skip_whitespace(&buffer), &global_hooks))
M
Max Bruckner 已提交
984 985
    {
        /* parse failure. ep is set. */
986
        goto fail;
M
Max Bruckner 已提交
987 988 989 990 991
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
992 993
        buffer_skip_whitespace(&buffer);
        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
M
Max Bruckner 已提交
994
        {
995
            goto fail;
M
Max Bruckner 已提交
996 997 998 999
        }
    }
    if (return_parse_end)
    {
1000
        *return_parse_end = (const char*)buffer_at_offset(&buffer);
M
Max Bruckner 已提交
1001 1002
    }

1003
    return item;
1004 1005 1006 1007 1008 1009 1010

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

1011 1012
    if (value != NULL)
    {
1013 1014 1015 1016
        error local_error;
        local_error.json = (const unsigned char*)value;
        local_error.position = 0;

1017 1018
        if (buffer.offset < buffer.length)
        {
1019
            local_error.position = buffer.offset;
1020 1021 1022
        }
        else if (buffer.length > 0)
        {
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            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;
1033 1034 1035
        }
    }

1036
    return NULL;
K
Kevin Branigan 已提交
1037
}
M
Max Bruckner 已提交
1038

1039
/* Default options for cJSON_Parse */
1040
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
1041 1042 1043
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
1044

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

1047
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1048 1049 1050 1051 1052 1053 1054
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
1055
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
1056 1057 1058 1059 1060 1061
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
M
Max Bruckner 已提交
1062
    if (!print_value(item, format, buffer, hooks))
M
Max Bruckner 已提交
1063 1064 1065
    {
        goto fail;
    }
1066
    update_offset(buffer);
M
Max Bruckner 已提交
1067

1068 1069
    /* check if reallocate is available */
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
1070
    {
1071 1072 1073 1074 1075
        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->length);
        buffer->buffer = NULL;
        if (printed == NULL) {
            goto fail;
        }
M
Max Bruckner 已提交
1076
    }
1077 1078 1079 1080 1081 1082 1083
    else /* otherwise copy the JSON over to a new buffer */
    {
        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
        if (printed == NULL)
        {
            goto fail;
        }
1084
        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
1085
        printed[buffer->offset] = '\0'; /* just to be sure */
M
Max Bruckner 已提交
1086

1087 1088 1089
        /* free the buffer */
        hooks->deallocate(buffer->buffer);
    }
M
Max Bruckner 已提交
1090 1091 1092 1093 1094 1095

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
1096
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
1097 1098 1099 1100
    }

    if (printed != NULL)
    {
1101
        hooks->deallocate(printed);
M
Max Bruckner 已提交
1102 1103 1104 1105 1106
    }

    return NULL;
}

K
Kevin Branigan 已提交
1107
/* Render a cJSON item/entity/structure to text. */
1108
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
1109
{
1110
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
1111 1112
}

1113
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
1114
{
1115
    return (char*)print(item, false, &global_hooks);
1116
}
1117

1118
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
1119
{
M
Max Bruckner 已提交
1120
    printbuffer p = { 0, 0, 0, 0, 0 };
M
Max Bruckner 已提交
1121 1122 1123

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
1124
        return NULL;
M
Max Bruckner 已提交
1125 1126
    }

1127
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
1128 1129
    if (!p.buffer)
    {
1130
        return NULL;
1131
    }
M
Max Bruckner 已提交
1132 1133

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
1134
    p.offset = 0;
1135
    p.noalloc = false;
M
Max Bruckner 已提交
1136

M
Max Bruckner 已提交
1137
    if (!print_value(item, fmt, &p, &global_hooks))
1138 1139 1140 1141 1142
    {
        return NULL;
    }

    return (char*)p.buffer;
1143 1144
}

1145
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
1146
{
M
Max Bruckner 已提交
1147
    printbuffer p = { 0, 0, 0, 0, 0 };
M
Max Bruckner 已提交
1148 1149 1150 1151 1152 1153

    if (len < 0)
    {
        return false;
    }

1154
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
1155
    p.length = (size_t)len;
1156
    p.offset = 0;
1157
    p.noalloc = true;
M
Max Bruckner 已提交
1158
    return print_value(item, fmt, &p, &global_hooks);
1159
}
K
Kevin Branigan 已提交
1160 1161

/* Parser core - when encountering text, process appropriately. */
1162
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1163
{
M
Max Bruckner 已提交
1164
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
M
Max Bruckner 已提交
1165
    {
1166
        return false; /* no input */
M
Max Bruckner 已提交
1167 1168 1169
    }

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

M
Max Bruckner 已提交
1213

1214
    return false;
K
Kevin Branigan 已提交
1215 1216 1217
}

/* Render a value to text. */
M
Max Bruckner 已提交
1218
static cJSON_bool print_value(const cJSON * const item, const cJSON_bool format,  printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1219
{
M
Max Bruckner 已提交
1220
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1221

M
Max Bruckner 已提交
1222
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1223
    {
1224
        return false;
M
Max Bruckner 已提交
1225
    }
M
Max Bruckner 已提交
1226 1227

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1228
    {
M
Max Bruckner 已提交
1229
        case cJSON_NULL:
1230
            output = ensure(output_buffer, 5, hooks);
1231
            if (output == NULL)
M
Max Bruckner 已提交
1232
            {
1233
                return false;
M
Max Bruckner 已提交
1234
            }
1235 1236 1237
            strcpy((char*)output, "null");
            return true;

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

M
Max Bruckner 已提交
1247
        case cJSON_True:
1248
            output = ensure(output_buffer, 5, hooks);
1249
            if (output == NULL)
M
Max Bruckner 已提交
1250
            {
1251
                return false;
M
Max Bruckner 已提交
1252
            }
1253 1254 1255
            strcpy((char*)output, "true");
            return true;

M
Max Bruckner 已提交
1256
        case cJSON_Number:
1257
            return print_number(item, output_buffer, hooks);
1258

M
Max Bruckner 已提交
1259
        case cJSON_Raw:
M
Max Bruckner 已提交
1260
        {
M
Max Bruckner 已提交
1261 1262
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1263
            {
M
Max Bruckner 已提交
1264
                if (!output_buffer->noalloc)
1265
                {
1266
                    hooks->deallocate(output_buffer->buffer);
1267
                }
1268
                return false;
M
Max Bruckner 已提交
1269
            }
1270

1271
            raw_length = strlen(item->valuestring) + sizeof("");
1272
            output = ensure(output_buffer, raw_length, hooks);
1273
            if (output == NULL)
M
Max Bruckner 已提交
1274
            {
1275
                return false;
1276
            }
1277 1278
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1279
        }
1280

M
Max Bruckner 已提交
1281
        case cJSON_String:
1282
            return print_string(item, output_buffer, hooks);
1283

M
Max Bruckner 已提交
1284
        case cJSON_Array:
M
Max Bruckner 已提交
1285
            return print_array(item, format, output_buffer, hooks);
1286

M
Max Bruckner 已提交
1287
        case cJSON_Object:
M
Max Bruckner 已提交
1288
            return print_object(item, format, output_buffer, hooks);
1289

M
Max Bruckner 已提交
1290
        default:
1291
            return false;
M
Max Bruckner 已提交
1292
    }
K
Kevin Branigan 已提交
1293 1294 1295
}

/* Build an array from input text. */
1296
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1297
{
1298
    cJSON *head = NULL; /* head of the linked list */
1299 1300
    cJSON *current_item = NULL;

1301 1302 1303 1304 1305 1306
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1307
    if (buffer_at_offset(input_buffer)[0] != '[')
M
Max Bruckner 已提交
1308
    {
1309
        /* not an array */
1310
        goto fail;
M
Max Bruckner 已提交
1311
    }
K
Kevin Branigan 已提交
1312

M
Max Bruckner 已提交
1313 1314 1315
    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 已提交
1316
    {
1317
        /* empty array */
1318
        goto success;
M
Max Bruckner 已提交
1319
    }
K
Kevin Branigan 已提交
1320

M
Max Bruckner 已提交
1321 1322 1323 1324 1325 1326 1327
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1328
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1329
    input_buffer->offset--;
M
Max Bruckner 已提交
1330
    /* loop through the comma separated array elements */
1331
    do
M
Max Bruckner 已提交
1332
    {
1333
        /* allocate next item */
1334
        cJSON *new_item = cJSON_New_Item(hooks);
1335
        if (new_item == NULL)
M
Max Bruckner 已提交
1336
        {
1337
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1338
        }
1339 1340 1341

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1342
        {
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
            /* 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 已提交
1355 1356
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1357
        if (!parse_value(current_item, input_buffer, hooks))
1358 1359
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1360
        }
M
Max Bruckner 已提交
1361
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1362
    }
M
Max Bruckner 已提交
1363
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
M
Max Bruckner 已提交
1364

M
Max Bruckner 已提交
1365
    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
M
Max Bruckner 已提交
1366
    {
1367
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1368 1369
    }

1370
success:
1371 1372
    input_buffer->depth--;

1373
    item->type = cJSON_Array;
1374
    item->child = head;
1375

M
Max Bruckner 已提交
1376 1377
    input_buffer->offset++;

1378
    return true;
K
Kevin Branigan 已提交
1379

1380
fail:
1381
    if (head != NULL)
1382
    {
1383
        cJSON_Delete(head);
1384 1385
    }

1386
    return false;
K
Kevin Branigan 已提交
1387 1388 1389
}

/* Render an array to text */
M
Max Bruckner 已提交
1390
static cJSON_bool print_array(const cJSON * const item, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1391
{
M
Max Bruckner 已提交
1392
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1393
    size_t length = 0;
M
Max Bruckner 已提交
1394
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1395

M
Max Bruckner 已提交
1396
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1397
    {
1398
        return false;
M
Max Bruckner 已提交
1399 1400
    }

M
Max Bruckner 已提交
1401 1402
    /* Compose the output array. */
    /* opening square bracket */
1403
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1404
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1405
    {
1406
        return false;
M
Max Bruckner 已提交
1407 1408
    }

M
Max Bruckner 已提交
1409 1410
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1411
    output_buffer->depth++;
M
Max Bruckner 已提交
1412

M
Max Bruckner 已提交
1413
    while (current_element != NULL)
M
Max Bruckner 已提交
1414
    {
M
Max Bruckner 已提交
1415
        if (!print_value(current_element, format, output_buffer, hooks))
M
Max Bruckner 已提交
1416
        {
1417
            return false;
M
Max Bruckner 已提交
1418
        }
1419
        update_offset(output_buffer);
M
Max Bruckner 已提交
1420
        if (current_element->next)
M
Max Bruckner 已提交
1421
        {
1422
            length = (size_t) (format ? 2 : 1);
1423
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1424
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1425
            {
1426
                return false;
M
Max Bruckner 已提交
1427
            }
M
Max Bruckner 已提交
1428 1429
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1430
            {
M
Max Bruckner 已提交
1431
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1432
            }
M
Max Bruckner 已提交
1433 1434
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1435
        }
M
Max Bruckner 已提交
1436
        current_element = current_element->next;
M
Max Bruckner 已提交
1437 1438
    }

1439
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1440
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1441
    {
1442
        return false;
M
Max Bruckner 已提交
1443
    }
M
Max Bruckner 已提交
1444 1445
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1446
    output_buffer->depth--;
M
Max Bruckner 已提交
1447

1448
    return true;
K
Kevin Branigan 已提交
1449 1450 1451
}

/* Build an object from the text. */
1452
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1453
{
1454
    cJSON *head = NULL; /* linked list head */
1455 1456
    cJSON *current_item = NULL;

1457 1458 1459 1460 1461 1462
    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

M
Max Bruckner 已提交
1463
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
M
Max Bruckner 已提交
1464
    {
1465
        goto fail; /* not an object */
M
Max Bruckner 已提交
1466 1467
    }

M
Max Bruckner 已提交
1468 1469 1470
    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 已提交
1471
    {
1472
        goto success; /* empty object */
M
Max Bruckner 已提交
1473 1474
    }

M
Max Bruckner 已提交
1475 1476 1477 1478 1479 1480 1481
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

1482
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1483
    input_buffer->offset--;
1484 1485
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1486
    {
1487
        /* allocate next item */
1488
        cJSON *new_item = cJSON_New_Item(hooks);
1489 1490 1491 1492
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1493

1494 1495
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1496
        {
1497 1498 1499 1500 1501 1502 1503 1504 1505
            /* 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 已提交
1506 1507
        }

1508
        /* parse the name of the child */
M
Max Bruckner 已提交
1509 1510
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1511
        if (!parse_string(current_item, input_buffer, hooks))
M
Max Bruckner 已提交
1512
        {
1513
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1514
        }
M
Max Bruckner 已提交
1515
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1516

1517 1518 1519
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1520

M
Max Bruckner 已提交
1521
        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
M
Max Bruckner 已提交
1522
        {
1523
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1524
        }
1525 1526

        /* parse the value */
M
Max Bruckner 已提交
1527 1528
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
1529
        if (!parse_value(current_item, input_buffer, hooks))
M
Max Bruckner 已提交
1530
        {
1531
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1532
        }
M
Max Bruckner 已提交
1533
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1534
    }
M
Max Bruckner 已提交
1535
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
1536

M
Max Bruckner 已提交
1537
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
M
Max Bruckner 已提交
1538
    {
1539
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1540 1541
    }

1542
success:
1543 1544
    input_buffer->depth--;

1545
    item->type = cJSON_Object;
1546
    item->child = head;
1547

M
Max Bruckner 已提交
1548
    input_buffer->offset++;
1549
    return true;
1550 1551

fail:
1552
    if (head != NULL)
1553
    {
1554
        cJSON_Delete(head);
1555 1556
    }

1557
    return false;
K
Kevin Branigan 已提交
1558 1559 1560
}

/* Render an object to text. */
M
Max Bruckner 已提交
1561
static cJSON_bool print_object(const cJSON * const item, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
1562
{
M
Max Bruckner 已提交
1563
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1564
    size_t length = 0;
M
Max Bruckner 已提交
1565
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1566

M
Max Bruckner 已提交
1567
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1568
    {
1569
        return false;
M
Max Bruckner 已提交
1570 1571
    }

M
Max Bruckner 已提交
1572
    /* Compose the output: */
1573
    length = (size_t) (format ? 2 : 1); /* fmt: {\n */
1574
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1575
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1576
    {
1577
        return false;
M
Max Bruckner 已提交
1578 1579
    }

M
Max Bruckner 已提交
1580
    *output_pointer++ = '{';
M
Max Bruckner 已提交
1581
    output_buffer->depth++;
M
Max Bruckner 已提交
1582
    if (format)
M
Max Bruckner 已提交
1583
    {
M
Max Bruckner 已提交
1584
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1585
    }
M
Max Bruckner 已提交
1586
    output_buffer->offset += length;
M
Max Bruckner 已提交
1587

M
Max Bruckner 已提交
1588
    while (current_item)
M
Max Bruckner 已提交
1589
    {
M
Max Bruckner 已提交
1590
        if (format)
M
Max Bruckner 已提交
1591
        {
M
Max Bruckner 已提交
1592
            size_t i;
M
Max Bruckner 已提交
1593
            output_pointer = ensure(output_buffer, output_buffer->depth, hooks);
M
Max Bruckner 已提交
1594
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1595
            {
1596
                return false;
M
Max Bruckner 已提交
1597
            }
M
Max Bruckner 已提交
1598
            for (i = 0; i < output_buffer->depth; i++)
M
Max Bruckner 已提交
1599
            {
M
Max Bruckner 已提交
1600
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1601
            }
M
Max Bruckner 已提交
1602
            output_buffer->offset += output_buffer->depth;
M
Max Bruckner 已提交
1603 1604
        }

M
Max Bruckner 已提交
1605
        /* print key */
1606
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks))
M
Max Bruckner 已提交
1607
        {
1608
            return false;
M
Max Bruckner 已提交
1609
        }
M
Max Bruckner 已提交
1610
        update_offset(output_buffer);
M
Max Bruckner 已提交
1611

1612
        length = (size_t) (format ? 2 : 1);
1613
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1614
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1615
        {
1616
            return false;
M
Max Bruckner 已提交
1617
        }
M
Max Bruckner 已提交
1618 1619
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1620
        {
M
Max Bruckner 已提交
1621
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1622
        }
M
Max Bruckner 已提交
1623
        output_buffer->offset += length;
M
Max Bruckner 已提交
1624

M
Max Bruckner 已提交
1625
        /* print value */
M
Max Bruckner 已提交
1626
        if (!print_value(current_item, format, output_buffer, hooks))
M
Max Bruckner 已提交
1627
        {
1628
            return false;
M
Max Bruckner 已提交
1629
        }
M
Max Bruckner 已提交
1630
        update_offset(output_buffer);
M
Max Bruckner 已提交
1631

M
Max Bruckner 已提交
1632
        /* print comma if not last */
1633
        length = (size_t) ((format ? 1 : 0) + (current_item->next ? 1 : 0));
1634
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1635
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1636
        {
1637
            return false;
M
Max Bruckner 已提交
1638
        }
M
Max Bruckner 已提交
1639
        if (current_item->next)
M
Max Bruckner 已提交
1640
        {
M
Max Bruckner 已提交
1641
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1642 1643
        }

M
Max Bruckner 已提交
1644
        if (format)
M
Max Bruckner 已提交
1645
        {
M
Max Bruckner 已提交
1646
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1647
        }
M
Max Bruckner 已提交
1648 1649
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1650

M
Max Bruckner 已提交
1651
        current_item = current_item->next;
M
Max Bruckner 已提交
1652
    }
M
Max Bruckner 已提交
1653

M
Max Bruckner 已提交
1654
    output_pointer = ensure(output_buffer, format ? (output_buffer->depth + 1) : 2, hooks);
M
Max Bruckner 已提交
1655
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1656
    {
1657
        return false;
M
Max Bruckner 已提交
1658
    }
M
Max Bruckner 已提交
1659
    if (format)
M
Max Bruckner 已提交
1660
    {
M
Max Bruckner 已提交
1661
        size_t i;
M
Max Bruckner 已提交
1662
        for (i = 0; i < (output_buffer->depth - 1); i++)
M
Max Bruckner 已提交
1663
        {
M
Max Bruckner 已提交
1664
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1665 1666
        }
    }
M
Max Bruckner 已提交
1667 1668
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1669
    output_buffer->depth--;
M
Max Bruckner 已提交
1670

1671
    return true;
K
Kevin Branigan 已提交
1672 1673 1674
}

/* Get Array size/item / object item. */
1675
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1676 1677
{
    cJSON *c = array->child;
1678
    size_t i = 0;
M
Max Bruckner 已提交
1679 1680 1681 1682 1683
    while(c)
    {
        i++;
        c = c->next;
    }
1684 1685 1686

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

M
Max Bruckner 已提交
1687
    return (int)i;
M
Max Bruckner 已提交
1688 1689
}

1690
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1691
{
1692
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1702
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
1703 1704 1705
{
    cJSON *current_element = NULL;

1706
    if ((object == NULL) || (name == NULL))
1707 1708 1709 1710 1711
    {
        return NULL;
    }

    current_element = object->child;
1712
    if (case_sensitive)
1713
    {
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
        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;
        }
1725 1726 1727 1728 1729
    }

    return current_element;
}

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *object, const char *string)
{
    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);
}

1740
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1741 1742 1743
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1744 1745

/* Utility for array list handling. */
M
Max Bruckner 已提交
1746 1747 1748 1749 1750 1751
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1752
/* Utility for handling references. */
1753
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1754
{
1755
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1756 1757
    if (!ref)
    {
1758
        return NULL;
M
Max Bruckner 已提交
1759 1760
    }
    memcpy(ref, item, sizeof(cJSON));
1761
    ref->string = NULL;
M
Max Bruckner 已提交
1762
    ref->type |= cJSON_IsReference;
1763
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1764 1765
    return ref;
}
K
Kevin Branigan 已提交
1766 1767

/* Add item to array/object. */
1768
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1769
{
1770 1771 1772
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1773 1774 1775
    {
        return;
    }
1776 1777 1778 1779

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1780 1781 1782 1783 1784 1785 1786
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1787
        while (child->next)
M
Max Bruckner 已提交
1788
        {
1789
            child = child->next;
M
Max Bruckner 已提交
1790
        }
1791
        suffix_object(child, item);
M
Max Bruckner 已提交
1792 1793 1794
    }
}

1795
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1796
{
1797
    /* call cJSON_AddItemToObjectCS for code reuse */
1798
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1799 1800
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1801 1802
}

1803 1804 1805
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
1806
#ifdef __GNUC__
1807
#pragma GCC diagnostic ignored "-Wcast-qual"
1808 1809
#endif

1810
/* Add an item to an object with constant string as key */
1811
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1812 1813 1814 1815 1816 1817 1818
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1819
        global_hooks.deallocate(item->string);
1820 1821 1822 1823 1824
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}
1825 1826 1827
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1828

1829
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1830
{
1831
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1832 1833
}

1834
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1835
{
1836
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1837 1838
}

M
Max Bruckner 已提交
1839
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1850
        return NULL;
1851
    }
1852
    if (c->prev)
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
    {
        /* not the first element */
        c->prev->next = c->next;
    }
    if (c->next)
    {
        c->next->prev = c->prev;
    }
    if (c==array->child)
    {
        array->child = c->next;
    }
    /* make sure the detached item doesn't point anywhere anymore */
1866
    c->prev = c->next = NULL;
1867 1868 1869

    return c;
}
1870
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1871 1872 1873 1874 1875 1876 1877 1878
{
    if (which < 0)
    {
        return NULL;
    }

    return DetachItemFromArray(array, (size_t)which);
}
K
Kevin Branigan 已提交
1879

1880
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1881 1882 1883 1884
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1885
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1886
{
1887
    size_t i = 0;
1888
    cJSON *c = object->child;
1889
    while (c && (case_insensitive_strcmp((unsigned char*)c->string, (const unsigned char*)string) != 0))
1890 1891 1892 1893 1894 1895
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1896
        return DetachItemFromArray(object, i);
1897 1898
    }

1899
    return NULL;
1900 1901
}

1902
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1903 1904 1905
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1906 1907

/* Replace array/object items with new ones. */
1908
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        cJSON_AddItemToArray(array, newitem);
        return;
    }
    newitem->next = c;
    newitem->prev = c->prev;
    c->prev = newitem;
    if (c == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
}

M
Max Bruckner 已提交
1934
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        return;
    }
    newitem->next = c->next;
    newitem->prev = c->prev;
    if (newitem->next)
    {
        newitem->next->prev = newitem;
    }
    if (c == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
1960
    c->next = c->prev = NULL;
1961 1962
    cJSON_Delete(c);
}
1963
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
1964 1965 1966 1967 1968 1969 1970 1971
{
    if (which < 0)
    {
        return;
    }

    ReplaceItemInArray(array, (size_t)which, newitem);
}
1972

1973
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1974
{
1975
    size_t i = 0;
1976
    cJSON *c = object->child;
1977
    while(c && (case_insensitive_strcmp((unsigned char*)c->string, (const unsigned char*)string) != 0))
1978 1979 1980 1981 1982 1983
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1984 1985 1986
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1987
             global_hooks.deallocate(newitem->string);
1988 1989
        }

1990
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1991
        ReplaceItemInArray(object, i, newitem);
1992 1993
    }
}
K
Kevin Branigan 已提交
1994 1995

/* Create basic types: */
1996
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
1997
{
1998
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1999 2000 2001 2002 2003 2004 2005 2006
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

2007
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
2008
{
2009
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2010 2011 2012 2013 2014 2015 2016 2017
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

2018
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
2019
{
2020
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2021 2022 2023 2024 2025 2026 2027 2028
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

2029
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
2030
{
2031
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2032 2033 2034 2035 2036 2037 2038 2039
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

2040
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
2041
{
2042
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2043 2044 2045 2046
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060

        /* 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 已提交
2061 2062 2063 2064 2065
    }

    return item;
}

2066
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
2067
{
2068
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2069 2070 2071
    if(item)
    {
        item->type = cJSON_String;
2072
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
2073 2074 2075
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2076
            return NULL;
M
Max Bruckner 已提交
2077 2078 2079 2080 2081 2082
        }
    }

    return item;
}

2083
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
2084
{
2085
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2086 2087 2088
    if(item)
    {
        item->type = cJSON_Raw;
2089
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
2090 2091 2092 2093 2094 2095 2096 2097
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2098 2099
}

2100
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
2101
{
2102
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2103 2104 2105 2106 2107 2108 2109 2110
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

2111
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
2112
{
2113
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2114 2115 2116 2117 2118 2119 2120
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2121 2122

/* Create Arrays: */
2123
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
2124
{
2125
    size_t i = 0;
2126 2127
    cJSON *n = NULL;
    cJSON *p = NULL;
2128 2129 2130 2131 2132 2133 2134 2135 2136
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2137 2138 2139 2140 2141
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2142
            return NULL;
M
Max Bruckner 已提交
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2158
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
2159
{
2160
    size_t i = 0;
2161 2162
    cJSON *n = NULL;
    cJSON *p = NULL;
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2173
    {
2174
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
2175 2176 2177
        if(!n)
        {
            cJSON_Delete(a);
2178
            return NULL;
M
Max Bruckner 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2194
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
2195
{
2196
    size_t i = 0;
2197 2198
    cJSON *n = NULL;
    cJSON *p = NULL;
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2209 2210 2211 2212 2213
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2214
            return NULL;
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2230
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2231
{
2232
    size_t i = 0;
2233 2234
    cJSON *n = NULL;
    cJSON *p = NULL;
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2245 2246 2247 2248 2249
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2250
            return NULL;
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2265 2266

/* Duplication */
2267
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2268
{
M
Max Bruckner 已提交
2269
    cJSON *newitem = NULL;
2270 2271
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2272
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2273 2274 2275 2276

    /* Bail on bad ptr */
    if (!item)
    {
2277
        goto fail;
M
Max Bruckner 已提交
2278 2279
    }
    /* Create new item */
2280
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2281 2282
    if (!newitem)
    {
2283
        goto fail;
M
Max Bruckner 已提交
2284 2285 2286 2287 2288 2289 2290
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2291
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2292 2293
        if (!newitem->valuestring)
        {
2294
            goto fail;
M
Max Bruckner 已提交
2295 2296 2297 2298
        }
    }
    if (item->string)
    {
2299
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2300 2301
        if (!newitem->string)
        {
2302
            goto fail;
M
Max Bruckner 已提交
2303 2304 2305 2306 2307 2308 2309 2310
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2311 2312
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2313
    {
2314
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2315 2316
        if (!newchild)
        {
2317
            goto fail;
M
Max Bruckner 已提交
2318
        }
2319
        if (next != NULL)
M
Max Bruckner 已提交
2320 2321
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2322 2323 2324
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2325 2326 2327 2328
        }
        else
        {
            /* Set newitem->child and move to it */
2329 2330
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2331
        }
2332
        child = child->next;
M
Max Bruckner 已提交
2333 2334 2335
    }

    return newitem;
2336 2337 2338 2339 2340 2341 2342 2343

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

    return NULL;
2344
}
2345

2346
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2347
{
2348
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
    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 已提交
2388
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2389 2390 2391 2392
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2393
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2394
                }
M
Max Bruckner 已提交
2395
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2396
            }
M
Max Bruckner 已提交
2397
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2398 2399 2400 2401
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2402
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2403 2404 2405 2406 2407
        }
    }

    /* and null-terminate. */
    *into = '\0';
2408
}
2409

2410
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2411 2412 2413 2414 2415 2416 2417 2418 2419
{
    if (item == NULL)
    {
        return false;
    }

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

2420
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2421 2422 2423 2424 2425 2426 2427 2428 2429
{
    if (item == NULL)
    {
        return false;
    }

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

2430
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
{
    if (item == NULL)
    {
        return false;
    }

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


2441
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2442 2443 2444 2445 2446 2447 2448 2449
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2450
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2451 2452 2453 2454 2455 2456 2457 2458 2459
{
    if (item == NULL)
    {
        return false;
    }

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

2460
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2461 2462 2463 2464 2465 2466 2467 2468 2469
{
    if (item == NULL)
    {
        return false;
    }

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

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

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

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

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

2490
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2491 2492 2493 2494 2495 2496 2497 2498 2499
{
    if (item == NULL)
    {
        return false;
    }

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

2500
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2501 2502 2503 2504 2505 2506 2507 2508
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Raw;
}
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 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

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:
        {
            cJSON *a_element = NULL;
            cJSON *b_element = NULL;
            for (a_element = a->child, b_element = b->child;
                    (a_element != NULL) && (b_element != NULL);
                    a_element = a_element->next, b_element = b_element->next)
            {
                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }
            }

            return true;
        }

        case cJSON_Object:
        {
            cJSON *a_element = NULL;
            cJSON_ArrayForEach(a_element, a)
            {
                /* TODO This has O(n^2) runtime, which is horrible! */
                cJSON *b_element = get_object_item(b, a_element->string, case_sensitive);
                if (b_element == NULL)
                {
                    return false;
                }

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

            return true;
        }

        default:
            return false;
    }
}
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619

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

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