cJSON.c 55.1 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 35
#pragma GCC visibility pop

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

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

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

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

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

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

    return version;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/* Parse the input text to generate a number, and populate the result into item. */
181
static const unsigned char *parse_number(cJSON * const item, const unsigned char * const input)
K
Kevin Branigan 已提交
182
{
183
    double number = 0;
184
    unsigned char *after_end = NULL;
M
Max Bruckner 已提交
185

186
    if (input == NULL)
187 188 189 190
    {
        return NULL;
    }

191 192
    number = strtod((const char*)input, (char**)&after_end);
    if (input == after_end)
M
Max Bruckner 已提交
193
    {
194
        return NULL; /* parse_error */
M
Max Bruckner 已提交
195 196
    }

197
    item->valuedouble = number;
M
Max Bruckner 已提交
198

199
    /* use saturation in case of overflow */
200
    if (number >= INT_MAX)
201 202 203
    {
        item->valueint = INT_MAX;
    }
204
    else if (number <= INT_MIN)
205 206 207 208 209
    {
        item->valueint = INT_MIN;
    }
    else
    {
210
        item->valueint = (int)number;
211
    }
212

M
Max Bruckner 已提交
213 214
    item->type = cJSON_Number;

215
    return after_end;
K
Kevin Branigan 已提交
216 217
}

218
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
219
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
        object->valueint = cJSON_Number;
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
237 238
typedef struct
{
239
    unsigned char *buffer;
240 241
    size_t length;
    size_t offset;
242
    cJSON_bool noalloc;
M
Max Bruckner 已提交
243
} printbuffer;
244

M
Max Bruckner 已提交
245
/* realloc printbuffer if necessary to have at least "needed" bytes more */
246
static unsigned char* ensure(printbuffer * const p, size_t needed, const internal_hooks * const hooks)
247
{
248
    unsigned char *newbuffer = NULL;
249 250
    size_t newsize = 0;

251
    if ((p == NULL) || (p->buffer == NULL))
252
    {
253
        return NULL;
254 255
    }

256 257 258 259 260 261
    if (needed > INT_MAX)
    {
        /* sizes bigger than INT_MAX are currently not supported */
        return NULL;
    }

M
Max Bruckner 已提交
262 263 264 265 266 267
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

268 269 270 271
    if (p->noalloc) {
        return NULL;
    }

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    /* calculate new buffer size */
    newsize = needed * 2;
    if (newsize > INT_MAX)
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }

287
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
288
    {
M
Max Bruckner 已提交
289
        /* reallocate with realloc if available */
290
        newbuffer = (unsigned char*)hooks->reallocate(p->buffer, newsize);
M
Max Bruckner 已提交
291
    }
M
Max Bruckner 已提交
292
    else
M
Max Bruckner 已提交
293
    {
M
Max Bruckner 已提交
294
        /* otherwise reallocate manually */
295
        newbuffer = (unsigned char*)hooks->allocate(newsize);
M
Max Bruckner 已提交
296 297
        if (!newbuffer)
        {
298
            hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
299 300 301 302 303 304 305
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
306
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
307
        }
308
        hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
309 310 311 312 313
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
314 315
}

316 317
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
318
{
319 320
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
321
    {
322
        return;
M
Max Bruckner 已提交
323
    }
324
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
325

326
    buffer->offset += strlen((const char*)buffer_pointer);
327 328
}

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
/* Removes trailing zeroes from the end of a printed number */
static unsigned char *trim_trailing_zeroes(printbuffer * const buffer)
{
    size_t offset = 0;
    unsigned char *content = NULL;

    if ((buffer == NULL) || (buffer->buffer == NULL) || (buffer->offset < 1))
    {
        return NULL;
    }

    offset = buffer->offset - 1;
    content = buffer->buffer;

    while ((offset > 0) && (content[offset] == '0'))
    {
        offset--;
    }
    if ((offset > 0) && (content[offset] == '.'))
    {
        offset--;
    }

    offset++;
    content[offset] = '\0';

    buffer->offset = offset;

    return content + offset;
}

360
/* Render the number nicely from the given item into a string. */
361
static unsigned char *print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
362
{
M
Max Bruckner 已提交
363
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
364
    double d = item->valuedouble;
365
    int length = 0;
366
    cJSON_bool trim_zeroes = true; /* should at the end be removed? */
M
Max Bruckner 已提交
367

M
Max Bruckner 已提交
368
    if (output_buffer == NULL)
M
Max Bruckner 已提交
369 370 371 372
    {
        return NULL;
    }

373 374 375
    /* This is a nice tradeoff. */
    output_pointer = ensure(output_buffer, 64, hooks);
    if (output_pointer != NULL)
M
Max Bruckner 已提交
376
    {
377 378
        /* This checks for NaN and Infinity */
        if ((d * 0) != 0)
M
Max Bruckner 已提交
379
        {
380
            length = sprintf((char*)output_pointer, "null");
M
Max Bruckner 已提交
381
        }
382 383 384 385 386 387 388 389 390 391 392 393
        else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
        {
            /* integer */
            length = sprintf((char*)output_pointer, "%.0f", d);
            trim_zeroes = false; /* don't remove zeroes for "big integers" */
        }
        else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
        {
            length = sprintf((char*)output_pointer, "%e", d);
            trim_zeroes = false; /* don't remove zeroes in engineering notation */
        }
        else
M
Max Bruckner 已提交
394
        {
395
            length = sprintf((char*)output_pointer, "%f", d);
M
Max Bruckner 已提交
396 397
        }
    }
398

399 400 401 402 403 404 405 406
    /* sprintf failed */
    if (length < 0)
    {
        return NULL;
    }

    output_buffer->offset += (size_t)length;

407 408 409 410 411
    if (trim_zeroes)
    {
        return trim_trailing_zeroes(output_buffer);
    }

412
    return output_buffer->buffer + output_buffer->offset;
K
Kevin Branigan 已提交
413 414
}

M
Max Bruckner 已提交
415
/* parse 4 digit hexadecimal number */
416
static unsigned parse_hex4(const unsigned char * const input)
417
{
M
Max Bruckner 已提交
418
    unsigned int h = 0;
419
    size_t i = 0;
M
Max Bruckner 已提交
420

421
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
422
    {
423
        /* parse digit */
424
        if ((input[i] >= '0') && (input[i] <= '9'))
425
        {
426
            h += (unsigned int) input[i] - '0';
427
        }
428
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
429
        {
430
            h += (unsigned int) 10 + input[i] - 'A';
431
        }
432
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
433
        {
434
            h += (unsigned int) 10 + input[i] - 'a';
435 436 437 438 439
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
440

441 442 443 444 445
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
446 447 448
    }

    return h;
449 450
}

451 452
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
453
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 已提交
454
{
455 456 457 458 459 460 461 462 463 464 465 466 467
    /* first bytes of UTF8 encoding for a given length in bytes */
    static const unsigned char firstByteMark[5] =
    {
        0x00, /* should never happen */
        0x00, /* 0xxxxxxx */
        0xC0, /* 110xxxxx */
        0xE0, /* 1110xxxx */
        0xF0 /* 11110xxx */
    };

    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
468 469
    unsigned char utf8_length = 0;
    unsigned char sequence_length = 0;
470 471 472 473 474 475 476 477 478

    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);
    if ((input_end - first_sequence) < 6)
    {
        /* input ends unexpectedly */
        *error_pointer = first_sequence;
        goto fail;
    }
M
Max Bruckner 已提交
479

480 481
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
482
    {
483
        *error_pointer = first_sequence;
484
        goto fail;
M
Max Bruckner 已提交
485
    }
M
Max Bruckner 已提交
486

487 488
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
489
    {
490 491 492 493 494
        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 已提交
495
        {
496 497 498
            /* input ends unexpectedly */
            *error_pointer = first_sequence;
            goto fail;
M
Max Bruckner 已提交
499
        }
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525

        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 已提交
526
    }
M
Max Bruckner 已提交
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    /* 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;
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
    }
    else
M
Max Bruckner 已提交
552
    {
553 554
        /* invalid unicode codepoint */
        *error_pointer = first_sequence;
555
        goto fail;
M
Max Bruckner 已提交
556 557
    }

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    /* encode as utf8 */
    switch (utf8_length)
    {
        case 4:
            /* 10xxxxxx */
            (*output_pointer)[3] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 3:
            /* 10xxxxxx */
            (*output_pointer)[2] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 2:
            (*output_pointer)[1] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 1:
            /* depending on the length in bytes this determines the
               encoding of the first UTF8 byte */
            (*output_pointer)[0] = (unsigned char)((codepoint | firstByteMark[utf8_length]) & 0xFF);
            break;
        default:
            *error_pointer = first_sequence;
            goto fail;
    }
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
590
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)
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
{
    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;
630
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof('\0'));
631 632 633 634 635 636 637
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
638
    /* loop through the string literal */
639
    while (input_pointer < input_end)
M
Max Bruckner 已提交
640
    {
641
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
642
        {
643
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
644 645 646 647
        }
        /* escape sequence */
        else
        {
648
            unsigned char sequence_length = 2;
649
            switch (input_pointer[1])
M
Max Bruckner 已提交
650 651
            {
                case 'b':
652
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
653 654
                    break;
                case 'f':
655
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
656 657
                    break;
                case 'n':
658
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
659 660
                    break;
                case 'r':
661
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
662 663
                    break;
                case 't':
664
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
665
                    break;
666 667 668
                case '\"':
                case '\\':
                case '/':
669
                    *output_pointer++ = input_pointer[1];
670
                    break;
671 672

                /* UTF-16 literal */
M
Max Bruckner 已提交
673
                case 'u':
674 675
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer, error_pointer);
                    if (sequence_length == 0)
M
Max Bruckner 已提交
676
                    {
677
                        /* failed to convert UTF16-literal to UTF-8 */
678
                        goto fail;
M
Max Bruckner 已提交
679 680
                    }
                    break;
681

M
Max Bruckner 已提交
682
                default:
683
                    *error_pointer = input_pointer;
684
                    goto fail;
M
Max Bruckner 已提交
685
            }
686
            input_pointer += sequence_length;
M
Max Bruckner 已提交
687 688
        }
    }
689 690 691

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

693
    item->type = cJSON_String;
694
    item->valuestring = (char*)output;
695

696
    return input_end + 1;
697 698

fail:
699
    if (output != NULL)
700
    {
701
        hooks->deallocate(output);
702 703 704
    }

    return NULL;
K
Kevin Branigan 已提交
705 706 707
}

/* Render the cstring provided to an escaped version that can be printed. */
708
static unsigned char *print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
709
{
710 711 712
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
713 714 715
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
716

717
    if (output_buffer == NULL)
M
Max Bruckner 已提交
718 719 720 721
    {
        return NULL;
    }

M
Max Bruckner 已提交
722
    /* empty string */
723
    if (input == NULL)
M
Max Bruckner 已提交
724
    {
725
        output = ensure(output_buffer, sizeof("\"\""), hooks);
726
        if (output == NULL)
M
Max Bruckner 已提交
727
        {
728
            return NULL;
M
Max Bruckner 已提交
729
        }
730
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
731

732
        return output;
M
Max Bruckner 已提交
733 734 735
    }

    /* set "flag" to 1 if something needs to be escaped */
736
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
737
    {
M
Max Bruckner 已提交
738
        if (strchr("\"\\\b\f\n\r\t", *input_pointer))
M
Max Bruckner 已提交
739
        {
M
Max Bruckner 已提交
740 741
            /* one character escape sequence */
            escape_characters++;
M
Max Bruckner 已提交
742
        }
M
Max Bruckner 已提交
743
        else if (*input_pointer < 32)
M
Max Bruckner 已提交
744
        {
M
Max Bruckner 已提交
745 746
            /* UTF-16 escape sequence uXXXX */
            escape_characters += 5;
M
Max Bruckner 已提交
747 748
        }
    }
M
Max Bruckner 已提交
749
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
750

751
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
752
    if (output == NULL)
M
Max Bruckner 已提交
753
    {
754
        return NULL;
M
Max Bruckner 已提交
755 756
    }

M
Max Bruckner 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769
    /* no characters have to be escaped */
    if (escape_characters == 0)
    {
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

        return output;
    }

    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
770
    /* copy the string */
M
Max Bruckner 已提交
771
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
772
    {
773
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
774 775
        {
            /* normal character, copy */
M
Max Bruckner 已提交
776
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
777 778 779 780
        }
        else
        {
            /* character needs to be escaped */
781
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
782
            switch (*input_pointer)
M
Max Bruckner 已提交
783 784
            {
                case '\\':
M
Max Bruckner 已提交
785
                    *output_pointer = '\\';
M
Max Bruckner 已提交
786 787
                    break;
                case '\"':
M
Max Bruckner 已提交
788
                    *output_pointer = '\"';
M
Max Bruckner 已提交
789 790
                    break;
                case '\b':
M
Max Bruckner 已提交
791
                    *output_pointer = 'b';
M
Max Bruckner 已提交
792 793
                    break;
                case '\f':
M
Max Bruckner 已提交
794
                    *output_pointer = 'f';
M
Max Bruckner 已提交
795 796
                    break;
                case '\n':
M
Max Bruckner 已提交
797
                    *output_pointer = 'n';
M
Max Bruckner 已提交
798 799
                    break;
                case '\r':
M
Max Bruckner 已提交
800
                    *output_pointer = 'r';
M
Max Bruckner 已提交
801 802
                    break;
                case '\t':
M
Max Bruckner 已提交
803
                    *output_pointer = 't';
M
Max Bruckner 已提交
804 805 806
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
807 808
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
809 810 811 812
                    break;
            }
        }
    }
M
Max Bruckner 已提交
813 814
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
815

816
    return output;
K
Kevin Branigan 已提交
817
}
M
Max Bruckner 已提交
818

M
Max Bruckner 已提交
819
/* Invoke print_string_ptr (which is useful) on an item. */
820
static unsigned char *print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
821
{
822
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
823
}
K
Kevin Branigan 已提交
824 825

/* Predeclare these prototypes. */
826
static const unsigned char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const ep, const internal_hooks * const hooks);
827
static unsigned char *print_value(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
828
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
829
static unsigned char *print_array(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
830
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
831
static unsigned char *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 已提交
832 833

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
834
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
835
{
836
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
837 838 839 840 841 842
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
843 844

/* Parse an object - create a new root, and populate. */
845
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
846
{
847
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
848
    /* use global error pointer if no specific one was given */
849
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
850
    cJSON *c = cJSON_New_Item(&global_hooks);
851
    *ep = NULL;
M
Max Bruckner 已提交
852 853
    if (!c) /* memory fail */
    {
854
        return NULL;
M
Max Bruckner 已提交
855 856
    }

857
    end = parse_value(c, skip_whitespace((const unsigned char*)value), ep, &global_hooks);
M
Max Bruckner 已提交
858 859 860 861
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
862
        return NULL;
M
Max Bruckner 已提交
863 864 865 866 867
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
868
        end = skip_whitespace(end);
M
Max Bruckner 已提交
869 870 871 872
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
873
            return NULL;
M
Max Bruckner 已提交
874 875 876 877
        }
    }
    if (return_parse_end)
    {
878
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
879 880 881
    }

    return c;
K
Kevin Branigan 已提交
882
}
M
Max Bruckner 已提交
883

884
/* Default options for cJSON_Parse */
885
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
886 887 888
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
889

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

892
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
893 894 895 896 897 898 899
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
900
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
901 902 903 904 905 906
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
907
    if (print_value(item, 0, format, buffer, hooks) == NULL)
M
Max Bruckner 已提交
908 909 910
    {
        goto fail;
    }
911
    update_offset(buffer);
M
Max Bruckner 已提交
912 913

    /* copy the buffer over to a new one */
914
    printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
M
Max Bruckner 已提交
915 916 917 918 919 920 921 922
    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 */
923
    hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
924 925 926 927 928 929

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
930
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
931 932 933 934
    }

    if (printed != NULL)
    {
935
        hooks->deallocate(printed);
M
Max Bruckner 已提交
936 937 938 939 940
    }

    return NULL;
}

K
Kevin Branigan 已提交
941
/* Render a cJSON item/entity/structure to text. */
942
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
943
{
944
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
945 946
}

947
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
948
{
949
    return (char*)print(item, false, &global_hooks);
950
}
951

952
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
953
{
M
Max Bruckner 已提交
954
    printbuffer p;
M
Max Bruckner 已提交
955 956 957

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
958
        return NULL;
M
Max Bruckner 已提交
959 960
    }

961
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
962 963
    if (!p.buffer)
    {
964
        return NULL;
965
    }
M
Max Bruckner 已提交
966 967

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
968
    p.offset = 0;
969
    p.noalloc = false;
M
Max Bruckner 已提交
970

971
    return (char*)print_value(item, 0, fmt, &p, &global_hooks);
972 973
}

974
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
975 976
{
    printbuffer p;
M
Max Bruckner 已提交
977 978 979 980 981 982

    if (len < 0)
    {
        return false;
    }

983
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
984
    p.length = (size_t)len;
985
    p.offset = 0;
986
    p.noalloc = true;
987
    return print_value(item, 0, fmt, &p, &global_hooks) != NULL;
988
}
K
Kevin Branigan 已提交
989 990

/* Parser core - when encountering text, process appropriately. */
991
static const unsigned  char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
992
{
993
    if (input == NULL)
M
Max Bruckner 已提交
994
    {
995
        return NULL; /* no input */
M
Max Bruckner 已提交
996 997 998
    }

    /* parse the different types of values */
999 1000
    /* null */
    if (!strncmp((const char*)input, "null", 4))
M
Max Bruckner 已提交
1001 1002
    {
        item->type = cJSON_NULL;
1003
        return input + 4;
M
Max Bruckner 已提交
1004
    }
1005 1006
    /* false */
    if (!strncmp((const char*)input, "false", 5))
M
Max Bruckner 已提交
1007 1008
    {
        item->type = cJSON_False;
1009
        return input + 5;
M
Max Bruckner 已提交
1010
    }
1011 1012
    /* true */
    if (!strncmp((const char*)input, "true", 4))
M
Max Bruckner 已提交
1013 1014 1015
    {
        item->type = cJSON_True;
        item->valueint = 1;
1016
        return input + 4;
M
Max Bruckner 已提交
1017
    }
1018 1019
    /* string */
    if (*input == '\"')
M
Max Bruckner 已提交
1020
    {
1021
        return parse_string(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1022
    }
1023 1024
    /* number */
    if ((*input == '-') || ((*input >= '0') && (*input <= '9')))
M
Max Bruckner 已提交
1025
    {
1026
        return parse_number(item, input);
M
Max Bruckner 已提交
1027
    }
1028 1029
    /* array */
    if (*input == '[')
M
Max Bruckner 已提交
1030
    {
1031
        return parse_array(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1032
    }
1033 1034
    /* object */
    if (*input == '{')
M
Max Bruckner 已提交
1035
    {
1036
        return parse_object(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1037 1038
    }

M
Max Bruckner 已提交
1039
    /* failure. */
1040
    *error_pointer = input;
1041
    return NULL;
K
Kevin Branigan 已提交
1042 1043 1044
}

/* Render a value to text. */
1045
static unsigned char *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 已提交
1046
{
M
Max Bruckner 已提交
1047
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1048

M
Max Bruckner 已提交
1049
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1050 1051 1052 1053 1054
    {
        return NULL;
    }

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1055
    {
M
Max Bruckner 已提交
1056
        case cJSON_NULL:
1057
            output = ensure(output_buffer, 5, hooks);
M
Max Bruckner 已提交
1058
            if (output != NULL)
M
Max Bruckner 已提交
1059
            {
M
Max Bruckner 已提交
1060
                strcpy((char*)output, "null");
M
Max Bruckner 已提交
1061 1062 1063
            }
            break;
        case cJSON_False:
1064
            output = ensure(output_buffer, 6, hooks);
M
Max Bruckner 已提交
1065
            if (output != NULL)
M
Max Bruckner 已提交
1066
            {
M
Max Bruckner 已提交
1067
                strcpy((char*)output, "false");
M
Max Bruckner 已提交
1068 1069 1070
            }
            break;
        case cJSON_True:
1071
            output = ensure(output_buffer, 5, hooks);
M
Max Bruckner 已提交
1072
            if (output != NULL)
M
Max Bruckner 已提交
1073
            {
M
Max Bruckner 已提交
1074
                strcpy((char*)output, "true");
M
Max Bruckner 已提交
1075 1076 1077
            }
            break;
        case cJSON_Number:
1078
            output = print_number(item, output_buffer, hooks);
M
Max Bruckner 已提交
1079 1080
            break;
        case cJSON_Raw:
M
Max Bruckner 已提交
1081
        {
M
Max Bruckner 已提交
1082 1083
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1084
            {
M
Max Bruckner 已提交
1085
                if (!output_buffer->noalloc)
J
Jiri Zouhar 已提交
1086
                {
1087
                    hooks->deallocate(output_buffer->buffer);
J
Jiri Zouhar 已提交
1088
                }
M
Max Bruckner 已提交
1089
                output = NULL;
1090
                break;
M
Max Bruckner 已提交
1091 1092 1093
            }

            raw_length = strlen(item->valuestring) + sizeof('\0');
1094
            output = ensure(output_buffer, raw_length, hooks);
M
Max Bruckner 已提交
1095
            if (output != NULL)
M
Max Bruckner 已提交
1096
            {
M
Max Bruckner 已提交
1097
                memcpy(output, item->valuestring, raw_length);
M
Max Bruckner 已提交
1098 1099
            }
            break;
M
Max Bruckner 已提交
1100
        }
M
Max Bruckner 已提交
1101
        case cJSON_String:
1102
            output = print_string(item, output_buffer, hooks);
M
Max Bruckner 已提交
1103 1104
            break;
        case cJSON_Array:
1105
            output = print_array(item, depth, format, output_buffer, hooks);
M
Max Bruckner 已提交
1106 1107
            break;
        case cJSON_Object:
1108
            output = print_object(item, depth, format, output_buffer, hooks);
M
Max Bruckner 已提交
1109 1110
            break;
        default:
M
Max Bruckner 已提交
1111
            output = NULL;
M
Max Bruckner 已提交
1112
            break;
M
Max Bruckner 已提交
1113 1114
    }

M
Max Bruckner 已提交
1115
    return output;
K
Kevin Branigan 已提交
1116 1117 1118
}

/* Build an array from input text. */
1119
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1120
{
1121
    cJSON *head = NULL; /* head of the linked list */
1122 1123
    cJSON *current_item = NULL;

1124
    if (*input != '[')
M
Max Bruckner 已提交
1125
    {
1126
        /* not an array */
1127
        *error_pointer = input;
1128
        goto fail;
M
Max Bruckner 已提交
1129
    }
K
Kevin Branigan 已提交
1130

M
Max Bruckner 已提交
1131
    input = skip_whitespace(input + 1);
1132
    if (*input == ']')
M
Max Bruckner 已提交
1133
    {
1134
        /* empty array */
1135
        goto success;
M
Max Bruckner 已提交
1136
    }
K
Kevin Branigan 已提交
1137

1138
    /* step back to character in front of the first element */
1139
    input--;
M
Max Bruckner 已提交
1140
    /* loop through the comma separated array elements */
1141
    do
M
Max Bruckner 已提交
1142
    {
1143
        /* allocate next item */
1144
        cJSON *new_item = cJSON_New_Item(hooks);
1145
        if (new_item == NULL)
M
Max Bruckner 已提交
1146
        {
1147
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1148
        }
1149 1150 1151

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1152
        {
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
            /* 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 已提交
1165
        input = skip_whitespace(input + 1);
1166
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1167
        input = skip_whitespace(input);
1168
        if (input == NULL)
1169 1170
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1171 1172
        }
    }
1173
    while (*input == ',');
M
Max Bruckner 已提交
1174

1175
    if (*input != ']')
M
Max Bruckner 已提交
1176
    {
1177 1178
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1179 1180
    }

1181 1182
success:
    item->type = cJSON_Array;
1183
    item->child = head;
1184

1185
    return input + 1;
K
Kevin Branigan 已提交
1186

1187
fail:
1188
    if (head != NULL)
1189
    {
1190
        cJSON_Delete(head);
1191 1192
    }

1193
    return NULL;
K
Kevin Branigan 已提交
1194 1195 1196
}

/* Render an array to text */
1197
static unsigned char *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 已提交
1198
{
M
Max Bruckner 已提交
1199 1200
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1201
    size_t length = 0;
M
Max Bruckner 已提交
1202
    cJSON *current_element = item->child;
M
Max Bruckner 已提交
1203
    size_t output_offset = 0;
M
Max Bruckner 已提交
1204

M
Max Bruckner 已提交
1205
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1206 1207 1208
    {
        return NULL;
    }
K
Kevin Branigan 已提交
1209

M
Max Bruckner 已提交
1210 1211
    /* Compose the output array. */
    /* opening square bracket */
M
Max Bruckner 已提交
1212
    output_offset = output_buffer->offset;
1213
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1214
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1215
    {
M
Max Bruckner 已提交
1216 1217
        return NULL;
    }
M
Max Bruckner 已提交
1218

M
Max Bruckner 已提交
1219 1220
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1221

M
Max Bruckner 已提交
1222
    while (current_element != NULL)
M
Max Bruckner 已提交
1223
    {
1224
        if (print_value(current_element, depth + 1, format, output_buffer, hooks) == NULL)
M
Max Bruckner 已提交
1225
        {
1226
            return NULL;
M
Max Bruckner 已提交
1227
        }
1228
        update_offset(output_buffer);
M
Max Bruckner 已提交
1229
        if (current_element->next)
M
Max Bruckner 已提交
1230
        {
M
Max Bruckner 已提交
1231
            length = format ? 2 : 1;
1232
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1233
            if (output_pointer == NULL)
1234 1235 1236
            {
                return NULL;
            }
M
Max Bruckner 已提交
1237 1238
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1239
            {
M
Max Bruckner 已提交
1240
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1241
            }
M
Max Bruckner 已提交
1242 1243
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1244
        }
M
Max Bruckner 已提交
1245
        current_element = current_element->next;
M
Max Bruckner 已提交
1246
    }
M
Max Bruckner 已提交
1247

1248
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1249
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1250
    {
M
Max Bruckner 已提交
1251
        return NULL;
M
Max Bruckner 已提交
1252
    }
M
Max Bruckner 已提交
1253 1254
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1255
    output = output_buffer->buffer + output_offset;
M
Max Bruckner 已提交
1256

M
Max Bruckner 已提交
1257
    return output;
K
Kevin Branigan 已提交
1258 1259 1260
}

/* Build an object from the text. */
1261
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1262
{
1263
    cJSON *head = NULL; /* linked list head */
1264 1265
    cJSON *current_item = NULL;

1266
    if (*input != '{')
M
Max Bruckner 已提交
1267
    {
1268 1269
        *error_pointer = input;
        goto fail; /* not an object */
M
Max Bruckner 已提交
1270 1271
    }

M
Max Bruckner 已提交
1272
    input = skip_whitespace(input + 1);
1273
    if (*input == '}')
M
Max Bruckner 已提交
1274
    {
1275
        goto success; /* empty object */
M
Max Bruckner 已提交
1276 1277
    }

1278
    /* step back to character in front of the first element */
1279
    input--;
1280 1281
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1282
    {
1283
        /* allocate next item */
1284
        cJSON *new_item = cJSON_New_Item(hooks);
1285 1286 1287 1288
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1289

1290 1291
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1292
        {
1293 1294 1295 1296 1297 1298 1299 1300 1301
            /* 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 已提交
1302 1303
        }

1304
        /* parse the name of the child */
M
Max Bruckner 已提交
1305
        input = skip_whitespace(input + 1);
1306
        input = parse_string(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1307
        input = skip_whitespace(input);
1308
        if (input == NULL)
M
Max Bruckner 已提交
1309
        {
1310
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1311 1312
        }

1313 1314 1315
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1316

1317
        if (*input != ':')
M
Max Bruckner 已提交
1318
        {
1319 1320
            *error_pointer = input;
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1321
        }
1322 1323

        /* parse the value */
M
Max Bruckner 已提交
1324
        input = skip_whitespace(input + 1);
1325
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1326
        input = skip_whitespace(input);
1327
        if (input == NULL)
M
Max Bruckner 已提交
1328
        {
1329
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1330 1331
        }
    }
1332
    while (*input == ',');
1333

1334
    if (*input != '}')
M
Max Bruckner 已提交
1335
    {
1336 1337
        *error_pointer = input;
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1338 1339
    }

1340 1341
success:
    item->type = cJSON_Object;
1342
    item->child = head;
1343

1344
    return input + 1;
1345 1346

fail:
1347
    if (head != NULL)
1348
    {
1349
        cJSON_Delete(head);
1350 1351
    }

1352
    return NULL;
K
Kevin Branigan 已提交
1353 1354 1355
}

/* Render an object to text. */
1356
static unsigned char *print_object(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
1357
{
M
Max Bruckner 已提交
1358 1359
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1360 1361
    size_t length = 0;
    size_t output_offset = 0;
M
Max Bruckner 已提交
1362
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1363

M
Max Bruckner 已提交
1364
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1365 1366 1367
    {
        return NULL;
    }
M
Max Bruckner 已提交
1368

M
Max Bruckner 已提交
1369
    /* Compose the output: */
M
Max Bruckner 已提交
1370
    output_offset = output_buffer->offset;
M
Max Bruckner 已提交
1371
    length = format ? 2 : 1; /* fmt: {\n */
1372
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1373
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1374
    {
M
Max Bruckner 已提交
1375 1376
        return NULL;
    }
M
Max Bruckner 已提交
1377

M
Max Bruckner 已提交
1378 1379
    *output_pointer++ = '{';
    if (format)
M
Max Bruckner 已提交
1380
    {
M
Max Bruckner 已提交
1381
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1382
    }
M
Max Bruckner 已提交
1383
    output_buffer->offset += length;
M
Max Bruckner 已提交
1384

M
Max Bruckner 已提交
1385
    while (current_item)
M
Max Bruckner 已提交
1386
    {
M
Max Bruckner 已提交
1387
        if (format)
M
Max Bruckner 已提交
1388
        {
M
Max Bruckner 已提交
1389
            size_t i;
1390
            output_pointer = ensure(output_buffer, depth + 1, hooks);
M
Max Bruckner 已提交
1391
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1392
            {
1393
                return NULL;
M
Max Bruckner 已提交
1394
            }
M
Max Bruckner 已提交
1395
            for (i = 0; i < depth + 1; i++)
M
Max Bruckner 已提交
1396
            {
M
Max Bruckner 已提交
1397
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1398
            }
M
Max Bruckner 已提交
1399
            output_buffer->offset += depth + 1;
M
Max Bruckner 已提交
1400 1401
        }

M
Max Bruckner 已提交
1402
        /* print key */
1403
        if (print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks) == NULL)
M
Max Bruckner 已提交
1404
        {
1405
            return NULL;
M
Max Bruckner 已提交
1406
        }
M
Max Bruckner 已提交
1407
        update_offset(output_buffer);
M
Max Bruckner 已提交
1408

M
Max Bruckner 已提交
1409
        length = format ? 2 : 1;
1410
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1411
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1412
        {
1413
            return NULL;
M
Max Bruckner 已提交
1414
        }
M
Max Bruckner 已提交
1415 1416
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1417
        {
M
Max Bruckner 已提交
1418
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1419
        }
M
Max Bruckner 已提交
1420
        output_buffer->offset += length;
M
Max Bruckner 已提交
1421

M
Max Bruckner 已提交
1422
        /* print value */
1423
        if (!print_value(current_item, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1424
        {
M
Max Bruckner 已提交
1425
            return NULL;
M
Max Bruckner 已提交
1426
        }
M
Max Bruckner 已提交
1427
        update_offset(output_buffer);
M
Max Bruckner 已提交
1428

M
Max Bruckner 已提交
1429
        /* print comma if not last */
M
Max Bruckner 已提交
1430
        length = (size_t) (format ? 1 : 0) + (current_item->next ? 1 : 0);
1431
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1432
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1433
        {
1434
            return NULL;
M
Max Bruckner 已提交
1435
        }
M
Max Bruckner 已提交
1436
        if (current_item->next)
M
Max Bruckner 已提交
1437
        {
M
Max Bruckner 已提交
1438
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1439
        }
M
Max Bruckner 已提交
1440

M
Max Bruckner 已提交
1441
        if (format)
M
Max Bruckner 已提交
1442
        {
M
Max Bruckner 已提交
1443
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1444
        }
M
Max Bruckner 已提交
1445 1446
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1447

M
Max Bruckner 已提交
1448
        current_item = current_item->next;
M
Max Bruckner 已提交
1449 1450
    }

1451
    output_pointer = ensure(output_buffer, format ? (depth + 2) : 2, hooks);
M
Max Bruckner 已提交
1452
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1453 1454 1455
    {
        return NULL;
    }
M
Max Bruckner 已提交
1456
    if (format)
M
Max Bruckner 已提交
1457
    {
M
Max Bruckner 已提交
1458 1459
        size_t i;
        for (i = 0; i < (depth); i++)
M
Max Bruckner 已提交
1460
        {
M
Max Bruckner 已提交
1461
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1462 1463
        }
    }
M
Max Bruckner 已提交
1464 1465
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1466
    output = (output_buffer->buffer) + output_offset;
M
Max Bruckner 已提交
1467

M
Max Bruckner 已提交
1468
    return output;
K
Kevin Branigan 已提交
1469 1470 1471
}

/* Get Array size/item / object item. */
1472
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1473 1474
{
    cJSON *c = array->child;
1475
    size_t i = 0;
M
Max Bruckner 已提交
1476 1477 1478 1479 1480
    while(c)
    {
        i++;
        c = c->next;
    }
1481 1482 1483

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

M
Max Bruckner 已提交
1484
    return (int)i;
M
Max Bruckner 已提交
1485 1486
}

1487
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1488
{
1489
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1490 1491 1492 1493 1494 1495 1496 1497 1498
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1499
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1500
{
1501
    cJSON *c = object ? object->child : NULL;
1502
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1503 1504 1505 1506 1507 1508
    {
        c = c->next;
    }
    return c;
}

1509
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
{
    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;
}

1527
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1528 1529 1530
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1531 1532

/* Utility for array list handling. */
M
Max Bruckner 已提交
1533 1534 1535 1536 1537 1538
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1539
/* Utility for handling references. */
1540
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1541
{
1542
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1543 1544
    if (!ref)
    {
1545
        return NULL;
M
Max Bruckner 已提交
1546 1547
    }
    memcpy(ref, item, sizeof(cJSON));
1548
    ref->string = NULL;
M
Max Bruckner 已提交
1549
    ref->type |= cJSON_IsReference;
1550
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1551 1552
    return ref;
}
K
Kevin Branigan 已提交
1553 1554

/* Add item to array/object. */
1555
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1556
{
1557 1558 1559
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1560 1561 1562
    {
        return;
    }
1563 1564 1565 1566

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1567 1568 1569 1570 1571 1572 1573
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1574
        while (child->next)
M
Max Bruckner 已提交
1575
        {
1576
            child = child->next;
M
Max Bruckner 已提交
1577
        }
1578
        suffix_object(child, item);
M
Max Bruckner 已提交
1579 1580 1581
    }
}

1582
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1583
{
1584
    /* call cJSON_AddItemToObjectCS for code reuse */
1585
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1586 1587
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1588 1589
}

1590
/* Add an item to an object with constant string as key */
1591
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1592 1593 1594 1595 1596 1597 1598
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1599
        global_hooks.deallocate(item->string);
1600
    }
1601 1602
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1603
    item->string = (char*)string;
1604
#pragma GCC diagnostic pop
1605 1606 1607 1608
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1609
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1610
{
1611
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1612 1613
}

1614
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1615
{
1616
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1617 1618
}

M
Max Bruckner 已提交
1619
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1630
        return NULL;
1631
    }
1632
    if (c->prev)
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    {
        /* 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 */
1646
    c->prev = c->next = NULL;
1647 1648 1649

    return c;
}
1650
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1651 1652 1653 1654 1655 1656 1657 1658
{
    if (which < 0)
    {
        return NULL;
    }

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

1660
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1661 1662 1663 1664
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1665
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1666
{
1667
    size_t i = 0;
1668
    cJSON *c = object->child;
1669
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1670 1671 1672 1673 1674 1675
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1676
        return DetachItemFromArray(object, i);
1677 1678
    }

1679
    return NULL;
1680 1681
}

1682
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1683 1684 1685
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1686 1687

/* Replace array/object items with new ones. */
1688
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
{
    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 已提交
1714
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
{
    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;
    }
1740
    c->next = c->prev = NULL;
1741 1742
    cJSON_Delete(c);
}
1743
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
1744 1745 1746 1747 1748 1749 1750 1751
{
    if (which < 0)
    {
        return;
    }

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

1753
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1754
{
1755
    size_t i = 0;
1756
    cJSON *c = object->child;
1757
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1758 1759 1760 1761 1762 1763
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1764 1765 1766
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1767
             global_hooks.deallocate(newitem->string);
1768 1769
        }

1770
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1771
        ReplaceItemInArray(object, i, newitem);
1772 1773
    }
}
K
Kevin Branigan 已提交
1774 1775

/* Create basic types: */
1776
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
1777
{
1778
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1779 1780 1781 1782 1783 1784 1785 1786
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

1787
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
1788
{
1789
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1790 1791 1792 1793 1794 1795 1796 1797
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

1798
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
1799
{
1800
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1801 1802 1803 1804 1805 1806 1807 1808
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

1809
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
1810
{
1811
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1812 1813 1814 1815 1816 1817 1818 1819
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

1820
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
1821
{
1822
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1823 1824 1825 1826
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840

        /* 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 已提交
1841 1842 1843 1844 1845
    }

    return item;
}

1846
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
1847
{
1848
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1849 1850 1851
    if(item)
    {
        item->type = cJSON_String;
1852
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1853 1854 1855
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1856
            return NULL;
M
Max Bruckner 已提交
1857 1858 1859 1860 1861 1862
        }
    }

    return item;
}

1863
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
1864
{
1865
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1866 1867 1868
    if(item)
    {
        item->type = cJSON_Raw;
1869
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
1870 1871 1872 1873 1874 1875 1876 1877
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
1878 1879
}

1880
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
1881
{
1882
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1883 1884 1885 1886 1887 1888 1889 1890
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

1891
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
1892
{
1893
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1894 1895 1896 1897 1898 1899 1900
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
1901 1902

/* Create Arrays: */
1903
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
1904
{
1905
    size_t i = 0;
1906 1907
    cJSON *n = NULL;
    cJSON *p = NULL;
1908 1909 1910 1911 1912 1913 1914 1915 1916
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1917 1918 1919 1920 1921
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
1922
            return NULL;
M
Max Bruckner 已提交
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1938
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
1939
{
1940
    size_t i = 0;
1941 1942
    cJSON *n = NULL;
    cJSON *p = NULL;
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1953
    {
1954
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
1955 1956 1957
        if(!n)
        {
            cJSON_Delete(a);
1958
            return NULL;
M
Max Bruckner 已提交
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1974
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
1975
{
1976
    size_t i = 0;
1977 1978
    cJSON *n = NULL;
    cJSON *p = NULL;
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
1989 1990 1991 1992 1993
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
1994
            return NULL;
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2010
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2011
{
2012
    size_t i = 0;
2013 2014
    cJSON *n = NULL;
    cJSON *p = NULL;
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2025 2026 2027 2028 2029
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2030
            return NULL;
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2045 2046

/* Duplication */
2047
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2048
{
M
Max Bruckner 已提交
2049
    cJSON *newitem = NULL;
2050 2051
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2052
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2053 2054 2055 2056

    /* Bail on bad ptr */
    if (!item)
    {
2057
        goto fail;
M
Max Bruckner 已提交
2058 2059
    }
    /* Create new item */
2060
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2061 2062
    if (!newitem)
    {
2063
        goto fail;
M
Max Bruckner 已提交
2064 2065 2066 2067 2068 2069 2070
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2071
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2072 2073
        if (!newitem->valuestring)
        {
2074
            goto fail;
M
Max Bruckner 已提交
2075 2076 2077 2078
        }
    }
    if (item->string)
    {
2079
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2080 2081
        if (!newitem->string)
        {
2082
            goto fail;
M
Max Bruckner 已提交
2083 2084 2085 2086 2087 2088 2089 2090
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2091 2092
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2093
    {
2094
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2095 2096
        if (!newchild)
        {
2097
            goto fail;
M
Max Bruckner 已提交
2098
        }
2099
        if (next != NULL)
M
Max Bruckner 已提交
2100 2101
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2102 2103 2104
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2105 2106 2107 2108
        }
        else
        {
            /* Set newitem->child and move to it */
2109 2110
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2111
        }
2112
        child = child->next;
M
Max Bruckner 已提交
2113 2114 2115
    }

    return newitem;
2116 2117 2118 2119 2120 2121 2122 2123

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

    return NULL;
2124
}
2125

2126
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2127
{
2128
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
    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 已提交
2168
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2169 2170 2171 2172
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2173
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2174
                }
M
Max Bruckner 已提交
2175
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2176
            }
M
Max Bruckner 已提交
2177
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2178 2179 2180 2181
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2182
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2183 2184 2185 2186 2187
        }
    }

    /* and null-terminate. */
    *into = '\0';
2188
}
2189

2190
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2191 2192 2193 2194 2195 2196 2197 2198 2199
{
    if (item == NULL)
    {
        return false;
    }

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

2200
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2201 2202 2203 2204 2205 2206 2207 2208 2209
{
    if (item == NULL)
    {
        return false;
    }

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

2210
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
{
    if (item == NULL)
    {
        return false;
    }

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


2221
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2222 2223 2224 2225 2226 2227 2228 2229
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2230
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2231 2232 2233 2234 2235 2236 2237 2238 2239
{
    if (item == NULL)
    {
        return false;
    }

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

2240
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2241 2242 2243 2244 2245 2246 2247 2248 2249
{
    if (item == NULL)
    {
        return false;
    }

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

2250
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2251 2252 2253 2254 2255 2256 2257 2258 2259
{
    if (item == NULL)
    {
        return false;
    }

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

2260
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2261 2262 2263 2264 2265 2266 2267 2268 2269
{
    if (item == NULL)
    {
        return false;
    }

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

2270
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2271 2272 2273 2274 2275 2276 2277 2278 2279
{
    if (item == NULL)
    {
        return false;
    }

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

2280
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2281 2282 2283 2284 2285 2286 2287 2288
{
    if (item == NULL)
    {
        return false;
    }

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