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

  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
#pragma GCC visibility push(default)
K
Kevin Branigan 已提交
27 28 29 30 31 32 33
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
34
#include <locale.h>
35 36
#pragma GCC visibility pop

K
Kevin Branigan 已提交
37 38
#include "cJSON.h"

M
Max Bruckner 已提交
39
/* define our own boolean type */
40 41
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)
M
Max Bruckner 已提交
42

43
static const unsigned char *global_ep = NULL;
K
Kevin Branigan 已提交
44

45
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
M
Max Bruckner 已提交
46
{
47
    return (const char*) global_ep;
M
Max Bruckner 已提交
48
}
K
Kevin Branigan 已提交
49

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

55
CJSON_PUBLIC(const char*) cJSON_Version(void)
56 57 58 59 60 61 62
{
    static char version[15];
    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

    return version;
}

M
Max Bruckner 已提交
63
/* case insensitive strcmp */
64
static int cJSON_strcasecmp(const unsigned char *s1, const unsigned char *s2)
K
Kevin Branigan 已提交
65
{
M
Max Bruckner 已提交
66 67 68 69 70 71 72 73
    if (!s1)
    {
        return (s1 == s2) ? 0 : 1; /* both NULL? */
    }
    if (!s2)
    {
        return 1;
    }
M
Max Bruckner 已提交
74
    for(; tolower(*s1) == tolower(*s2); (void)++s1, ++s2)
M
Max Bruckner 已提交
75
    {
76
        if (*s1 == '\0')
M
Max Bruckner 已提交
77 78 79 80 81
        {
            return 0;
        }
    }

82
    return tolower(*s1) - tolower(*s2);
K
Kevin Branigan 已提交
83 84
}

85 86 87 88 89 90 91 92
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 已提交
93

94
static unsigned char* cJSON_strdup(const unsigned char* str, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
95
{
M
Max Bruckner 已提交
96
    size_t len = 0;
97
    unsigned char *copy = NULL;
K
Kevin Branigan 已提交
98

99 100 101 102 103
    if (str == NULL)
    {
        return NULL;
    }

104
    len = strlen((const char*)str) + sizeof("");
105
    if (!(copy = (unsigned char*)hooks->allocate(len)))
M
Max Bruckner 已提交
106
    {
107
        return NULL;
M
Max Bruckner 已提交
108 109 110 111
    }
    memcpy(copy, str, len);

    return copy;
K
Kevin Branigan 已提交
112 113
}

114
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
K
Kevin Branigan 已提交
115
{
M
Max Bruckner 已提交
116
    if (hooks == NULL)
M
Max Bruckner 已提交
117 118
    {
        /* Reset hooks */
119 120 121
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
K
Kevin Branigan 已提交
122 123 124
        return;
    }

125
    global_hooks.allocate = malloc;
M
Max Bruckner 已提交
126 127
    if (hooks->malloc_fn != NULL)
    {
128
        global_hooks.allocate = hooks->malloc_fn;
M
Max Bruckner 已提交
129 130
    }

131
    global_hooks.deallocate = free;
M
Max Bruckner 已提交
132 133
    if (hooks->free_fn != NULL)
    {
134
        global_hooks.deallocate = hooks->free_fn;
M
Max Bruckner 已提交
135 136 137
    }

    /* use realloc only if both free and malloc are used */
138 139
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
M
Max Bruckner 已提交
140
    {
141
        global_hooks.reallocate = realloc;
M
Max Bruckner 已提交
142
    }
K
Kevin Branigan 已提交
143 144 145
}

/* Internal constructor. */
146
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
K
Kevin Branigan 已提交
147
{
148
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
M
Max Bruckner 已提交
149 150
    if (node)
    {
151
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
152 153 154
    }

    return node;
K
Kevin Branigan 已提交
155 156 157
}

/* Delete a cJSON structure. */
158
CJSON_PUBLIC(void) cJSON_Delete(cJSON *c)
K
Kevin Branigan 已提交
159
{
M
Max Bruckner 已提交
160
    cJSON *next = NULL;
M
Max Bruckner 已提交
161 162 163 164 165 166 167 168 169
    while (c)
    {
        next = c->next;
        if (!(c->type & cJSON_IsReference) && c->child)
        {
            cJSON_Delete(c->child);
        }
        if (!(c->type & cJSON_IsReference) && c->valuestring)
        {
170
            global_hooks.deallocate(c->valuestring);
M
Max Bruckner 已提交
171 172 173
        }
        if (!(c->type & cJSON_StringIsConst) && c->string)
        {
174
            global_hooks.deallocate(c->string);
M
Max Bruckner 已提交
175
        }
176
        global_hooks.deallocate(c);
M
Max Bruckner 已提交
177 178
        c = next;
    }
K
Kevin Branigan 已提交
179 180
}

181 182 183 184 185 186 187
/* 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 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
typedef struct
{
    const unsigned char *content;
    size_t length;
    size_t offset;
} 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 已提交
204
/* Parse the input text to generate a number, and populate the result into item. */
205
static const unsigned char *parse_number(cJSON * const item, const unsigned char * const input)
K
Kevin Branigan 已提交
206
{
207
    double number = 0;
208
    unsigned char *after_end = NULL;
209 210 211
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;
M
Max Bruckner 已提交
212

213
    if (input == NULL)
214 215 216 217
    {
        return NULL;
    }

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    /* copy the number into a temporary buffer and replace '.' with the decimal point
     * of the current locale (for strtod) */
    for (i = 0; (i < (sizeof(number_c_string) - 1)) && (input[i] != '\0'); i++)
    {
        switch (input[i])
        {
            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':
                number_c_string[i] = input[i];
                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 已提交
254
    {
255
        return NULL; /* parse_error */
M
Max Bruckner 已提交
256 257
    }

258
    item->valuedouble = number;
M
Max Bruckner 已提交
259

260
    /* use saturation in case of overflow */
261
    if (number >= INT_MAX)
262 263 264
    {
        item->valueint = INT_MAX;
    }
265
    else if (number <= INT_MIN)
266 267 268 269 270
    {
        item->valueint = INT_MIN;
    }
    else
    {
271
        item->valueint = (int)number;
272
    }
273

M
Max Bruckner 已提交
274 275
    item->type = cJSON_Number;

276
    return input + (after_end - number_c_string);
K
Kevin Branigan 已提交
277 278
}

279
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
280
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
281 282 283 284 285 286 287 288 289 290 291
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
292
        object->valueint = (int)number;
293 294 295 296 297
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
298 299
typedef struct
{
300
    unsigned char *buffer;
301 302
    size_t length;
    size_t offset;
303
    cJSON_bool noalloc;
M
Max Bruckner 已提交
304
} printbuffer;
305

M
Max Bruckner 已提交
306
/* realloc printbuffer if necessary to have at least "needed" bytes more */
307
static unsigned char* ensure(printbuffer * const p, size_t needed, const internal_hooks * const hooks)
308
{
309
    unsigned char *newbuffer = NULL;
310 311
    size_t newsize = 0;

312
    if ((p == NULL) || (p->buffer == NULL))
313 314 315 316
    {
        return NULL;
    }

M
Max Bruckner 已提交
317 318 319 320 321 322
    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

323
    if (needed > INT_MAX)
M
Max Bruckner 已提交
324
    {
325
        /* sizes bigger than INT_MAX are currently not supported */
326
        return NULL;
M
Max Bruckner 已提交
327
    }
328

329
    needed += p->offset + 1;
M
Max Bruckner 已提交
330 331 332 333 334
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

335 336 337 338
    if (p->noalloc) {
        return NULL;
    }

339
    /* calculate new buffer size */
M
Max Bruckner 已提交
340
    if (needed > (INT_MAX / 2))
341 342 343 344 345 346 347 348 349 350 351
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
352 353 354 355
    else
    {
        newsize = needed * 2;
    }
356

357
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
358
    {
M
Max Bruckner 已提交
359
        /* reallocate with realloc if available */
360
        newbuffer = (unsigned char*)hooks->reallocate(p->buffer, newsize);
M
Max Bruckner 已提交
361
    }
M
Max Bruckner 已提交
362
    else
M
Max Bruckner 已提交
363
    {
M
Max Bruckner 已提交
364
        /* otherwise reallocate manually */
365
        newbuffer = (unsigned char*)hooks->allocate(newsize);
M
Max Bruckner 已提交
366 367
        if (!newbuffer)
        {
368
            hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
369 370 371 372 373 374 375
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
376
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
377
        }
378
        hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
379 380 381 382 383
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
384 385
}

386 387
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
388
{
389 390
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
391
    {
392
        return;
M
Max Bruckner 已提交
393
    }
394
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
395

396
    buffer->offset += strlen((const char*)buffer_pointer);
397 398
}

399
/* Removes trailing zeroes from the end of a printed number */
400
static int trim_trailing_zeroes(const unsigned char * const number, int length, const unsigned char decimal_point)
K
Kevin Branigan 已提交
401
{
402
    if ((number == NULL) || (length <= 0))
403
    {
404
        return -1;
405 406
    }

407
    while ((length > 0) && (number[length - 1] == '0'))
M
Max Bruckner 已提交
408
    {
409
        length--;
M
Max Bruckner 已提交
410
    }
411
    if ((length > 0) && (number[length - 1] == decimal_point))
412
    {
413 414
        /* remove trailing decimal_point */
        length--;
415 416
    }

417
    return length;
418 419 420
}

/* Render the number nicely from the given item into a string. */
421
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
422
{
M
Max Bruckner 已提交
423
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
424
    double d = item->valuedouble;
425
    int length = 0;
426
    size_t i = 0;
427
    cJSON_bool trim_zeroes = true; /* should zeroes at the end be removed? */
428 429
    unsigned char number_buffer[64]; /* temporary buffer to print the number into */
    unsigned char decimal_point = get_decimal_point();
M
Max Bruckner 已提交
430

M
Max Bruckner 已提交
431
    if (output_buffer == NULL)
M
Max Bruckner 已提交
432
    {
433
        return false;
M
Max Bruckner 已提交
434
    }
M
Max Bruckner 已提交
435

436 437 438
    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
439
        length = sprintf((char*)number_buffer, "null");
440 441 442 443
    }
    else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
    {
        /* integer */
444
        length = sprintf((char*)number_buffer, "%.0f", d);
445 446 447 448
        trim_zeroes = false; /* don't remove zeroes for "big integers" */
    }
    else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
    {
449
        length = sprintf((char*)number_buffer, "%e", d);
450 451 452 453
        trim_zeroes = false; /* don't remove zeroes in engineering notation */
    }
    else
    {
454
        length = sprintf((char*)number_buffer, "%f", d);
M
Max Bruckner 已提交
455
    }
456

457 458
    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
459
    {
460
        return false;
461 462
    }

463 464
    if (trim_zeroes)
    {
465 466 467 468 469 470 471 472 473 474 475 476
        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;
477 478
    }

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

495
    return true;
K
Kevin Branigan 已提交
496 497
}

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

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

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

    return h;
532 533
}

534 535
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
536
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer, const unsigned char **error_pointer)
M
Max Bruckner 已提交
537
{
538 539 540
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
541
    unsigned char utf8_length = 0;
542
    unsigned char utf8_position = 0;
543
    unsigned char sequence_length = 0;
544
    unsigned char first_byte_mark = 0;
545 546 547 548 549 550 551

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

553 554 555
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

556 557
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
558
    {
559
        *error_pointer = first_sequence;
560
        goto fail;
M
Max Bruckner 已提交
561
    }
M
Max Bruckner 已提交
562

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

        if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
        {
            /* missing second half of the surrogate pair */
            *error_pointer = first_sequence;
            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 */
            *error_pointer = first_sequence;
            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 已提交
602
    }
M
Max Bruckner 已提交
603

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

637
    /* encode as utf8 */
638 639 640 641 642
    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;
643
    }
644 645 646 647 648 649 650 651
    /* 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);
652
    }
653

654 655 656 657 658 659 660 661 662
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
663
static const unsigned char *parse_string(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
{
    const unsigned char *input_pointer = input + 1;
    const unsigned char *input_end = input + 1;
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
    if (*input != '\"')
    {
        *error_pointer = input;
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
        while ((*input_end != '\"') && (*input_end != '\0'))
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
                if (input_end[1] == '\0')
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
        if (*input_end == '\0')
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
        allocation_length = (size_t) (input_end - input) - skipped_bytes;
703
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof(""));
704 705 706 707 708 709 710
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
711
    /* loop through the string literal */
712
    while (input_pointer < input_end)
M
Max Bruckner 已提交
713
    {
714
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
715
        {
716
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
717 718 719 720
        }
        /* escape sequence */
        else
        {
721
            unsigned char sequence_length = 2;
722
            switch (input_pointer[1])
M
Max Bruckner 已提交
723 724
            {
                case 'b':
725
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
726 727
                    break;
                case 'f':
728
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
729 730
                    break;
                case 'n':
731
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
732 733
                    break;
                case 'r':
734
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
735 736
                    break;
                case 't':
737
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
738
                    break;
739 740 741
                case '\"':
                case '\\':
                case '/':
742
                    *output_pointer++ = input_pointer[1];
743
                    break;
744 745

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

M
Max Bruckner 已提交
755
                default:
756
                    *error_pointer = input_pointer;
757
                    goto fail;
M
Max Bruckner 已提交
758
            }
759
            input_pointer += sequence_length;
M
Max Bruckner 已提交
760 761
        }
    }
762 763 764

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

766
    item->type = cJSON_String;
767
    item->valuestring = (char*)output;
768

769
    return input_end + 1;
770 771

fail:
772
    if (output != NULL)
773
    {
774
        hooks->deallocate(output);
775 776 777
    }

    return NULL;
K
Kevin Branigan 已提交
778 779 780
}

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

790
    if (output_buffer == NULL)
M
Max Bruckner 已提交
791
    {
792
        return false;
M
Max Bruckner 已提交
793 794 795
    }

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

805
        return true;
M
Max Bruckner 已提交
806 807 808
    }

    /* set "flag" to 1 if something needs to be escaped */
809
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
810
    {
M
Max Bruckner 已提交
811
        if (strchr("\"\\\b\f\n\r\t", *input_pointer))
M
Max Bruckner 已提交
812
        {
M
Max Bruckner 已提交
813 814
            /* one character escape sequence */
            escape_characters++;
M
Max Bruckner 已提交
815
        }
M
Max Bruckner 已提交
816
        else if (*input_pointer < 32)
M
Max Bruckner 已提交
817
        {
M
Max Bruckner 已提交
818 819
            /* UTF-16 escape sequence uXXXX */
            escape_characters += 5;
M
Max Bruckner 已提交
820 821
        }
    }
M
Max Bruckner 已提交
822
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
823

824
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
825
    if (output == NULL)
M
Max Bruckner 已提交
826
    {
827
        return false;
M
Max Bruckner 已提交
828 829
    }

M
Max Bruckner 已提交
830 831
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
832
    {
M
Max Bruckner 已提交
833 834 835 836 837
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

838
        return true;
M
Max Bruckner 已提交
839 840
    }

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

889
    return true;
K
Kevin Branigan 已提交
890
}
M
Max Bruckner 已提交
891

M
Max Bruckner 已提交
892
/* Invoke print_string_ptr (which is useful) on an item. */
893
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
894
{
895
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
896
}
K
Kevin Branigan 已提交
897 898

/* Predeclare these prototypes. */
M
Max Bruckner 已提交
899
static const unsigned char *parse_value(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const ep, const internal_hooks * const hooks);
900
static cJSON_bool print_value(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
M
Max Bruckner 已提交
901
static const unsigned char *parse_array(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const ep, const internal_hooks * const hooks);
902
static cJSON_bool print_array(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
M
Max Bruckner 已提交
903
static const unsigned char *parse_object(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const ep, const internal_hooks * const hooks);
904
static cJSON_bool print_object(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
K
Kevin Branigan 已提交
905 906

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
907
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
908
{
909
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
910 911 912 913 914 915
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
916

M
Max Bruckner 已提交
917 918 919 920 921 922 923
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
{
    if ((buffer == NULL) || (buffer->content == NULL))
    {
        return NULL;
    }

M
Max Bruckner 已提交
924 925 926 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)
    {
        buffer->offset--;
    }
M
Max Bruckner 已提交
933 934 935 936

    return buffer;
}

K
Kevin Branigan 已提交
937
/* Parse an object - create a new root, and populate. */
938
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
939
{
M
Max Bruckner 已提交
940
    parse_buffer buffer;
941
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
942
    /* use global error pointer if no specific one was given */
943
    const unsigned char **error_pointer = (return_parse_end != NULL) ? (const unsigned char**)return_parse_end : &global_ep;
944 945
    cJSON *item = NULL;

946
    *error_pointer = NULL;
947 948

    item = cJSON_New_Item(&global_hooks);
949
    if (item == NULL) /* memory fail */
M
Max Bruckner 已提交
950
    {
951 952 953 954 955 956
        goto fail;
    }

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

M
Max Bruckner 已提交
959 960 961 962 963
    buffer.content = (const unsigned char*)value;
    buffer.length = strlen((const char*)value) + sizeof("");
    buffer.offset = 0;

    end = parse_value(item, buffer_skip_whitespace(&buffer), error_pointer, &global_hooks);
964
    if (end == NULL)
M
Max Bruckner 已提交
965 966
    {
        /* parse failure. ep is set. */
967
        goto fail;
M
Max Bruckner 已提交
968 969 970 971 972
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
973
        end = skip_whitespace(end);
974
        if (*end != '\0')
M
Max Bruckner 已提交
975
        {
976
            *error_pointer = end;
977
            goto fail;
M
Max Bruckner 已提交
978 979 980 981
        }
    }
    if (return_parse_end)
    {
982
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
983 984
    }

985
    return item;
986 987 988 989 990 991 992 993

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

    return NULL;
K
Kevin Branigan 已提交
994
}
M
Max Bruckner 已提交
995

996
/* Default options for cJSON_Parse */
997
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
998 999 1000
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
1001

M
Max Bruckner 已提交
1002 1003
#define min(a, b) ((a < b) ? a : b)

1004
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1005 1006 1007 1008 1009 1010 1011
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
1012
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
1013 1014 1015 1016 1017 1018
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
1019
    if (!print_value(item, 0, format, buffer, hooks))
M
Max Bruckner 已提交
1020 1021 1022
    {
        goto fail;
    }
1023
    update_offset(buffer);
M
Max Bruckner 已提交
1024 1025

    /* copy the buffer over to a new one */
1026
    printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
M
Max Bruckner 已提交
1027 1028 1029 1030 1031 1032 1033 1034
    if (printed == NULL)
    {
        goto fail;
    }
    strncpy((char*)printed, (char*)buffer->buffer, min(buffer->length, buffer->offset + 1));
    printed[buffer->offset] = '\0'; /* just to be sure */

    /* free the buffer */
1035
    hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
1036 1037 1038 1039 1040 1041

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
1042
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
1043 1044 1045 1046
    }

    if (printed != NULL)
    {
1047
        hooks->deallocate(printed);
M
Max Bruckner 已提交
1048 1049 1050 1051 1052
    }

    return NULL;
}

K
Kevin Branigan 已提交
1053
/* Render a cJSON item/entity/structure to text. */
1054
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
1055
{
1056
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
1057 1058
}

1059
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
1060
{
1061
    return (char*)print(item, false, &global_hooks);
1062
}
1063

1064
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
1065
{
M
Max Bruckner 已提交
1066
    printbuffer p;
M
Max Bruckner 已提交
1067 1068 1069

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
1070
        return NULL;
M
Max Bruckner 已提交
1071 1072
    }

1073
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
1074 1075
    if (!p.buffer)
    {
1076
        return NULL;
1077
    }
M
Max Bruckner 已提交
1078 1079

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
1080
    p.offset = 0;
1081
    p.noalloc = false;
M
Max Bruckner 已提交
1082

1083 1084 1085 1086 1087 1088
    if (!print_value(item, 0, fmt, &p, &global_hooks))
    {
        return NULL;
    }

    return (char*)p.buffer;
1089 1090
}

1091
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
1092 1093
{
    printbuffer p;
M
Max Bruckner 已提交
1094 1095 1096 1097 1098 1099

    if (len < 0)
    {
        return false;
    }

1100
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
1101
    p.length = (size_t)len;
1102
    p.offset = 0;
1103
    p.noalloc = true;
1104
    return print_value(item, 0, fmt, &p, &global_hooks);
1105
}
K
Kevin Branigan 已提交
1106 1107

/* Parser core - when encountering text, process appropriately. */
M
Max Bruckner 已提交
1108
static const unsigned  char *parse_value(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1109
{
M
Max Bruckner 已提交
1110
    const unsigned char *content_pointer = NULL;
M
Max Bruckner 已提交
1111
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
M
Max Bruckner 已提交
1112
    {
1113
        return NULL; /* no input */
M
Max Bruckner 已提交
1114 1115 1116
    }

    /* parse the different types of values */
1117
    /* null */
M
Max Bruckner 已提交
1118
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
M
Max Bruckner 已提交
1119 1120
    {
        item->type = cJSON_NULL;
M
Max Bruckner 已提交
1121 1122
        input_buffer->offset += 4;
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1123
    }
1124
    /* false */
M
Max Bruckner 已提交
1125
    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
M
Max Bruckner 已提交
1126 1127
    {
        item->type = cJSON_False;
M
Max Bruckner 已提交
1128 1129
        input_buffer->offset += 5;
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1130
    }
1131
    /* true */
M
Max Bruckner 已提交
1132
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
M
Max Bruckner 已提交
1133 1134 1135
    {
        item->type = cJSON_True;
        item->valueint = 1;
M
Max Bruckner 已提交
1136 1137
        input_buffer->offset += 4;
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1138
    }
1139
    /* string */
M
Max Bruckner 已提交
1140
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
M
Max Bruckner 已提交
1141
    {
M
Max Bruckner 已提交
1142 1143 1144 1145 1146 1147 1148 1149
        content_pointer = parse_string(item, buffer_at_offset(input_buffer), error_pointer, hooks);
        if (content_pointer == NULL)
        {
            return NULL;
        }

        input_buffer->offset = (size_t)(content_pointer - input_buffer->content);
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1150
    }
1151
    /* number */
M
Max Bruckner 已提交
1152
    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 已提交
1153
    {
M
Max Bruckner 已提交
1154 1155 1156 1157 1158 1159 1160 1161
        content_pointer = parse_number(item, buffer_at_offset(input_buffer));
        if (content_pointer == NULL)
        {
            return NULL;
        }

        input_buffer->offset = (size_t)(content_pointer - input_buffer->content);
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1162
    }
1163
    /* array */
M
Max Bruckner 已提交
1164
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
M
Max Bruckner 已提交
1165
    {
M
Max Bruckner 已提交
1166
        return parse_array(item, input_buffer, error_pointer, hooks);
M
Max Bruckner 已提交
1167
    }
1168
    /* object */
M
Max Bruckner 已提交
1169
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
M
Max Bruckner 已提交
1170
    {
M
Max Bruckner 已提交
1171
        content_pointer = parse_object(item, input_buffer, error_pointer, hooks);
M
Max Bruckner 已提交
1172 1173 1174 1175 1176 1177 1178
        if (content_pointer == NULL)
        {
            return NULL;
        }

        input_buffer->offset = (size_t)(content_pointer - input_buffer->content);
        return buffer_at_offset(input_buffer);
M
Max Bruckner 已提交
1179 1180
    }

M
Max Bruckner 已提交
1181
    /* failure. */
M
Max Bruckner 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    if (can_access_at_index(input_buffer, 0))
    {
        *error_pointer = buffer_at_offset(input_buffer);
    }
    else if (input_buffer->length > 0)
    {
        *error_pointer = input_buffer->content + input_buffer->length - 1;
    }
    else
    {
        *error_pointer = input_buffer->content;
    }

1195
    return NULL;
K
Kevin Branigan 已提交
1196 1197 1198
}

/* Render a value to text. */
1199
static cJSON_bool print_value(const cJSON * const item, const size_t depth, const cJSON_bool format,  printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1200
{
M
Max Bruckner 已提交
1201
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1202

M
Max Bruckner 已提交
1203
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1204
    {
1205
        return false;
M
Max Bruckner 已提交
1206
    }
M
Max Bruckner 已提交
1207 1208

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1209
    {
M
Max Bruckner 已提交
1210
        case cJSON_NULL:
1211
            output = ensure(output_buffer, 5, hooks);
1212
            if (output == NULL)
M
Max Bruckner 已提交
1213
            {
1214
                return false;
M
Max Bruckner 已提交
1215
            }
1216 1217 1218
            strcpy((char*)output, "null");
            return true;

M
Max Bruckner 已提交
1219
        case cJSON_False:
1220
            output = ensure(output_buffer, 6, hooks);
1221
            if (output == NULL)
M
Max Bruckner 已提交
1222
            {
1223
                return false;
M
Max Bruckner 已提交
1224
            }
1225 1226 1227
            strcpy((char*)output, "false");
            return true;

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

M
Max Bruckner 已提交
1237
        case cJSON_Number:
1238
            return print_number(item, output_buffer, hooks);
1239

M
Max Bruckner 已提交
1240
        case cJSON_Raw:
M
Max Bruckner 已提交
1241
        {
M
Max Bruckner 已提交
1242 1243
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1244
            {
M
Max Bruckner 已提交
1245
                if (!output_buffer->noalloc)
1246
                {
1247
                    hooks->deallocate(output_buffer->buffer);
1248
                }
1249
                return false;
M
Max Bruckner 已提交
1250
            }
1251

1252
            raw_length = strlen(item->valuestring) + sizeof("");
1253
            output = ensure(output_buffer, raw_length, hooks);
1254
            if (output == NULL)
M
Max Bruckner 已提交
1255
            {
1256
                return false;
1257
            }
1258 1259
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1260
        }
1261

M
Max Bruckner 已提交
1262
        case cJSON_String:
1263
            return print_string(item, output_buffer, hooks);
1264

M
Max Bruckner 已提交
1265
        case cJSON_Array:
1266
            return print_array(item, depth, format, output_buffer, hooks);
1267

M
Max Bruckner 已提交
1268
        case cJSON_Object:
1269
            return print_object(item, depth, format, output_buffer, hooks);
1270

M
Max Bruckner 已提交
1271
        default:
1272
            return false;
M
Max Bruckner 已提交
1273
    }
K
Kevin Branigan 已提交
1274 1275 1276
}

/* Build an array from input text. */
M
Max Bruckner 已提交
1277
static const unsigned char *parse_array(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1278
{
1279
    cJSON *head = NULL; /* head of the linked list */
1280 1281
    cJSON *current_item = NULL;

M
Max Bruckner 已提交
1282
    if (buffer_at_offset(input_buffer)[0] != '[')
M
Max Bruckner 已提交
1283
    {
1284
        /* not an array */
M
Max Bruckner 已提交
1285
        *error_pointer = buffer_at_offset(input_buffer);
1286
        goto fail;
M
Max Bruckner 已提交
1287
    }
K
Kevin Branigan 已提交
1288

M
Max Bruckner 已提交
1289 1290 1291
    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 已提交
1292
    {
1293
        /* empty array */
1294
        goto success;
M
Max Bruckner 已提交
1295
    }
K
Kevin Branigan 已提交
1296

M
Max Bruckner 已提交
1297 1298 1299 1300 1301 1302 1303 1304
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        *error_pointer = buffer_at_offset(input_buffer);
        goto fail;
    }

1305
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1306
    input_buffer->offset--;
M
Max Bruckner 已提交
1307
    /* loop through the comma separated array elements */
1308
    do
M
Max Bruckner 已提交
1309
    {
1310
        /* allocate next item */
1311
        cJSON *new_item = cJSON_New_Item(hooks);
1312
        if (new_item == NULL)
M
Max Bruckner 已提交
1313
        {
1314
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1315
        }
1316 1317 1318

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1319
        {
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
            /* 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 已提交
1332 1333 1334
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        if (parse_value(current_item, input_buffer, error_pointer, hooks) == NULL)
1335 1336
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1337
        }
M
Max Bruckner 已提交
1338
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1339
    }
M
Max Bruckner 已提交
1340
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
M
Max Bruckner 已提交
1341

M
Max Bruckner 已提交
1342
    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
M
Max Bruckner 已提交
1343
    {
M
Max Bruckner 已提交
1344
        *error_pointer = buffer_at_offset(input_buffer);
1345
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1346 1347
    }

1348 1349
success:
    item->type = cJSON_Array;
1350
    item->child = head;
1351

M
Max Bruckner 已提交
1352 1353 1354
    input_buffer->offset++;

    return buffer_at_offset(input_buffer);
K
Kevin Branigan 已提交
1355

1356
fail:
1357
    if (head != NULL)
1358
    {
1359
        cJSON_Delete(head);
1360 1361
    }

1362
    return NULL;
K
Kevin Branigan 已提交
1363 1364 1365
}

/* Render an array to text */
1366
static cJSON_bool print_array(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1367
{
M
Max Bruckner 已提交
1368
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1369
    size_t length = 0;
M
Max Bruckner 已提交
1370
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1371

M
Max Bruckner 已提交
1372
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1373
    {
1374
        return false;
M
Max Bruckner 已提交
1375 1376
    }

M
Max Bruckner 已提交
1377 1378
    /* Compose the output array. */
    /* opening square bracket */
1379
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1380
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1381
    {
1382
        return false;
M
Max Bruckner 已提交
1383 1384
    }

M
Max Bruckner 已提交
1385 1386
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1387

M
Max Bruckner 已提交
1388
    while (current_element != NULL)
M
Max Bruckner 已提交
1389
    {
1390
        if (!print_value(current_element, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1391
        {
1392
            return false;
M
Max Bruckner 已提交
1393
        }
1394
        update_offset(output_buffer);
M
Max Bruckner 已提交
1395
        if (current_element->next)
M
Max Bruckner 已提交
1396
        {
1397
            length = (size_t) (format ? 2 : 1);
1398
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1399
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1400
            {
1401
                return false;
M
Max Bruckner 已提交
1402
            }
M
Max Bruckner 已提交
1403 1404
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1405
            {
M
Max Bruckner 已提交
1406
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1407
            }
M
Max Bruckner 已提交
1408 1409
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1410
        }
M
Max Bruckner 已提交
1411
        current_element = current_element->next;
M
Max Bruckner 已提交
1412 1413
    }

1414
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1415
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1416
    {
1417
        return false;
M
Max Bruckner 已提交
1418
    }
M
Max Bruckner 已提交
1419 1420
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1421

1422
    return true;
K
Kevin Branigan 已提交
1423 1424 1425
}

/* Build an object from the text. */
M
Max Bruckner 已提交
1426
static const unsigned char *parse_object(cJSON * const item, parse_buffer * const input_buffer, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1427
{
1428
    cJSON *head = NULL; /* linked list head */
1429
    cJSON *current_item = NULL;
M
Max Bruckner 已提交
1430
    const unsigned char *content_pointer = NULL;
1431

M
Max Bruckner 已提交
1432
    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
M
Max Bruckner 已提交
1433
    {
M
Max Bruckner 已提交
1434
        *error_pointer = buffer_at_offset(input_buffer);
1435
        goto fail; /* not an object */
M
Max Bruckner 已提交
1436 1437
    }

M
Max Bruckner 已提交
1438 1439 1440
    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 已提交
1441
    {
1442
        goto success; /* empty object */
M
Max Bruckner 已提交
1443 1444
    }

M
Max Bruckner 已提交
1445 1446 1447 1448 1449 1450 1451 1452
    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        *error_pointer = buffer_at_offset(input_buffer);
        goto fail;
    }

1453
    /* step back to character in front of the first element */
M
Max Bruckner 已提交
1454
    input_buffer->offset--;
1455 1456
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1457
    {
1458
        /* allocate next item */
1459
        cJSON *new_item = cJSON_New_Item(hooks);
1460 1461 1462 1463
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1464

1465 1466
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1467
        {
1468 1469 1470 1471 1472 1473 1474 1475 1476
            /* 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 已提交
1477 1478
        }

1479
        /* parse the name of the child */
M
Max Bruckner 已提交
1480 1481 1482 1483
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        content_pointer = parse_string(current_item, buffer_at_offset(input_buffer), error_pointer, hooks);
        if (content_pointer == NULL)
M
Max Bruckner 已提交
1484
        {
1485
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1486
        }
M
Max Bruckner 已提交
1487 1488
        input_buffer->offset = (size_t)(content_pointer - input_buffer->content);
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1489

1490 1491 1492
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1493

M
Max Bruckner 已提交
1494
        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
M
Max Bruckner 已提交
1495
        {
M
Max Bruckner 已提交
1496
            *error_pointer = buffer_at_offset(input_buffer);
1497
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1498
        }
1499 1500

        /* parse the value */
M
Max Bruckner 已提交
1501 1502 1503
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        if (parse_value(current_item, input_buffer, error_pointer, hooks) == NULL)
M
Max Bruckner 已提交
1504
        {
1505
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1506
        }
M
Max Bruckner 已提交
1507
        buffer_skip_whitespace(input_buffer);
M
Max Bruckner 已提交
1508
    }
M
Max Bruckner 已提交
1509
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
1510

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

1517 1518
success:
    item->type = cJSON_Object;
1519
    item->child = head;
1520

M
Max Bruckner 已提交
1521 1522
    input_buffer->offset++;
    return buffer_at_offset(input_buffer);
1523 1524

fail:
1525
    if (head != NULL)
1526
    {
1527
        cJSON_Delete(head);
1528 1529
    }

1530
    return NULL;
K
Kevin Branigan 已提交
1531 1532 1533
}

/* Render an object to text. */
1534
static cJSON_bool print_object(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
1535
{
M
Max Bruckner 已提交
1536
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1537
    size_t length = 0;
M
Max Bruckner 已提交
1538
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1539

M
Max Bruckner 已提交
1540
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1541
    {
1542
        return false;
M
Max Bruckner 已提交
1543 1544
    }

M
Max Bruckner 已提交
1545
    /* Compose the output: */
1546
    length = (size_t) (format ? 2 : 1); /* fmt: {\n */
1547
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1548
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1549
    {
1550
        return false;
M
Max Bruckner 已提交
1551 1552
    }

M
Max Bruckner 已提交
1553 1554
    *output_pointer++ = '{';
    if (format)
M
Max Bruckner 已提交
1555
    {
M
Max Bruckner 已提交
1556
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1557
    }
M
Max Bruckner 已提交
1558
    output_buffer->offset += length;
M
Max Bruckner 已提交
1559

M
Max Bruckner 已提交
1560
    while (current_item)
M
Max Bruckner 已提交
1561
    {
M
Max Bruckner 已提交
1562
        if (format)
M
Max Bruckner 已提交
1563
        {
M
Max Bruckner 已提交
1564
            size_t i;
1565
            output_pointer = ensure(output_buffer, depth + 1, hooks);
M
Max Bruckner 已提交
1566
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1567
            {
1568
                return false;
M
Max Bruckner 已提交
1569
            }
M
Max Bruckner 已提交
1570
            for (i = 0; i < depth + 1; i++)
M
Max Bruckner 已提交
1571
            {
M
Max Bruckner 已提交
1572
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1573
            }
M
Max Bruckner 已提交
1574
            output_buffer->offset += depth + 1;
M
Max Bruckner 已提交
1575 1576
        }

M
Max Bruckner 已提交
1577
        /* print key */
1578
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks))
M
Max Bruckner 已提交
1579
        {
1580
            return false;
M
Max Bruckner 已提交
1581
        }
M
Max Bruckner 已提交
1582
        update_offset(output_buffer);
M
Max Bruckner 已提交
1583

1584
        length = (size_t) (format ? 2 : 1);
1585
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1586
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1587
        {
1588
            return false;
M
Max Bruckner 已提交
1589
        }
M
Max Bruckner 已提交
1590 1591
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1592
        {
M
Max Bruckner 已提交
1593
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1594
        }
M
Max Bruckner 已提交
1595
        output_buffer->offset += length;
M
Max Bruckner 已提交
1596

M
Max Bruckner 已提交
1597
        /* print value */
1598
        if (!print_value(current_item, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1599
        {
1600
            return false;
M
Max Bruckner 已提交
1601
        }
M
Max Bruckner 已提交
1602
        update_offset(output_buffer);
M
Max Bruckner 已提交
1603

M
Max Bruckner 已提交
1604
        /* print comma if not last */
1605
        length = (size_t) ((format ? 1 : 0) + (current_item->next ? 1 : 0));
1606
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1607
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1608
        {
1609
            return false;
M
Max Bruckner 已提交
1610
        }
M
Max Bruckner 已提交
1611
        if (current_item->next)
M
Max Bruckner 已提交
1612
        {
M
Max Bruckner 已提交
1613
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1614 1615
        }

M
Max Bruckner 已提交
1616
        if (format)
M
Max Bruckner 已提交
1617
        {
M
Max Bruckner 已提交
1618
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1619
        }
M
Max Bruckner 已提交
1620 1621
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1622

M
Max Bruckner 已提交
1623
        current_item = current_item->next;
M
Max Bruckner 已提交
1624
    }
M
Max Bruckner 已提交
1625

1626
    output_pointer = ensure(output_buffer, format ? (depth + 2) : 2, hooks);
M
Max Bruckner 已提交
1627
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1628
    {
1629
        return false;
M
Max Bruckner 已提交
1630
    }
M
Max Bruckner 已提交
1631
    if (format)
M
Max Bruckner 已提交
1632
    {
M
Max Bruckner 已提交
1633 1634
        size_t i;
        for (i = 0; i < (depth); i++)
M
Max Bruckner 已提交
1635
        {
M
Max Bruckner 已提交
1636
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1637 1638
        }
    }
M
Max Bruckner 已提交
1639 1640
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1641

1642
    return true;
K
Kevin Branigan 已提交
1643 1644 1645
}

/* Get Array size/item / object item. */
1646
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1647 1648
{
    cJSON *c = array->child;
1649
    size_t i = 0;
M
Max Bruckner 已提交
1650 1651 1652 1653 1654
    while(c)
    {
        i++;
        c = c->next;
    }
1655 1656 1657

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

M
Max Bruckner 已提交
1658
    return (int)i;
M
Max Bruckner 已提交
1659 1660
}

1661
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1662
{
1663
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1673
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1674
{
1675
    cJSON *c = object ? object->child : NULL;
1676
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1677 1678 1679 1680 1681 1682
    {
        c = c->next;
    }
    return c;
}

1683
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
{
    cJSON *current_element = NULL;

    if ((object == NULL) || (string == NULL))
    {
        return NULL;
    }

    current_element = object->child;
    while ((current_element != NULL) && (strcmp(string, current_element->string) != 0))
    {
        current_element = current_element->next;
    }

    return current_element;
}

1701
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1702 1703 1704
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1705 1706

/* Utility for array list handling. */
M
Max Bruckner 已提交
1707 1708 1709 1710 1711 1712
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1713
/* Utility for handling references. */
1714
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1715
{
1716
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1717 1718
    if (!ref)
    {
1719
        return NULL;
M
Max Bruckner 已提交
1720 1721
    }
    memcpy(ref, item, sizeof(cJSON));
1722
    ref->string = NULL;
M
Max Bruckner 已提交
1723
    ref->type |= cJSON_IsReference;
1724
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1725 1726
    return ref;
}
K
Kevin Branigan 已提交
1727 1728

/* Add item to array/object. */
1729
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1730
{
1731 1732 1733
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1734 1735 1736
    {
        return;
    }
1737 1738 1739 1740

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1741 1742 1743 1744 1745 1746 1747
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1748
        while (child->next)
M
Max Bruckner 已提交
1749
        {
1750
            child = child->next;
M
Max Bruckner 已提交
1751
        }
1752
        suffix_object(child, item);
M
Max Bruckner 已提交
1753 1754 1755
    }
}

1756
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1757
{
1758
    /* call cJSON_AddItemToObjectCS for code reuse */
1759
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1760 1761
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1762 1763
}

1764 1765 1766 1767
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wcast-qual"
1768
/* Add an item to an object with constant string as key */
1769
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1770 1771 1772 1773 1774 1775 1776
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1777
        global_hooks.deallocate(item->string);
1778 1779 1780 1781 1782
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}
1783 1784 1785
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1786

1787
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1788
{
1789
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1790 1791
}

1792
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1793
{
1794
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1795 1796
}

M
Max Bruckner 已提交
1797
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1808
        return NULL;
1809
    }
1810
    if (c->prev)
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    {
        /* 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 */
1824
    c->prev = c->next = NULL;
1825 1826 1827

    return c;
}
1828
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1829 1830 1831 1832 1833 1834 1835 1836
{
    if (which < 0)
    {
        return NULL;
    }

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

1838
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1839 1840 1841 1842
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1843
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1844
{
1845
    size_t i = 0;
1846
    cJSON *c = object->child;
1847
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1848 1849 1850 1851 1852 1853
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1854
        return DetachItemFromArray(object, i);
1855 1856
    }

1857
    return NULL;
1858 1859
}

1860
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1861 1862 1863
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1864 1865

/* Replace array/object items with new ones. */
1866
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
{
    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 已提交
1892
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
{
    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;
    }
1918
    c->next = c->prev = NULL;
1919 1920
    cJSON_Delete(c);
}
1921
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
1922 1923 1924 1925 1926 1927 1928 1929
{
    if (which < 0)
    {
        return;
    }

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

1931
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1932
{
1933
    size_t i = 0;
1934
    cJSON *c = object->child;
1935
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1936 1937 1938 1939 1940 1941
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1942 1943 1944
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1945
             global_hooks.deallocate(newitem->string);
1946 1947
        }

1948
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1949
        ReplaceItemInArray(object, i, newitem);
1950 1951
    }
}
K
Kevin Branigan 已提交
1952 1953

/* Create basic types: */
1954
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
1955
{
1956
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1957 1958 1959 1960 1961 1962 1963 1964
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

1965
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
1966
{
1967
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1968 1969 1970 1971 1972 1973 1974 1975
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

1976
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
1977
{
1978
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1979 1980 1981 1982 1983 1984 1985 1986
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

1987
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
1988
{
1989
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1990 1991 1992 1993 1994 1995 1996 1997
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

1998
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
1999
{
2000
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2001 2002 2003 2004
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

        /* 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 已提交
2019 2020 2021 2022 2023
    }

    return item;
}

2024
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
2025
{
2026
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2027 2028 2029
    if(item)
    {
        item->type = cJSON_String;
2030
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
2031 2032 2033
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2034
            return NULL;
M
Max Bruckner 已提交
2035 2036 2037 2038 2039 2040
        }
    }

    return item;
}

2041
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
2042
{
2043
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2044 2045 2046
    if(item)
    {
        item->type = cJSON_Raw;
2047
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
2048 2049 2050 2051 2052 2053 2054 2055
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2056 2057
}

2058
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
2059
{
2060
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2061 2062 2063 2064 2065 2066 2067 2068
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

2069
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
2070
{
2071
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2072 2073 2074 2075 2076 2077 2078
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2079 2080

/* Create Arrays: */
2081
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
2082
{
2083
    size_t i = 0;
2084 2085
    cJSON *n = NULL;
    cJSON *p = NULL;
2086 2087 2088 2089 2090 2091 2092 2093 2094
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2095 2096 2097 2098 2099
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2100
            return NULL;
M
Max Bruckner 已提交
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2116
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
2117
{
2118
    size_t i = 0;
2119 2120
    cJSON *n = NULL;
    cJSON *p = NULL;
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2131
    {
2132
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
2133 2134 2135
        if(!n)
        {
            cJSON_Delete(a);
2136
            return NULL;
M
Max Bruckner 已提交
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2152
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
2153
{
2154
    size_t i = 0;
2155 2156
    cJSON *n = NULL;
    cJSON *p = NULL;
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2167 2168 2169 2170 2171
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2172
            return NULL;
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2188
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2189
{
2190
    size_t i = 0;
2191 2192
    cJSON *n = NULL;
    cJSON *p = NULL;
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2203 2204 2205 2206 2207
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2208
            return NULL;
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2223 2224

/* Duplication */
2225
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2226
{
M
Max Bruckner 已提交
2227
    cJSON *newitem = NULL;
2228 2229
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2230
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2231 2232 2233 2234

    /* Bail on bad ptr */
    if (!item)
    {
2235
        goto fail;
M
Max Bruckner 已提交
2236 2237
    }
    /* Create new item */
2238
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2239 2240
    if (!newitem)
    {
2241
        goto fail;
M
Max Bruckner 已提交
2242 2243 2244 2245 2246 2247 2248
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2249
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2250 2251
        if (!newitem->valuestring)
        {
2252
            goto fail;
M
Max Bruckner 已提交
2253 2254 2255 2256
        }
    }
    if (item->string)
    {
2257
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2258 2259
        if (!newitem->string)
        {
2260
            goto fail;
M
Max Bruckner 已提交
2261 2262 2263 2264 2265 2266 2267 2268
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2269 2270
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2271
    {
2272
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2273 2274
        if (!newchild)
        {
2275
            goto fail;
M
Max Bruckner 已提交
2276
        }
2277
        if (next != NULL)
M
Max Bruckner 已提交
2278 2279
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2280 2281 2282
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2283 2284 2285 2286
        }
        else
        {
            /* Set newitem->child and move to it */
2287 2288
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2289
        }
2290
        child = child->next;
M
Max Bruckner 已提交
2291 2292 2293
    }

    return newitem;
2294 2295 2296 2297 2298 2299 2300 2301

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

    return NULL;
2302
}
2303

2304
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2305
{
2306
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    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 已提交
2346
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2347 2348 2349 2350
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2351
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2352
                }
M
Max Bruckner 已提交
2353
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2354
            }
M
Max Bruckner 已提交
2355
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2356 2357 2358 2359
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2360
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2361 2362 2363 2364 2365
        }
    }

    /* and null-terminate. */
    *into = '\0';
2366
}
2367

2368
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2369 2370 2371 2372 2373 2374 2375 2376 2377
{
    if (item == NULL)
    {
        return false;
    }

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

2378
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2379 2380 2381 2382 2383 2384 2385 2386 2387
{
    if (item == NULL)
    {
        return false;
    }

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

2388
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
{
    if (item == NULL)
    {
        return false;
    }

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


2399
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2400 2401 2402 2403 2404 2405 2406 2407
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2408
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2409 2410 2411 2412 2413 2414 2415 2416 2417
{
    if (item == NULL)
    {
        return false;
    }

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

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

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

2428
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2429 2430 2431 2432 2433 2434 2435 2436 2437
{
    if (item == NULL)
    {
        return false;
    }

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

2438
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2439 2440 2441 2442 2443 2444 2445 2446 2447
{
    if (item == NULL)
    {
        return false;
    }

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

2448
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2449 2450 2451 2452 2453 2454 2455 2456 2457
{
    if (item == NULL)
    {
        return false;
    }

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

2458
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2459 2460 2461 2462 2463 2464 2465 2466
{
    if (item == NULL)
    {
        return false;
    }

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