cJSON.c 55.9 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 != 5)
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];
}

K
Kevin Branigan 已提交
188
/* Parse the input text to generate a number, and populate the result into item. */
189
static const unsigned char *parse_number(cJSON * const item, const unsigned char * const input)
K
Kevin Branigan 已提交
190
{
191
    double number = 0;
192
    unsigned char *after_end = NULL;
193 194 195
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;
M
Max Bruckner 已提交
196

197
    if (input == NULL)
198 199 200 201
    {
        return NULL;
    }

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    /* 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 已提交
238
    {
239
        return NULL; /* parse_error */
M
Max Bruckner 已提交
240 241
    }

242
    item->valuedouble = number;
M
Max Bruckner 已提交
243

244
    /* use saturation in case of overflow */
245
    if (number >= INT_MAX)
246 247 248
    {
        item->valueint = INT_MAX;
    }
249
    else if (number <= INT_MIN)
250 251 252 253 254
    {
        item->valueint = INT_MIN;
    }
    else
    {
255
        item->valueint = (int)number;
256
    }
257

M
Max Bruckner 已提交
258 259
    item->type = cJSON_Number;

260
    return input + (after_end - number_c_string);
K
Kevin Branigan 已提交
261 262
}

263
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
264
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
265 266 267 268 269 270 271 272 273 274 275
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
276
        object->valueint = (int)number;
277 278 279 280 281
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
282 283
typedef struct
{
284
    unsigned char *buffer;
285 286
    size_t length;
    size_t offset;
287
    cJSON_bool noalloc;
M
Max Bruckner 已提交
288
} printbuffer;
289

M
Max Bruckner 已提交
290
/* realloc printbuffer if necessary to have at least "needed" bytes more */
291
static unsigned char* ensure(printbuffer * const p, size_t needed, const internal_hooks * const hooks)
292
{
293
    unsigned char *newbuffer = NULL;
294 295
    size_t newsize = 0;

296
    if ((p == NULL) || (p->buffer == NULL))
297 298 299 300
    {
        return NULL;
    }

M
Max Bruckner 已提交
301 302 303 304 305 306
    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

307
    if (needed > INT_MAX)
M
Max Bruckner 已提交
308
    {
309
        /* sizes bigger than INT_MAX are currently not supported */
310
        return NULL;
M
Max Bruckner 已提交
311
    }
312

313
    needed += p->offset + 1;
M
Max Bruckner 已提交
314 315 316 317 318
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

319 320 321 322
    if (p->noalloc) {
        return NULL;
    }

323
    /* calculate new buffer size */
M
Max Bruckner 已提交
324
    if (needed > (INT_MAX / 2))
325 326 327 328 329 330 331 332 333 334 335
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
336 337 338 339
    else
    {
        newsize = needed * 2;
    }
340

341
    if (hooks->reallocate != NULL)
M
Max Bruckner 已提交
342
    {
M
Max Bruckner 已提交
343
        /* reallocate with realloc if available */
344
        newbuffer = (unsigned char*)hooks->reallocate(p->buffer, newsize);
M
Max Bruckner 已提交
345
    }
M
Max Bruckner 已提交
346
    else
M
Max Bruckner 已提交
347
    {
M
Max Bruckner 已提交
348
        /* otherwise reallocate manually */
349
        newbuffer = (unsigned char*)hooks->allocate(newsize);
M
Max Bruckner 已提交
350 351
        if (!newbuffer)
        {
352
            hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
353 354 355 356 357 358 359
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
360
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
361
        }
362
        hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
363 364 365 366 367
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
368 369
}

370 371
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
372
{
373 374
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
375
    {
376
        return;
M
Max Bruckner 已提交
377
    }
378
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
379

380
    buffer->offset += strlen((const char*)buffer_pointer);
381 382
}

383
/* Removes trailing zeroes from the end of a printed number */
384
static cJSON_bool trim_trailing_zeroes(printbuffer * const buffer)
K
Kevin Branigan 已提交
385
{
386 387 388 389 390
    size_t offset = 0;
    unsigned char *content = NULL;

    if ((buffer == NULL) || (buffer->buffer == NULL) || (buffer->offset < 1))
    {
391
        return false;
392 393 394 395 396 397
    }

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

    while ((offset > 0) && (content[offset] == '0'))
M
Max Bruckner 已提交
398
    {
399
        offset--;
M
Max Bruckner 已提交
400
    }
401 402 403 404 405 406 407
    if ((offset > 0) && (content[offset] == '.'))
    {
        offset--;
    }

    offset++;
    content[offset] = '\0';
M
Max Bruckner 已提交
408

409 410
    buffer->offset = offset;

411
    return true;
412 413 414
}

/* Render the number nicely from the given item into a string. */
415
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
416
{
M
Max Bruckner 已提交
417
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
418
    double d = item->valuedouble;
419
    int length = 0;
420
    cJSON_bool trim_zeroes = true; /* should zeroes at the end be removed? */
M
Max Bruckner 已提交
421

M
Max Bruckner 已提交
422
    if (output_buffer == NULL)
M
Max Bruckner 已提交
423
    {
424
        return false;
M
Max Bruckner 已提交
425
    }
M
Max Bruckner 已提交
426

427 428
    /* This is a nice tradeoff. */
    output_pointer = ensure(output_buffer, 64, hooks);
429
    if (output_pointer == NULL)
M
Max Bruckner 已提交
430
    {
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        return false;
    }

    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
        length = sprintf((char*)output_pointer, "null");
    }
    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
    {
        length = sprintf((char*)output_pointer, "%f", d);
M
Max Bruckner 已提交
453
    }
454

455 456 457
    /* sprintf failed */
    if (length < 0)
    {
458
        return false;
459 460 461 462
    }

    output_buffer->offset += (size_t)length;

463 464 465 466 467
    if (trim_zeroes)
    {
        return trim_trailing_zeroes(output_buffer);
    }

468
    return true;
K
Kevin Branigan 已提交
469 470
}

M
Max Bruckner 已提交
471
/* parse 4 digit hexadecimal number */
472
static unsigned parse_hex4(const unsigned char * const input)
473
{
M
Max Bruckner 已提交
474
    unsigned int h = 0;
475
    size_t i = 0;
M
Max Bruckner 已提交
476

477
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
478
    {
479
        /* parse digit */
480
        if ((input[i] >= '0') && (input[i] <= '9'))
481
        {
482
            h += (unsigned int) input[i] - '0';
483
        }
484
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
485
        {
486
            h += (unsigned int) 10 + input[i] - 'A';
487
        }
488
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
489
        {
490
            h += (unsigned int) 10 + input[i] - 'a';
491 492 493 494 495
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
496

497 498 499 500 501
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
502 503 504
    }

    return h;
505 506
}

507 508
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
509
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 已提交
510
{
511 512 513
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
514
    unsigned char utf8_length = 0;
515
    unsigned char utf8_position = 0;
516
    unsigned char sequence_length = 0;
517
    unsigned char first_byte_mark = 0;
518 519 520 521 522 523 524

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

526 527 528
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

529 530
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
531
    {
532
        *error_pointer = first_sequence;
533
        goto fail;
M
Max Bruckner 已提交
534
    }
M
Max Bruckner 已提交
535

536 537
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
538
    {
539 540 541 542 543
        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 已提交
544
        {
545 546 547
            /* input ends unexpectedly */
            *error_pointer = first_sequence;
            goto fail;
M
Max Bruckner 已提交
548
        }
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574

        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 已提交
575
    }
M
Max Bruckner 已提交
576

577 578 579 580 581 582 583 584 585 586 587 588
    /* 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;
589
        first_byte_mark = 0xC0; /* 11000000 */
590 591 592 593 594
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
595
        first_byte_mark = 0xE0; /* 11100000 */
596 597 598 599 600
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
601
        first_byte_mark = 0xF0; /* 11110000 */
602 603
    }
    else
M
Max Bruckner 已提交
604
    {
605 606
        /* invalid unicode codepoint */
        *error_pointer = first_sequence;
607
        goto fail;
M
Max Bruckner 已提交
608 609
    }

610
    /* encode as utf8 */
611 612 613 614 615
    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;
616
    }
617 618 619 620 621 622 623 624
    /* 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);
625
    }
626

627 628 629 630 631 632 633 634 635
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
636
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)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
{
    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;
676
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof(""));
677 678 679 680 681 682 683
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
684
    /* loop through the string literal */
685
    while (input_pointer < input_end)
M
Max Bruckner 已提交
686
    {
687
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
688
        {
689
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
690 691 692 693
        }
        /* escape sequence */
        else
        {
694
            unsigned char sequence_length = 2;
695
            switch (input_pointer[1])
M
Max Bruckner 已提交
696 697
            {
                case 'b':
698
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
699 700
                    break;
                case 'f':
701
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
702 703
                    break;
                case 'n':
704
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
705 706
                    break;
                case 'r':
707
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
708 709
                    break;
                case 't':
710
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
711
                    break;
712 713 714
                case '\"':
                case '\\':
                case '/':
715
                    *output_pointer++ = input_pointer[1];
716
                    break;
717 718

                /* UTF-16 literal */
M
Max Bruckner 已提交
719
                case 'u':
720 721
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer, error_pointer);
                    if (sequence_length == 0)
M
Max Bruckner 已提交
722
                    {
723
                        /* failed to convert UTF16-literal to UTF-8 */
724
                        goto fail;
M
Max Bruckner 已提交
725 726
                    }
                    break;
727

M
Max Bruckner 已提交
728
                default:
729
                    *error_pointer = input_pointer;
730
                    goto fail;
M
Max Bruckner 已提交
731
            }
732
            input_pointer += sequence_length;
M
Max Bruckner 已提交
733 734
        }
    }
735 736 737

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

739
    item->type = cJSON_String;
740
    item->valuestring = (char*)output;
741

742
    return input_end + 1;
743 744

fail:
745
    if (output != NULL)
746
    {
747
        hooks->deallocate(output);
748 749 750
    }

    return NULL;
K
Kevin Branigan 已提交
751 752 753
}

/* Render the cstring provided to an escaped version that can be printed. */
754
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
755
{
756 757 758
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
759 760 761
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
762

763
    if (output_buffer == NULL)
M
Max Bruckner 已提交
764
    {
765
        return false;
M
Max Bruckner 已提交
766 767 768
    }

    /* empty string */
769
    if (input == NULL)
M
Max Bruckner 已提交
770
    {
771
        output = ensure(output_buffer, sizeof("\"\""), hooks);
772
        if (output == NULL)
M
Max Bruckner 已提交
773
        {
774
            return false;
M
Max Bruckner 已提交
775
        }
776
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
777

778
        return true;
M
Max Bruckner 已提交
779 780 781
    }

    /* set "flag" to 1 if something needs to be escaped */
782
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
783
    {
M
Max Bruckner 已提交
784
        if (strchr("\"\\\b\f\n\r\t", *input_pointer))
M
Max Bruckner 已提交
785
        {
M
Max Bruckner 已提交
786 787
            /* one character escape sequence */
            escape_characters++;
M
Max Bruckner 已提交
788
        }
M
Max Bruckner 已提交
789
        else if (*input_pointer < 32)
M
Max Bruckner 已提交
790
        {
M
Max Bruckner 已提交
791 792
            /* UTF-16 escape sequence uXXXX */
            escape_characters += 5;
M
Max Bruckner 已提交
793 794
        }
    }
M
Max Bruckner 已提交
795
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
796

797
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
798
    if (output == NULL)
M
Max Bruckner 已提交
799
    {
800
        return false;
M
Max Bruckner 已提交
801 802
    }

M
Max Bruckner 已提交
803 804
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
805
    {
M
Max Bruckner 已提交
806 807 808 809 810
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

811
        return true;
M
Max Bruckner 已提交
812 813
    }

M
Max Bruckner 已提交
814 815
    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
816
    /* copy the string */
M
Max Bruckner 已提交
817
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
818
    {
819
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
820 821
        {
            /* normal character, copy */
M
Max Bruckner 已提交
822
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
823 824 825 826
        }
        else
        {
            /* character needs to be escaped */
827
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
828
            switch (*input_pointer)
M
Max Bruckner 已提交
829 830
            {
                case '\\':
M
Max Bruckner 已提交
831
                    *output_pointer = '\\';
M
Max Bruckner 已提交
832 833
                    break;
                case '\"':
M
Max Bruckner 已提交
834
                    *output_pointer = '\"';
M
Max Bruckner 已提交
835 836
                    break;
                case '\b':
M
Max Bruckner 已提交
837
                    *output_pointer = 'b';
M
Max Bruckner 已提交
838 839
                    break;
                case '\f':
M
Max Bruckner 已提交
840
                    *output_pointer = 'f';
M
Max Bruckner 已提交
841 842
                    break;
                case '\n':
M
Max Bruckner 已提交
843
                    *output_pointer = 'n';
M
Max Bruckner 已提交
844 845
                    break;
                case '\r':
M
Max Bruckner 已提交
846
                    *output_pointer = 'r';
M
Max Bruckner 已提交
847 848
                    break;
                case '\t':
M
Max Bruckner 已提交
849
                    *output_pointer = 't';
M
Max Bruckner 已提交
850 851 852
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
853 854
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
855 856 857 858
                    break;
            }
        }
    }
M
Max Bruckner 已提交
859 860
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
861

862
    return true;
K
Kevin Branigan 已提交
863
}
M
Max Bruckner 已提交
864

M
Max Bruckner 已提交
865
/* Invoke print_string_ptr (which is useful) on an item. */
866
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
867
{
868
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
869
}
K
Kevin Branigan 已提交
870 871

/* Predeclare these prototypes. */
872
static const unsigned char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const ep, const internal_hooks * const hooks);
873
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);
874
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
875
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);
876
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
877
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 已提交
878 879

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
880
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
881
{
882
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
883 884 885 886 887 888
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
889 890

/* Parse an object - create a new root, and populate. */
891
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
892
{
893
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
894
    /* use global error pointer if no specific one was given */
895
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
896
    cJSON *c = cJSON_New_Item(&global_hooks);
897
    *ep = NULL;
M
Max Bruckner 已提交
898 899
    if (!c) /* memory fail */
    {
900
        return NULL;
M
Max Bruckner 已提交
901 902
    }

903
    end = parse_value(c, skip_whitespace((const unsigned char*)value), ep, &global_hooks);
M
Max Bruckner 已提交
904 905 906 907
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
908
        return NULL;
M
Max Bruckner 已提交
909 910 911 912 913
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
914
        end = skip_whitespace(end);
M
Max Bruckner 已提交
915 916 917 918
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
919
            return NULL;
M
Max Bruckner 已提交
920 921 922 923
        }
    }
    if (return_parse_end)
    {
924
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
925 926 927
    }

    return c;
K
Kevin Branigan 已提交
928
}
M
Max Bruckner 已提交
929

930
/* Default options for cJSON_Parse */
931
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
932 933 934
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
935

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

938
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
939 940 941 942 943 944 945
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
946
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
947 948 949 950 951 952
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
953
    if (!print_value(item, 0, format, buffer, hooks))
M
Max Bruckner 已提交
954 955 956
    {
        goto fail;
    }
957
    update_offset(buffer);
M
Max Bruckner 已提交
958 959

    /* copy the buffer over to a new one */
960
    printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
M
Max Bruckner 已提交
961 962 963 964 965 966 967 968
    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 */
969
    hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
970 971 972 973 974 975

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
976
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
977 978 979 980
    }

    if (printed != NULL)
    {
981
        hooks->deallocate(printed);
M
Max Bruckner 已提交
982 983 984 985 986
    }

    return NULL;
}

K
Kevin Branigan 已提交
987
/* Render a cJSON item/entity/structure to text. */
988
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
989
{
990
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
991 992
}

993
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
994
{
995
    return (char*)print(item, false, &global_hooks);
996
}
997

998
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
999
{
M
Max Bruckner 已提交
1000
    printbuffer p;
M
Max Bruckner 已提交
1001 1002 1003

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
1004
        return NULL;
M
Max Bruckner 已提交
1005 1006
    }

1007
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
1008 1009
    if (!p.buffer)
    {
1010
        return NULL;
1011
    }
M
Max Bruckner 已提交
1012 1013

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
1014
    p.offset = 0;
1015
    p.noalloc = false;
M
Max Bruckner 已提交
1016

1017 1018 1019 1020 1021 1022
    if (!print_value(item, 0, fmt, &p, &global_hooks))
    {
        return NULL;
    }

    return (char*)p.buffer;
1023 1024
}

1025
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
1026 1027
{
    printbuffer p;
M
Max Bruckner 已提交
1028 1029 1030 1031 1032 1033

    if (len < 0)
    {
        return false;
    }

1034
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
1035
    p.length = (size_t)len;
1036
    p.offset = 0;
1037
    p.noalloc = true;
1038
    return print_value(item, 0, fmt, &p, &global_hooks);
1039
}
K
Kevin Branigan 已提交
1040 1041

/* Parser core - when encountering text, process appropriately. */
1042
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 已提交
1043
{
1044
    if (input == NULL)
M
Max Bruckner 已提交
1045
    {
1046
        return NULL; /* no input */
M
Max Bruckner 已提交
1047 1048 1049
    }

    /* parse the different types of values */
1050 1051
    /* null */
    if (!strncmp((const char*)input, "null", 4))
M
Max Bruckner 已提交
1052 1053
    {
        item->type = cJSON_NULL;
1054
        return input + 4;
M
Max Bruckner 已提交
1055
    }
1056 1057
    /* false */
    if (!strncmp((const char*)input, "false", 5))
M
Max Bruckner 已提交
1058 1059
    {
        item->type = cJSON_False;
1060
        return input + 5;
M
Max Bruckner 已提交
1061
    }
1062 1063
    /* true */
    if (!strncmp((const char*)input, "true", 4))
M
Max Bruckner 已提交
1064 1065 1066
    {
        item->type = cJSON_True;
        item->valueint = 1;
1067
        return input + 4;
M
Max Bruckner 已提交
1068
    }
1069 1070
    /* string */
    if (*input == '\"')
M
Max Bruckner 已提交
1071
    {
1072
        return parse_string(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1073
    }
1074 1075
    /* number */
    if ((*input == '-') || ((*input >= '0') && (*input <= '9')))
M
Max Bruckner 已提交
1076
    {
1077
        return parse_number(item, input);
M
Max Bruckner 已提交
1078
    }
1079 1080
    /* array */
    if (*input == '[')
M
Max Bruckner 已提交
1081
    {
1082
        return parse_array(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1083
    }
1084 1085
    /* object */
    if (*input == '{')
M
Max Bruckner 已提交
1086
    {
1087
        return parse_object(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1088 1089
    }

M
Max Bruckner 已提交
1090
    /* failure. */
1091
    *error_pointer = input;
1092
    return NULL;
K
Kevin Branigan 已提交
1093 1094 1095
}

/* Render a value to text. */
1096
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 已提交
1097
{
M
Max Bruckner 已提交
1098
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1099

M
Max Bruckner 已提交
1100
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1101
    {
1102
        return false;
M
Max Bruckner 已提交
1103
    }
M
Max Bruckner 已提交
1104 1105

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1106
    {
M
Max Bruckner 已提交
1107
        case cJSON_NULL:
1108
            output = ensure(output_buffer, 5, hooks);
1109
            if (output == NULL)
M
Max Bruckner 已提交
1110
            {
1111
                return false;
M
Max Bruckner 已提交
1112
            }
1113 1114 1115
            strcpy((char*)output, "null");
            return true;

M
Max Bruckner 已提交
1116
        case cJSON_False:
1117
            output = ensure(output_buffer, 6, hooks);
1118
            if (output == NULL)
M
Max Bruckner 已提交
1119
            {
1120
                return false;
M
Max Bruckner 已提交
1121
            }
1122 1123 1124
            strcpy((char*)output, "false");
            return true;

M
Max Bruckner 已提交
1125
        case cJSON_True:
1126
            output = ensure(output_buffer, 5, hooks);
1127
            if (output == NULL)
M
Max Bruckner 已提交
1128
            {
1129
                return false;
M
Max Bruckner 已提交
1130
            }
1131 1132 1133
            strcpy((char*)output, "true");
            return true;

M
Max Bruckner 已提交
1134
        case cJSON_Number:
1135
            return print_number(item, output_buffer, hooks);
1136

M
Max Bruckner 已提交
1137
        case cJSON_Raw:
M
Max Bruckner 已提交
1138
        {
M
Max Bruckner 已提交
1139 1140
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1141
            {
M
Max Bruckner 已提交
1142
                if (!output_buffer->noalloc)
1143
                {
1144
                    hooks->deallocate(output_buffer->buffer);
1145
                }
1146
                return false;
M
Max Bruckner 已提交
1147
            }
1148

1149
            raw_length = strlen(item->valuestring) + sizeof("");
1150
            output = ensure(output_buffer, raw_length, hooks);
1151
            if (output == NULL)
M
Max Bruckner 已提交
1152
            {
1153
                return false;
1154
            }
1155 1156
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1157
        }
1158

M
Max Bruckner 已提交
1159
        case cJSON_String:
1160
            return print_string(item, output_buffer, hooks);
1161

M
Max Bruckner 已提交
1162
        case cJSON_Array:
1163
            return print_array(item, depth, format, output_buffer, hooks);
1164

M
Max Bruckner 已提交
1165
        case cJSON_Object:
1166
            return print_object(item, depth, format, output_buffer, hooks);
1167

M
Max Bruckner 已提交
1168
        default:
1169
            return false;
M
Max Bruckner 已提交
1170
    }
K
Kevin Branigan 已提交
1171 1172 1173
}

/* Build an array from input text. */
1174
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 已提交
1175
{
1176
    cJSON *head = NULL; /* head of the linked list */
1177 1178
    cJSON *current_item = NULL;

1179
    if (*input != '[')
M
Max Bruckner 已提交
1180
    {
1181
        /* not an array */
1182
        *error_pointer = input;
1183
        goto fail;
M
Max Bruckner 已提交
1184
    }
K
Kevin Branigan 已提交
1185

M
Max Bruckner 已提交
1186
    input = skip_whitespace(input + 1);
1187
    if (*input == ']')
M
Max Bruckner 已提交
1188
    {
1189
        /* empty array */
1190
        goto success;
M
Max Bruckner 已提交
1191
    }
K
Kevin Branigan 已提交
1192

1193
    /* step back to character in front of the first element */
1194
    input--;
M
Max Bruckner 已提交
1195
    /* loop through the comma separated array elements */
1196
    do
M
Max Bruckner 已提交
1197
    {
1198
        /* allocate next item */
1199
        cJSON *new_item = cJSON_New_Item(hooks);
1200
        if (new_item == NULL)
M
Max Bruckner 已提交
1201
        {
1202
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1203
        }
1204 1205 1206

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1207
        {
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            /* 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 已提交
1220
        input = skip_whitespace(input + 1);
1221
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1222
        input = skip_whitespace(input);
1223
        if (input == NULL)
1224 1225
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1226 1227
        }
    }
1228
    while (*input == ',');
M
Max Bruckner 已提交
1229

1230
    if (*input != ']')
M
Max Bruckner 已提交
1231
    {
1232 1233
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1234 1235
    }

1236 1237
success:
    item->type = cJSON_Array;
1238
    item->child = head;
1239

1240
    return input + 1;
K
Kevin Branigan 已提交
1241

1242
fail:
1243
    if (head != NULL)
1244
    {
1245
        cJSON_Delete(head);
1246 1247
    }

1248
    return NULL;
K
Kevin Branigan 已提交
1249 1250 1251
}

/* Render an array to text */
1252
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 已提交
1253
{
M
Max Bruckner 已提交
1254
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1255
    size_t length = 0;
M
Max Bruckner 已提交
1256
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1257

M
Max Bruckner 已提交
1258
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1259
    {
1260
        return false;
M
Max Bruckner 已提交
1261 1262
    }

M
Max Bruckner 已提交
1263 1264
    /* Compose the output array. */
    /* opening square bracket */
1265
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1266
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1267
    {
1268
        return false;
M
Max Bruckner 已提交
1269 1270
    }

M
Max Bruckner 已提交
1271 1272
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1273

M
Max Bruckner 已提交
1274
    while (current_element != NULL)
M
Max Bruckner 已提交
1275
    {
1276
        if (!print_value(current_element, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1277
        {
1278
            return false;
M
Max Bruckner 已提交
1279
        }
1280
        update_offset(output_buffer);
M
Max Bruckner 已提交
1281
        if (current_element->next)
M
Max Bruckner 已提交
1282
        {
1283
            length = (size_t) (format ? 2 : 1);
1284
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1285
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1286
            {
1287
                return false;
M
Max Bruckner 已提交
1288
            }
M
Max Bruckner 已提交
1289 1290
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1291
            {
M
Max Bruckner 已提交
1292
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1293
            }
M
Max Bruckner 已提交
1294 1295
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1296
        }
M
Max Bruckner 已提交
1297
        current_element = current_element->next;
M
Max Bruckner 已提交
1298 1299
    }

1300
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1301
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1302
    {
1303
        return false;
M
Max Bruckner 已提交
1304
    }
M
Max Bruckner 已提交
1305 1306
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1307

1308
    return true;
K
Kevin Branigan 已提交
1309 1310 1311
}

/* Build an object from the text. */
1312
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 已提交
1313
{
1314
    cJSON *head = NULL; /* linked list head */
1315 1316
    cJSON *current_item = NULL;

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

M
Max Bruckner 已提交
1323
    input = skip_whitespace(input + 1);
1324
    if (*input == '}')
M
Max Bruckner 已提交
1325
    {
1326
        goto success; /* empty object */
M
Max Bruckner 已提交
1327 1328
    }

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

1341 1342
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1343
        {
1344 1345 1346 1347 1348 1349 1350 1351 1352
            /* 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 已提交
1353 1354
        }

1355
        /* parse the name of the child */
M
Max Bruckner 已提交
1356
        input = skip_whitespace(input + 1);
1357
        input = parse_string(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1358
        input = skip_whitespace(input);
1359
        if (input == NULL)
M
Max Bruckner 已提交
1360
        {
1361
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1362 1363
        }

1364 1365 1366
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1367

1368
        if (*input != ':')
M
Max Bruckner 已提交
1369
        {
1370 1371
            *error_pointer = input;
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1372
        }
1373 1374

        /* parse the value */
M
Max Bruckner 已提交
1375
        input = skip_whitespace(input + 1);
1376
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1377
        input = skip_whitespace(input);
1378
        if (input == NULL)
M
Max Bruckner 已提交
1379
        {
1380
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1381 1382
        }
    }
1383
    while (*input == ',');
1384

1385
    if (*input != '}')
M
Max Bruckner 已提交
1386
    {
1387 1388
        *error_pointer = input;
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1389 1390
    }

1391 1392
success:
    item->type = cJSON_Object;
1393
    item->child = head;
1394

1395
    return input + 1;
1396 1397

fail:
1398
    if (head != NULL)
1399
    {
1400
        cJSON_Delete(head);
1401 1402
    }

1403
    return NULL;
K
Kevin Branigan 已提交
1404 1405 1406
}

/* Render an object to text. */
1407
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)
1408
{
M
Max Bruckner 已提交
1409
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1410
    size_t length = 0;
M
Max Bruckner 已提交
1411
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1412

M
Max Bruckner 已提交
1413
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1414
    {
1415
        return false;
M
Max Bruckner 已提交
1416 1417
    }

M
Max Bruckner 已提交
1418
    /* Compose the output: */
1419
    length = (size_t) (format ? 2 : 1); /* fmt: {\n */
1420
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1421
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1422
    {
1423
        return false;
M
Max Bruckner 已提交
1424 1425
    }

M
Max Bruckner 已提交
1426 1427
    *output_pointer++ = '{';
    if (format)
M
Max Bruckner 已提交
1428
    {
M
Max Bruckner 已提交
1429
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1430
    }
M
Max Bruckner 已提交
1431
    output_buffer->offset += length;
M
Max Bruckner 已提交
1432

M
Max Bruckner 已提交
1433
    while (current_item)
M
Max Bruckner 已提交
1434
    {
M
Max Bruckner 已提交
1435
        if (format)
M
Max Bruckner 已提交
1436
        {
M
Max Bruckner 已提交
1437
            size_t i;
1438
            output_pointer = ensure(output_buffer, depth + 1, hooks);
M
Max Bruckner 已提交
1439
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1440
            {
1441
                return false;
M
Max Bruckner 已提交
1442
            }
M
Max Bruckner 已提交
1443
            for (i = 0; i < depth + 1; i++)
M
Max Bruckner 已提交
1444
            {
M
Max Bruckner 已提交
1445
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1446
            }
M
Max Bruckner 已提交
1447
            output_buffer->offset += depth + 1;
M
Max Bruckner 已提交
1448 1449
        }

M
Max Bruckner 已提交
1450
        /* print key */
1451
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks))
M
Max Bruckner 已提交
1452
        {
1453
            return false;
M
Max Bruckner 已提交
1454
        }
M
Max Bruckner 已提交
1455
        update_offset(output_buffer);
M
Max Bruckner 已提交
1456

1457
        length = (size_t) (format ? 2 : 1);
1458
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1459
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1460
        {
1461
            return false;
M
Max Bruckner 已提交
1462
        }
M
Max Bruckner 已提交
1463 1464
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1465
        {
M
Max Bruckner 已提交
1466
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1467
        }
M
Max Bruckner 已提交
1468
        output_buffer->offset += length;
M
Max Bruckner 已提交
1469

M
Max Bruckner 已提交
1470
        /* print value */
1471
        if (!print_value(current_item, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1472
        {
1473
            return false;
M
Max Bruckner 已提交
1474
        }
M
Max Bruckner 已提交
1475
        update_offset(output_buffer);
M
Max Bruckner 已提交
1476

M
Max Bruckner 已提交
1477
        /* print comma if not last */
1478
        length = (size_t) ((format ? 1 : 0) + (current_item->next ? 1 : 0));
1479
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1480
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1481
        {
1482
            return false;
M
Max Bruckner 已提交
1483
        }
M
Max Bruckner 已提交
1484
        if (current_item->next)
M
Max Bruckner 已提交
1485
        {
M
Max Bruckner 已提交
1486
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1487 1488
        }

M
Max Bruckner 已提交
1489
        if (format)
M
Max Bruckner 已提交
1490
        {
M
Max Bruckner 已提交
1491
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1492
        }
M
Max Bruckner 已提交
1493 1494
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1495

M
Max Bruckner 已提交
1496
        current_item = current_item->next;
M
Max Bruckner 已提交
1497
    }
M
Max Bruckner 已提交
1498

1499
    output_pointer = ensure(output_buffer, format ? (depth + 2) : 2, hooks);
M
Max Bruckner 已提交
1500
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1501
    {
1502
        return false;
M
Max Bruckner 已提交
1503
    }
M
Max Bruckner 已提交
1504
    if (format)
M
Max Bruckner 已提交
1505
    {
M
Max Bruckner 已提交
1506 1507
        size_t i;
        for (i = 0; i < (depth); i++)
M
Max Bruckner 已提交
1508
        {
M
Max Bruckner 已提交
1509
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1510 1511
        }
    }
M
Max Bruckner 已提交
1512 1513
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1514

1515
    return true;
K
Kevin Branigan 已提交
1516 1517 1518
}

/* Get Array size/item / object item. */
1519
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1520 1521
{
    cJSON *c = array->child;
1522
    size_t i = 0;
M
Max Bruckner 已提交
1523 1524 1525 1526 1527
    while(c)
    {
        i++;
        c = c->next;
    }
1528 1529 1530

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

M
Max Bruckner 已提交
1531
    return (int)i;
M
Max Bruckner 已提交
1532 1533
}

1534
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1535
{
1536
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1546
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1547
{
1548
    cJSON *c = object ? object->child : NULL;
1549
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1550 1551 1552 1553 1554 1555
    {
        c = c->next;
    }
    return c;
}

1556
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
{
    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;
}

1574
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1575 1576 1577
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1578 1579

/* Utility for array list handling. */
M
Max Bruckner 已提交
1580 1581 1582 1583 1584 1585
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1586
/* Utility for handling references. */
1587
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1588
{
1589
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1590 1591
    if (!ref)
    {
1592
        return NULL;
M
Max Bruckner 已提交
1593 1594
    }
    memcpy(ref, item, sizeof(cJSON));
1595
    ref->string = NULL;
M
Max Bruckner 已提交
1596
    ref->type |= cJSON_IsReference;
1597
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1598 1599
    return ref;
}
K
Kevin Branigan 已提交
1600 1601

/* Add item to array/object. */
1602
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1603
{
1604 1605 1606
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1607 1608 1609
    {
        return;
    }
1610 1611 1612 1613

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1614 1615 1616 1617 1618 1619 1620
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1621
        while (child->next)
M
Max Bruckner 已提交
1622
        {
1623
            child = child->next;
M
Max Bruckner 已提交
1624
        }
1625
        suffix_object(child, item);
M
Max Bruckner 已提交
1626 1627 1628
    }
}

1629
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1630
{
1631
    /* call cJSON_AddItemToObjectCS for code reuse */
1632
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1633 1634
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1635 1636
}

1637 1638 1639 1640
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wcast-qual"
1641
/* Add an item to an object with constant string as key */
1642
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1643 1644 1645 1646 1647 1648 1649
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1650
        global_hooks.deallocate(item->string);
1651 1652 1653 1654 1655
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}
1656 1657 1658
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1659

1660
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1661
{
1662
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1663 1664
}

1665
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1666
{
1667
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1668 1669
}

M
Max Bruckner 已提交
1670
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1681
        return NULL;
1682
    }
1683
    if (c->prev)
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
    {
        /* 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 */
1697
    c->prev = c->next = NULL;
1698 1699 1700

    return c;
}
1701
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1702 1703 1704 1705 1706 1707 1708 1709
{
    if (which < 0)
    {
        return NULL;
    }

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

1711
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1712 1713 1714 1715
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1716
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1717
{
1718
    size_t i = 0;
1719
    cJSON *c = object->child;
1720
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1721 1722 1723 1724 1725 1726
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1727
        return DetachItemFromArray(object, i);
1728 1729
    }

1730
    return NULL;
1731 1732
}

1733
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1734 1735 1736
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1737 1738

/* Replace array/object items with new ones. */
1739
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
{
    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 已提交
1765
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
{
    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;
    }
1791
    c->next = c->prev = NULL;
1792 1793
    cJSON_Delete(c);
}
1794
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
1795 1796 1797 1798 1799 1800 1801 1802
{
    if (which < 0)
    {
        return;
    }

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

1804
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1805
{
1806
    size_t i = 0;
1807
    cJSON *c = object->child;
1808
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1809 1810 1811 1812 1813 1814
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1815 1816 1817
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1818
             global_hooks.deallocate(newitem->string);
1819 1820
        }

1821
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1822
        ReplaceItemInArray(object, i, newitem);
1823 1824
    }
}
K
Kevin Branigan 已提交
1825 1826

/* Create basic types: */
1827
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
1828
{
1829
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1830 1831 1832 1833 1834 1835 1836 1837
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

1838
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
1839
{
1840
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1841 1842 1843 1844 1845 1846 1847 1848
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

1849
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
1850
{
1851
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1852 1853 1854 1855 1856 1857 1858 1859
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

1860
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
1861
{
1862
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1863 1864 1865 1866 1867 1868 1869 1870
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

1871
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
1872
{
1873
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1874 1875 1876 1877
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891

        /* 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 已提交
1892 1893 1894 1895 1896
    }

    return item;
}

1897
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
1898
{
1899
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1900 1901 1902
    if(item)
    {
        item->type = cJSON_String;
1903
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1904 1905 1906
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1907
            return NULL;
M
Max Bruckner 已提交
1908 1909 1910 1911 1912 1913
        }
    }

    return item;
}

1914
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
1915
{
1916
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1917 1918 1919
    if(item)
    {
        item->type = cJSON_Raw;
1920
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
1921 1922 1923 1924 1925 1926 1927 1928
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
1929 1930
}

1931
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
1932
{
1933
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1934 1935 1936 1937 1938 1939 1940 1941
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

1942
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
1943
{
1944
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1945 1946 1947 1948 1949 1950 1951
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
1952 1953

/* Create Arrays: */
1954
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
1955
{
1956
    size_t i = 0;
1957 1958
    cJSON *n = NULL;
    cJSON *p = NULL;
1959 1960 1961 1962 1963 1964 1965 1966 1967
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1968 1969 1970 1971 1972
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
1973
            return NULL;
M
Max Bruckner 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1989
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
1990
{
1991
    size_t i = 0;
1992 1993
    cJSON *n = NULL;
    cJSON *p = NULL;
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2004
    {
2005
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
2006 2007 2008
        if(!n)
        {
            cJSON_Delete(a);
2009
            return NULL;
M
Max Bruckner 已提交
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2025
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
2026
{
2027
    size_t i = 0;
2028 2029
    cJSON *n = NULL;
    cJSON *p = NULL;
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2040 2041 2042 2043 2044
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2045
            return NULL;
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2061
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2062
{
2063
    size_t i = 0;
2064 2065
    cJSON *n = NULL;
    cJSON *p = NULL;
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2076 2077 2078 2079 2080
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2081
            return NULL;
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2096 2097

/* Duplication */
2098
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2099
{
M
Max Bruckner 已提交
2100
    cJSON *newitem = NULL;
2101 2102
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2103
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2104 2105 2106 2107

    /* Bail on bad ptr */
    if (!item)
    {
2108
        goto fail;
M
Max Bruckner 已提交
2109 2110
    }
    /* Create new item */
2111
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2112 2113
    if (!newitem)
    {
2114
        goto fail;
M
Max Bruckner 已提交
2115 2116 2117 2118 2119 2120 2121
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2122
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2123 2124
        if (!newitem->valuestring)
        {
2125
            goto fail;
M
Max Bruckner 已提交
2126 2127 2128 2129
        }
    }
    if (item->string)
    {
2130
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2131 2132
        if (!newitem->string)
        {
2133
            goto fail;
M
Max Bruckner 已提交
2134 2135 2136 2137 2138 2139 2140 2141
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2142 2143
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2144
    {
2145
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2146 2147
        if (!newchild)
        {
2148
            goto fail;
M
Max Bruckner 已提交
2149
        }
2150
        if (next != NULL)
M
Max Bruckner 已提交
2151 2152
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2153 2154 2155
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2156 2157 2158 2159
        }
        else
        {
            /* Set newitem->child and move to it */
2160 2161
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2162
        }
2163
        child = child->next;
M
Max Bruckner 已提交
2164 2165 2166
    }

    return newitem;
2167 2168 2169 2170 2171 2172 2173 2174

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

    return NULL;
2175
}
2176

2177
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2178
{
2179
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
    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 已提交
2219
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2220 2221 2222 2223
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2224
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2225
                }
M
Max Bruckner 已提交
2226
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2227
            }
M
Max Bruckner 已提交
2228
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2229 2230 2231 2232
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2233
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2234 2235 2236 2237 2238
        }
    }

    /* and null-terminate. */
    *into = '\0';
2239
}
2240

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

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

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

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

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

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


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

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2281
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2282 2283 2284 2285 2286 2287 2288 2289 2290
{
    if (item == NULL)
    {
        return false;
    }

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

2291
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2292 2293 2294 2295 2296 2297 2298 2299 2300
{
    if (item == NULL)
    {
        return false;
    }

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

2301
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2302 2303 2304 2305 2306 2307 2308 2309 2310
{
    if (item == NULL)
    {
        return false;
    }

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

2311
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2312 2313 2314 2315 2316 2317 2318 2319 2320
{
    if (item == NULL)
    {
        return false;
    }

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

2321
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2322 2323 2324 2325 2326 2327 2328 2329 2330
{
    if (item == NULL)
    {
        return false;
    }

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

2331
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2332 2333 2334 2335 2336 2337 2338 2339
{
    if (item == NULL)
    {
        return false;
    }

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