cJSON.c 56.2 KB
Newer Older
K
Kevin Branigan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
  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. */

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"

M
Max Bruckner 已提交
35
/* define our own boolean type */
M
Max Bruckner 已提交
36 37 38
typedef int cjbool;
#define true ((cjbool)1)
#define false ((cjbool)0)
M
Max Bruckner 已提交
39

40
static const unsigned char *global_ep = NULL;
K
Kevin Branigan 已提交
41

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

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

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

    return version;
}

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

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

static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
M
Max Bruckner 已提交
84
static void *(*cJSON_realloc)(void *pointer, size_t size) = realloc;
K
Kevin Branigan 已提交
85

86
static unsigned char* cJSON_strdup(const unsigned char* str)
K
Kevin Branigan 已提交
87
{
M
Max Bruckner 已提交
88
    size_t len = 0;
89
    unsigned char *copy = NULL;
K
Kevin Branigan 已提交
90

91 92 93 94 95
    if (str == NULL)
    {
        return NULL;
    }

96 97
    len = strlen((const char*)str) + 1;
    if (!(copy = (unsigned char*)cJSON_malloc(len)))
M
Max Bruckner 已提交
98
    {
99
        return NULL;
M
Max Bruckner 已提交
100 101 102 103
    }
    memcpy(copy, str, len);

    return copy;
K
Kevin Branigan 已提交
104 105 106 107
}

void cJSON_InitHooks(cJSON_Hooks* hooks)
{
M
Max Bruckner 已提交
108
    if (hooks == NULL)
M
Max Bruckner 已提交
109 110
    {
        /* Reset hooks */
K
Kevin Branigan 已提交
111 112
        cJSON_malloc = malloc;
        cJSON_free = free;
M
Max Bruckner 已提交
113
        cJSON_realloc = realloc;
K
Kevin Branigan 已提交
114 115 116
        return;
    }

M
Max Bruckner 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    cJSON_malloc = malloc;
    if (hooks->malloc_fn != NULL)
    {
        cJSON_malloc = hooks->malloc_fn;
    }

    cJSON_free = free;
    if (hooks->free_fn != NULL)
    {
        cJSON_free = hooks->free_fn;
    }

    /* use realloc only if both free and malloc are used */
    cJSON_realloc = NULL;
    if ((cJSON_malloc == malloc) && (cJSON_free == free))
    {
        cJSON_realloc = realloc;
    }
K
Kevin Branigan 已提交
135 136 137
}

/* Internal constructor. */
D
Dave Gamble 已提交
138
static cJSON *cJSON_New_Item(void)
K
Kevin Branigan 已提交
139
{
M
Max Bruckner 已提交
140 141 142
    cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
    if (node)
    {
143
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
144 145 146
    }

    return node;
K
Kevin Branigan 已提交
147 148 149 150 151
}

/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
M
Max Bruckner 已提交
152
    cJSON *next = NULL;
M
Max Bruckner 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    while (c)
    {
        next = c->next;
        if (!(c->type & cJSON_IsReference) && c->child)
        {
            cJSON_Delete(c->child);
        }
        if (!(c->type & cJSON_IsReference) && c->valuestring)
        {
            cJSON_free(c->valuestring);
        }
        if (!(c->type & cJSON_StringIsConst) && c->string)
        {
            cJSON_free(c->string);
        }
        cJSON_free(c);
        c = next;
    }
K
Kevin Branigan 已提交
171 172 173
}

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

179
    if (input == NULL)
180 181 182 183
    {
        return NULL;
    }

184 185
    number = strtod((const char*)input, (char**)&after_end);
    if (input == after_end)
M
Max Bruckner 已提交
186
    {
187
        return NULL; /* parse_error */
M
Max Bruckner 已提交
188 189
    }

190
    item->valuedouble = number;
M
Max Bruckner 已提交
191

192
    /* use saturation in case of overflow */
193
    if (number >= INT_MAX)
194 195 196
    {
        item->valueint = INT_MAX;
    }
197
    else if (number <= INT_MIN)
198 199 200 201 202
    {
        item->valueint = INT_MIN;
    }
    else
    {
203
        item->valueint = (int)number;
204
    }
205

M
Max Bruckner 已提交
206 207
    item->type = cJSON_Number;

208
    return after_end;
K
Kevin Branigan 已提交
209 210
}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
double cJSON_SetNumberHelper(cJSON *object, double number)
{
    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 已提交
230 231
typedef struct
{
232
    unsigned char *buffer;
233 234
    size_t length;
    size_t offset;
235
    cjbool noalloc;
M
Max Bruckner 已提交
236
} printbuffer;
237

M
Max Bruckner 已提交
238
/* realloc printbuffer if necessary to have at least "needed" bytes more */
239
static unsigned char* ensure(printbuffer *p, size_t needed)
240
{
241
    unsigned char *newbuffer = NULL;
242 243
    size_t newsize = 0;

244 245 246 247 248
    if (p == NULL)
    {
        return (unsigned char*)cJSON_malloc(needed);
    }

249 250 251 252 253 254
    if (needed > INT_MAX)
    {
        /* sizes bigger than INT_MAX are currently not supported */
        return NULL;
    }

255
    if (p->buffer == NULL)
M
Max Bruckner 已提交
256
    {
257
        return NULL;
M
Max Bruckner 已提交
258 259 260 261 262 263 264
    }
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

265 266 267 268
    if (p->noalloc) {
        return NULL;
    }

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    /* 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;
        }
    }

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

            return NULL;
        }
        if (newbuffer)
        {
303
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
304 305
        }
        cJSON_free(p->buffer);
M
Max Bruckner 已提交
306 307 308 309 310
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
311 312
}

M
Max Bruckner 已提交
313
/* calculate the new length of the string in a printbuffer */
314
static size_t update(const printbuffer *p)
K
Kevin Branigan 已提交
315
{
M
Max Bruckner 已提交
316
    const unsigned char *str = NULL;
M
Max Bruckner 已提交
317 318 319 320 321 322
    if (!p || !p->buffer)
    {
        return 0;
    }
    str = p->buffer + p->offset;

M
Max Bruckner 已提交
323
    return p->offset + strlen((const char*)str);
324 325 326
}

/* Render the number nicely from the given item into a string. */
327
static unsigned char *print_number(const cJSON *item, printbuffer *p)
328
{
329
    unsigned char *str = NULL;
M
Max Bruckner 已提交
330 331 332 333
    double d = item->valuedouble;
    /* special case for 0. */
    if (d == 0)
    {
334 335
        str = ensure(p, 2);
        if (str != NULL)
M
Max Bruckner 已提交
336
        {
337
            strcpy((char*)str,"0");
M
Max Bruckner 已提交
338 339 340 341 342 343
        }
    }
    /* value is an int */
    else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
    {
            /* 2^64+1 can be represented in 21 chars. */
344 345
        str = ensure(p, 21);
        if (str != NULL)
M
Max Bruckner 已提交
346
        {
347
            sprintf((char*)str, "%d", item->valueint);
M
Max Bruckner 已提交
348 349 350 351 352
        }
    }
    /* value is a floating point number */
    else
    {
353 354 355
        /* This is a nice tradeoff. */
        str = ensure(p, 64);
        if (str != NULL)
M
Max Bruckner 已提交
356 357 358 359
        {
            /* This checks for NaN and Infinity */
            if ((d * 0) != 0)
            {
360
                sprintf((char*)str, "null");
M
Max Bruckner 已提交
361
            }
362
            else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
M
Max Bruckner 已提交
363
            {
364
                sprintf((char*)str, "%.0f", d);
M
Max Bruckner 已提交
365 366 367
            }
            else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
            {
368
                sprintf((char*)str, "%e", d);
M
Max Bruckner 已提交
369 370 371
            }
            else
            {
372
                sprintf((char*)str, "%f", d);
M
Max Bruckner 已提交
373 374 375 376
            }
        }
    }
    return str;
K
Kevin Branigan 已提交
377 378
}

M
Max Bruckner 已提交
379
/* parse 4 digit hexadecimal number */
380
static unsigned parse_hex4(const unsigned char * const input)
381
{
M
Max Bruckner 已提交
382
    unsigned int h = 0;
383
    size_t i = 0;
M
Max Bruckner 已提交
384

385
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
386
    {
387
        /* parse digit */
388
        if ((input[i] >= '0') && (input[i] <= '9'))
389
        {
390
            h += (unsigned int) input[i] - '0';
391
        }
392
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
393
        {
394
            h += (unsigned int) 10 + input[i] - 'A';
395
        }
396
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
397
        {
398
            h += (unsigned int) 10 + input[i] - 'a';
399 400 401 402 403
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
404

405 406 407 408 409
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
410 411 412
    }

    return h;
413 414
}

415 416
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
417
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 已提交
418
{
419 420 421 422 423 424 425 426 427 428 429 430 431
    /* 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;
432 433
    unsigned char utf8_length = 0;
    unsigned char sequence_length = 0;
434 435 436 437 438 439 440 441 442

    /* 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 已提交
443

444 445
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
446
    {
447
        *error_pointer = first_sequence;
448
        goto fail;
M
Max Bruckner 已提交
449
    }
M
Max Bruckner 已提交
450

451 452
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
453
    {
454 455 456 457 458
        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 已提交
459
        {
460 461 462
            /* input ends unexpectedly */
            *error_pointer = first_sequence;
            goto fail;
M
Max Bruckner 已提交
463
        }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

        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 已提交
490
    }
M
Max Bruckner 已提交
491

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    /* 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 已提交
516
    {
517 518
        /* invalid unicode codepoint */
        *error_pointer = first_sequence;
519
        goto fail;
M
Max Bruckner 已提交
520 521
    }

522 523 524 525 526 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 552 553
    /* 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. */
554
static const unsigned char *parse_string(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer)
555 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 590 591 592 593 594 595 596 597 598 599 600 601
{
    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;
        output = (unsigned char*)cJSON_malloc(allocation_length + sizeof('\0'));
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
602
    /* loop through the string literal */
603
    while (input_pointer < input_end)
M
Max Bruckner 已提交
604
    {
605
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
606
        {
607
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
608 609 610 611
        }
        /* escape sequence */
        else
        {
612
            unsigned char sequence_length = 2;
613
            switch (input_pointer[1])
M
Max Bruckner 已提交
614 615
            {
                case 'b':
616
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
617 618
                    break;
                case 'f':
619
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
620 621
                    break;
                case 'n':
622
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
623 624
                    break;
                case 'r':
625
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
626 627
                    break;
                case 't':
628
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
629
                    break;
630 631 632
                case '\"':
                case '\\':
                case '/':
633
                    *output_pointer++ = input_pointer[1];
634
                    break;
635 636

                /* UTF-16 literal */
M
Max Bruckner 已提交
637
                case 'u':
638 639
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer, error_pointer);
                    if (sequence_length == 0)
M
Max Bruckner 已提交
640
                    {
641
                        /* failed to convert UTF16-literal to UTF-8 */
642
                        goto fail;
M
Max Bruckner 已提交
643 644
                    }
                    break;
645

M
Max Bruckner 已提交
646
                default:
647
                    *error_pointer = input_pointer;
648
                    goto fail;
M
Max Bruckner 已提交
649
            }
650
            input_pointer += sequence_length;
M
Max Bruckner 已提交
651 652
        }
    }
653 654 655

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

657
    item->type = cJSON_String;
658
    item->valuestring = (char*)output;
659

660
    return input_end + 1;
661 662

fail:
663
    if (output != NULL)
664
    {
665
        cJSON_free(output);
666 667 668
    }

    return NULL;
K
Kevin Branigan 已提交
669 670 671
}

/* Render the cstring provided to an escaped version that can be printed. */
672
static unsigned char *print_string_ptr(const unsigned char *str, printbuffer *p)
K
Kevin Branigan 已提交
673
{
674 675 676
    const unsigned char *ptr = NULL;
    unsigned char *ptr2 = NULL;
    unsigned char *out = NULL;
677
    size_t len = 0;
M
Max Bruckner 已提交
678
    cjbool flag = false;
M
Max Bruckner 已提交
679
    unsigned char token = '\0';
M
Max Bruckner 已提交
680 681 682 683

    /* empty string */
    if (!str)
    {
684 685
        out = ensure(p, 3);
        if (out == NULL)
M
Max Bruckner 已提交
686
        {
687
            return NULL;
M
Max Bruckner 已提交
688
        }
689
        strcpy((char*)out, "\"\"");
M
Max Bruckner 已提交
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

        return out;
    }

    /* set "flag" to 1 if something needs to be escaped */
    for (ptr = str; *ptr; ptr++)
    {
        flag |= (((*ptr > 0) && (*ptr < 32)) /* unprintable characters */
                || (*ptr == '\"') /* double quote */
                || (*ptr == '\\')) /* backslash */
            ? 1
            : 0;
    }
    /* no characters have to be escaped */
    if (!flag)
    {
M
Max Bruckner 已提交
706
        len = (size_t)(ptr - str);
707 708 709

        out = ensure(p, len + 3);
        if (out == NULL)
M
Max Bruckner 已提交
710
        {
711
            return NULL;
M
Max Bruckner 已提交
712 713 714 715
        }

        ptr2 = out;
        *ptr2++ = '\"';
716
        strcpy((char*)ptr2, (const char*)str);
M
Max Bruckner 已提交
717 718 719 720 721 722 723 724
        ptr2[len] = '\"';
        ptr2[len + 1] = '\0';

        return out;
    }

    ptr = str;
    /* calculate additional space that is needed for escaping */
S
Stephan 已提交
725
    while ((token = *ptr))
M
Max Bruckner 已提交
726
    {
S
Stephan 已提交
727
        ++len;
M
Max Bruckner 已提交
728 729 730 731 732 733 734 735 736 737 738
        if (strchr("\"\\\b\f\n\r\t", token))
        {
            len++; /* +1 for the backslash */
        }
        else if (token < 32)
        {
            len += 5; /* +5 for \uXXXX */
        }
        ptr++;
    }

739 740
    out = ensure(p, len + 3);
    if (out == NULL)
M
Max Bruckner 已提交
741
    {
742
        return NULL;
M
Max Bruckner 已提交
743 744 745 746 747 748 749 750
    }

    ptr2 = out;
    ptr = str;
    *ptr2++ = '\"';
    /* copy the string */
    while (*ptr)
    {
751
        if ((*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
M
Max Bruckner 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        {
            /* normal character, copy */
            *ptr2++ = *ptr++;
        }
        else
        {
            /* character needs to be escaped */
            *ptr2++ = '\\';
            switch (token = *ptr++)
            {
                case '\\':
                    *ptr2++ = '\\';
                    break;
                case '\"':
                    *ptr2++ = '\"';
                    break;
                case '\b':
                    *ptr2++ = 'b';
                    break;
                case '\f':
                    *ptr2++ = 'f';
                    break;
                case '\n':
                    *ptr2++ = 'n';
                    break;
                case '\r':
                    *ptr2++ = 'r';
                    break;
                case '\t':
                    *ptr2++ = 't';
                    break;
                default:
                    /* escape and print as unicode codepoint */
785
                    sprintf((char*)ptr2, "u%04x", token);
M
Max Bruckner 已提交
786 787 788 789 790 791 792 793 794
                    ptr2 += 5;
                    break;
            }
        }
    }
    *ptr2++ = '\"';
    *ptr2++ = '\0';

    return out;
K
Kevin Branigan 已提交
795
}
M
Max Bruckner 已提交
796

M
Max Bruckner 已提交
797
/* Invoke print_string_ptr (which is useful) on an item. */
798
static unsigned char *print_string(const cJSON *item, printbuffer *p)
M
Max Bruckner 已提交
799
{
800
    return print_string_ptr((unsigned char*)item->valuestring, p);
M
Max Bruckner 已提交
801
}
K
Kevin Branigan 已提交
802 803

/* Predeclare these prototypes. */
804
static const unsigned char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const ep);
805
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
806
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const ep);
807
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
808
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const ep);
809
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
K
Kevin Branigan 已提交
810 811

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
812
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
813
{
814
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
815 816 817 818 819 820
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
821 822

/* Parse an object - create a new root, and populate. */
M
Max Bruckner 已提交
823
cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cjbool require_null_terminated)
K
Kevin Branigan 已提交
824
{
825
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
826
    /* use global error pointer if no specific one was given */
827
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
M
Max Bruckner 已提交
828
    cJSON *c = cJSON_New_Item();
829
    *ep = NULL;
M
Max Bruckner 已提交
830 831
    if (!c) /* memory fail */
    {
832
        return NULL;
M
Max Bruckner 已提交
833 834
    }

M
Max Bruckner 已提交
835
    end = parse_value(c, skip_whitespace((const unsigned char*)value), ep);
M
Max Bruckner 已提交
836 837 838 839
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
840
        return NULL;
M
Max Bruckner 已提交
841 842 843 844 845
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
846
        end = skip_whitespace(end);
M
Max Bruckner 已提交
847 848 849 850
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
851
            return NULL;
M
Max Bruckner 已提交
852 853 854 855
        }
    }
    if (return_parse_end)
    {
856
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
857 858 859
    }

    return c;
K
Kevin Branigan 已提交
860
}
M
Max Bruckner 已提交
861

862
/* Default options for cJSON_Parse */
M
Max Bruckner 已提交
863 864 865 866
cJSON *cJSON_Parse(const char *value)
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
867

M
Max Bruckner 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
#define min(a, b) ((a < b) ? a : b)

static unsigned char *print(const cJSON * const item, cjbool format)
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
    buffer->buffer = (unsigned char*) cJSON_malloc(256);
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
    if (print_value(item, 0, format, buffer) == NULL)
    {
        goto fail;
    }
    buffer->offset = update(buffer); /* update the length of the string */

    /* copy the buffer over to a new one */
    printed = (unsigned char*) cJSON_malloc(buffer->offset + 1);
    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 */
    cJSON_free(buffer->buffer);

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
        cJSON_free(buffer->buffer);
    }

    if (printed != NULL)
    {
        cJSON_free(printed);
    }

    return NULL;
}

K
Kevin Branigan 已提交
919
/* Render a cJSON item/entity/structure to text. */
920
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
921
{
M
Max Bruckner 已提交
922
    return (char*)print(item, true);
M
Max Bruckner 已提交
923 924
}

925
char *cJSON_PrintUnformatted(const cJSON *item)
926
{
M
Max Bruckner 已提交
927
    return (char*)print(item, false);
928
}
929

M
Max Bruckner 已提交
930
char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, cjbool fmt)
931
{
M
Max Bruckner 已提交
932
    printbuffer p;
M
Max Bruckner 已提交
933 934 935

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
936
        return NULL;
M
Max Bruckner 已提交
937 938 939
    }

    p.buffer = (unsigned char*)cJSON_malloc((size_t)prebuffer);
940 941
    if (!p.buffer)
    {
942
        return NULL;
943
    }
M
Max Bruckner 已提交
944 945

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
946
    p.offset = 0;
947
    p.noalloc = false;
M
Max Bruckner 已提交
948

949
    return (char*)print_value(item, 0, fmt, &p);
950 951
}

952
int cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cjbool fmt)
953 954
{
    printbuffer p;
M
Max Bruckner 已提交
955 956 957 958 959 960

    if (len < 0)
    {
        return false;
    }

961
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
962
    p.length = (size_t)len;
963
    p.offset = 0;
964
    p.noalloc = true;
M
Max Bruckner 已提交
965
    return print_value(item, 0, fmt, &p) != NULL;
966
}
K
Kevin Branigan 已提交
967 968

/* Parser core - when encountering text, process appropriately. */
969
static const unsigned  char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer)
K
Kevin Branigan 已提交
970
{
971
    if (input == NULL)
M
Max Bruckner 已提交
972
    {
973
        return NULL; /* no input */
M
Max Bruckner 已提交
974 975 976
    }

    /* parse the different types of values */
977 978
    /* null */
    if (!strncmp((const char*)input, "null", 4))
M
Max Bruckner 已提交
979 980
    {
        item->type = cJSON_NULL;
981
        return input + 4;
M
Max Bruckner 已提交
982
    }
983 984
    /* false */
    if (!strncmp((const char*)input, "false", 5))
M
Max Bruckner 已提交
985 986
    {
        item->type = cJSON_False;
987
        return input + 5;
M
Max Bruckner 已提交
988
    }
989 990
    /* true */
    if (!strncmp((const char*)input, "true", 4))
M
Max Bruckner 已提交
991 992 993
    {
        item->type = cJSON_True;
        item->valueint = 1;
994
        return input + 4;
M
Max Bruckner 已提交
995
    }
996 997
    /* string */
    if (*input == '\"')
M
Max Bruckner 已提交
998
    {
999
        return parse_string(item, input, error_pointer);
M
Max Bruckner 已提交
1000
    }
1001 1002
    /* number */
    if ((*input == '-') || ((*input >= '0') && (*input <= '9')))
M
Max Bruckner 已提交
1003
    {
1004
        return parse_number(item, input);
M
Max Bruckner 已提交
1005
    }
1006 1007
    /* array */
    if (*input == '[')
M
Max Bruckner 已提交
1008
    {
1009
        return parse_array(item, input, error_pointer);
M
Max Bruckner 已提交
1010
    }
1011 1012
    /* object */
    if (*input == '{')
M
Max Bruckner 已提交
1013
    {
1014
        return parse_object(item, input, error_pointer);
M
Max Bruckner 已提交
1015 1016
    }

M
Max Bruckner 已提交
1017
    /* failure. */
1018
    *error_pointer = input;
1019
    return NULL;
K
Kevin Branigan 已提交
1020 1021 1022
}

/* Render a value to text. */
1023
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1024
{
1025
    unsigned char *out = NULL;
M
Max Bruckner 已提交
1026 1027 1028

    if (!item)
    {
1029
        return NULL;
M
Max Bruckner 已提交
1030 1031 1032
    }
    if (p)
    {
1033
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1034 1035 1036
        {
            case cJSON_NULL:
                out = ensure(p, 5);
1037
                if (out != NULL)
M
Max Bruckner 已提交
1038
                {
1039
                    strcpy((char*)out, "null");
M
Max Bruckner 已提交
1040 1041 1042 1043
                }
                break;
            case cJSON_False:
                out = ensure(p, 6);
1044
                if (out != NULL)
M
Max Bruckner 已提交
1045
                {
1046
                    strcpy((char*)out, "false");
M
Max Bruckner 已提交
1047 1048 1049 1050
                }
                break;
            case cJSON_True:
                out = ensure(p, 5);
1051
                if (out != NULL)
M
Max Bruckner 已提交
1052
                {
1053
                    strcpy((char*)out, "true");
M
Max Bruckner 已提交
1054 1055 1056 1057 1058
                }
                break;
            case cJSON_Number:
                out = print_number(item, p);
                break;
J
Jiri Zouhar 已提交
1059
            case cJSON_Raw:
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
            {
                size_t raw_length = 0;
                if (item->valuestring == NULL)
                {
                    if (!p->noalloc)
                    {
                        cJSON_free(p->buffer);
                    }
                    out = NULL;
                    break;
                }

                raw_length = strlen(item->valuestring) + sizeof('\0');
                out = ensure(p, raw_length);
1074
                if (out != NULL)
J
Jiri Zouhar 已提交
1075
                {
1076
                    memcpy(out, item->valuestring, raw_length);
J
Jiri Zouhar 已提交
1077 1078
                }
                break;
1079
            }
M
Max Bruckner 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088
            case cJSON_String:
                out = print_string(item, p);
                break;
            case cJSON_Array:
                out = print_array(item, depth, fmt, p);
                break;
            case cJSON_Object:
                out = print_object(item, depth, fmt, p);
                break;
1089 1090 1091
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
1092 1093 1094 1095
        }
    }
    else
    {
1096
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1097 1098
        {
            case cJSON_NULL:
1099
                out = cJSON_strdup((const unsigned char*)"null");
M
Max Bruckner 已提交
1100 1101
                break;
            case cJSON_False:
1102
                out = cJSON_strdup((const unsigned char*)"false");
M
Max Bruckner 已提交
1103 1104
                break;
            case cJSON_True:
1105
                out = cJSON_strdup((const unsigned char*)"true");
M
Max Bruckner 已提交
1106 1107 1108 1109
                break;
            case cJSON_Number:
                out = print_number(item, 0);
                break;
J
Jiri Zouhar 已提交
1110
            case cJSON_Raw:
1111
                out = cJSON_strdup((unsigned char*)item->valuestring);
J
Jiri Zouhar 已提交
1112
                break;
M
Max Bruckner 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121
            case cJSON_String:
                out = print_string(item, 0);
                break;
            case cJSON_Array:
                out = print_array(item, depth, fmt, 0);
                break;
            case cJSON_Object:
                out = print_object(item, depth, fmt, 0);
                break;
1122 1123 1124
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
1125 1126 1127 1128
        }
    }

    return out;
K
Kevin Branigan 已提交
1129 1130 1131
}

/* Build an array from input text. */
1132
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer)
K
Kevin Branigan 已提交
1133
{
1134
    cJSON *head = NULL; /* head of the linked list */
1135 1136
    cJSON *current_item = NULL;

1137
    if (*input != '[')
M
Max Bruckner 已提交
1138
    {
1139
        /* not an array */
1140
        *error_pointer = input;
1141
        goto fail;
M
Max Bruckner 已提交
1142
    }
K
Kevin Branigan 已提交
1143

M
Max Bruckner 已提交
1144
    input = skip_whitespace(input + 1);
1145
    if (*input == ']')
M
Max Bruckner 已提交
1146
    {
1147
        /* empty array */
1148
        goto success;
M
Max Bruckner 已提交
1149
    }
K
Kevin Branigan 已提交
1150

1151
    /* step back to character in front of the first element */
1152
    input--;
M
Max Bruckner 已提交
1153
    /* loop through the comma separated array elements */
1154
    do
M
Max Bruckner 已提交
1155
    {
1156 1157 1158
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item();
        if (new_item == NULL)
M
Max Bruckner 已提交
1159
        {
1160
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1161
        }
1162 1163 1164

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1165
        {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
            /* 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 已提交
1178
        input = skip_whitespace(input + 1);
1179
        input = parse_value(current_item, input, error_pointer);
M
Max Bruckner 已提交
1180
        input = skip_whitespace(input);
1181
        if (input == NULL)
1182 1183
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1184 1185
        }
    }
1186
    while (*input == ',');
M
Max Bruckner 已提交
1187

1188
    if (*input != ']')
M
Max Bruckner 已提交
1189
    {
1190 1191
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1192 1193
    }

1194 1195
success:
    item->type = cJSON_Array;
1196
    item->child = head;
1197

1198
    return input + 1;
K
Kevin Branigan 已提交
1199

1200
fail:
1201
    if (head != NULL)
1202
    {
1203
        cJSON_Delete(head);
1204 1205
    }

1206
    return NULL;
K
Kevin Branigan 已提交
1207 1208 1209
}

/* Render an array to text */
1210
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1211
{
1212 1213 1214 1215
    unsigned char **entries;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
1216
    size_t len = 5;
M
Max Bruckner 已提交
1217
    cJSON *child = item->child;
1218 1219
    size_t numentries = 0;
    size_t i = 0;
M
Max Bruckner 已提交
1220
    cjbool fail = false;
M
Max Bruckner 已提交
1221
    size_t tmplen = 0;
K
Kevin Branigan 已提交
1222

M
Max Bruckner 已提交
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    /* How many entries in the array? */
    while (child)
    {
        numentries++;
        child = child->next;
    }

    /* Explicitly handle numentries == 0 */
    if (!numentries)
    {
1233 1234
        out = ensure(p, 3);
        if (out != NULL)
M
Max Bruckner 已提交
1235
        {
1236
            strcpy((char*)out, "[]");
M
Max Bruckner 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
        }

        return out;
    }

    if (p)
    {
        /* Compose the output array. */
        /* opening square bracket */
        i = p->offset;
        ptr = ensure(p, 1);
1248
        if (ptr == NULL)
M
Max Bruckner 已提交
1249
        {
1250
            return NULL;
M
Max Bruckner 已提交
1251 1252 1253 1254 1255 1256 1257
        }
        *ptr = '[';
        p->offset++;

        child = item->child;
        while (child && !fail)
        {
K
Kyle Chisholm 已提交
1258
            if (!print_value(child, depth + 1, fmt, p))
1259 1260 1261
            {
                return NULL;
            }
M
Max Bruckner 已提交
1262 1263 1264 1265 1266
            p->offset = update(p);
            if (child->next)
            {
                len = fmt ? 2 : 1;
                ptr = ensure(p, len + 1);
1267
                if (ptr == NULL)
M
Max Bruckner 已提交
1268
                {
1269
                    return NULL;
M
Max Bruckner 已提交
1270 1271 1272 1273 1274 1275
                }
                *ptr++ = ',';
                if(fmt)
                {
                    *ptr++ = ' ';
                }
1276
                *ptr = '\0';
M
Max Bruckner 已提交
1277 1278 1279 1280 1281
                p->offset += len;
            }
            child = child->next;
        }
        ptr = ensure(p, 2);
1282
        if (ptr == NULL)
M
Max Bruckner 已提交
1283
        {
1284
            return NULL;
M
Max Bruckner 已提交
1285 1286 1287 1288 1289 1290 1291 1292
        }
        *ptr++ = ']';
        *ptr = '\0';
        out = (p->buffer) + i;
    }
    else
    {
        /* Allocate an array to hold the pointers to all printed values */
1293
        entries = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1294 1295
        if (!entries)
        {
1296
            return NULL;
M
Max Bruckner 已提交
1297
        }
1298
        memset(entries, '\0', numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307

        /* Retrieve all the results: */
        child = item->child;
        while (child && !fail)
        {
            ret = print_value(child, depth + 1, fmt, 0);
            entries[i++] = ret;
            if (ret)
            {
1308
                len += strlen((char*)ret) + 2 + (fmt ? 1 : 0);
M
Max Bruckner 已提交
1309 1310 1311
            }
            else
            {
M
Max Bruckner 已提交
1312
                fail = true;
M
Max Bruckner 已提交
1313 1314 1315 1316 1317 1318 1319
            }
            child = child->next;
        }

        /* If we didn't fail, try to malloc the output string */
        if (!fail)
        {
1320
            out = (unsigned char*)cJSON_malloc(len);
M
Max Bruckner 已提交
1321 1322 1323 1324
        }
        /* If that fails, we fail. */
        if (!out)
        {
M
Max Bruckner 已提交
1325
            fail = true;
M
Max Bruckner 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
        }

        /* Handle failure. */
        if (fail)
        {
            /* free all the entries in the array */
            for (i = 0; i < numentries; i++)
            {
                if (entries[i])
                {
                    cJSON_free(entries[i]);
                }
            }
            cJSON_free(entries);
1340
            return NULL;
M
Max Bruckner 已提交
1341 1342 1343 1344 1345 1346 1347 1348
        }

        /* Compose the output array. */
        *out='[';
        ptr = out + 1;
        *ptr = '\0';
        for (i = 0; i < numentries; i++)
        {
1349
            tmplen = strlen((char*)entries[i]);
M
Max Bruckner 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358
            memcpy(ptr, entries[i], tmplen);
            ptr += tmplen;
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
                if(fmt)
                {
                    *ptr++ = ' ';
                }
1359
                *ptr = '\0';
M
Max Bruckner 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368
            }
            cJSON_free(entries[i]);
        }
        cJSON_free(entries);
        *ptr++ = ']';
        *ptr++ = '\0';
    }

    return out;
K
Kevin Branigan 已提交
1369 1370 1371
}

/* Build an object from the text. */
1372
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer)
K
Kevin Branigan 已提交
1373
{
1374
    cJSON *head = NULL; /* linked list head */
1375 1376
    cJSON *current_item = NULL;

1377
    if (*input != '{')
M
Max Bruckner 已提交
1378
    {
1379 1380
        *error_pointer = input;
        goto fail; /* not an object */
M
Max Bruckner 已提交
1381 1382
    }

M
Max Bruckner 已提交
1383
    input = skip_whitespace(input + 1);
1384
    if (*input == '}')
M
Max Bruckner 已提交
1385
    {
1386
        goto success; /* empty object */
M
Max Bruckner 已提交
1387 1388
    }

1389
    /* step back to character in front of the first element */
1390
    input--;
1391 1392
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1393
    {
1394 1395 1396 1397 1398 1399
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item();
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1400

1401 1402
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1403
        {
1404 1405 1406 1407 1408 1409 1410 1411 1412
            /* 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 已提交
1413 1414
        }

1415
        /* parse the name of the child */
M
Max Bruckner 已提交
1416
        input = skip_whitespace(input + 1);
1417
        input = parse_string(current_item, input, error_pointer);
M
Max Bruckner 已提交
1418
        input = skip_whitespace(input);
1419
        if (input == NULL)
M
Max Bruckner 已提交
1420
        {
1421
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1422 1423
        }

1424 1425 1426
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1427

1428
        if (*input != ':')
M
Max Bruckner 已提交
1429
        {
1430 1431
            *error_pointer = input;
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1432
        }
1433 1434

        /* parse the value */
M
Max Bruckner 已提交
1435
        input = skip_whitespace(input + 1);
1436
        input = parse_value(current_item, input, error_pointer);
M
Max Bruckner 已提交
1437
        input = skip_whitespace(input);
1438
        if (input == NULL)
M
Max Bruckner 已提交
1439
        {
1440
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1441 1442
        }
    }
1443
    while (*input == ',');
1444

1445
    if (*input != '}')
M
Max Bruckner 已提交
1446
    {
1447 1448
        *error_pointer = input;
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1449 1450
    }

1451 1452
success:
    item->type = cJSON_Object;
1453
    item->child = head;
1454

1455
    return input + 1;
1456 1457

fail:
1458
    if (head != NULL)
1459
    {
1460
        cJSON_Delete(head);
1461 1462
    }

1463
    return NULL;
K
Kevin Branigan 已提交
1464 1465 1466
}

/* Render an object to text. */
1467
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
1468 1469 1470 1471 1472 1473 1474
{
    unsigned char **entries = NULL;
    unsigned char **names = NULL;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
    unsigned char *str = NULL;
1475 1476 1477
    size_t len = 7;
    size_t i = 0;
    size_t j = 0;
M
Max Bruckner 已提交
1478
    cJSON *child = item->child;
1479
    size_t numentries = 0;
M
Max Bruckner 已提交
1480
    cjbool fail = false;
M
Max Bruckner 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    size_t tmplen = 0;

    /* Count the number of entries. */
    while (child)
    {
        numentries++;
        child = child->next;
    }

    /* Explicitly handle empty object case */
    if (!numentries)
    {
1493 1494
        out = ensure(p, fmt ? depth + 4 : 3);
        if (out == NULL)
M
Max Bruckner 已提交
1495
        {
1496
            return NULL;
M
Max Bruckner 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
        }
        ptr = out;
        *ptr++ = '{';
        if (fmt) {
            *ptr++ = '\n';
            for (i = 0; i < depth; i++)
            {
                *ptr++ = '\t';
            }
        }
        *ptr++ = '}';
        *ptr++ = '\0';

        return out;
    }

    if (p)
    {
        /* Compose the output: */
        i = p->offset;
        len = fmt ? 2 : 1; /* fmt: {\n */
        ptr = ensure(p, len + 1);
1519
        if (ptr == NULL)
M
Max Bruckner 已提交
1520
        {
1521
            return NULL;
M
Max Bruckner 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
        }

        *ptr++ = '{';
        if (fmt)
        {
            *ptr++ = '\n';
        }
        *ptr = '\0';
        p->offset += len;

        child = item->child;
        depth++;
        while (child)
        {
            if (fmt)
            {
                ptr = ensure(p, depth);
1539
                if (ptr == NULL)
M
Max Bruckner 已提交
1540
                {
1541
                    return NULL;
M
Max Bruckner 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550
                }
                for (j = 0; j < depth; j++)
                {
                    *ptr++ = '\t';
                }
                p->offset += depth;
            }

            /* print key */
1551
            if (!print_string_ptr((unsigned char*)child->string, p))
1552 1553 1554
            {
                return NULL;
            }
M
Max Bruckner 已提交
1555 1556 1557 1558
            p->offset = update(p);

            len = fmt ? 2 : 1;
            ptr = ensure(p, len);
1559
            if (ptr == NULL)
M
Max Bruckner 已提交
1560
            {
1561
                return NULL;
M
Max Bruckner 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570
            }
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
            p->offset+=len;

            /* print value */
K
Kyle Chisholm 已提交
1571 1572 1573 1574
            if (!print_value(child, depth, fmt, p))
            {
                return NULL;
            };
M
Max Bruckner 已提交
1575 1576 1577
            p->offset = update(p);

            /* print comma if not last */
M
Max Bruckner 已提交
1578
            len = (size_t) (fmt ? 1 : 0) + (child->next ? 1 : 0);
M
Max Bruckner 已提交
1579
            ptr = ensure(p, len + 1);
1580
            if (ptr == NULL)
M
Max Bruckner 已提交
1581
            {
1582
                return NULL;
M
Max Bruckner 已提交
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
            }
            if (child->next)
            {
                *ptr++ = ',';
            }

            if (fmt)
            {
                *ptr++ = '\n';
            }
            *ptr = '\0';
            p->offset += len;

            child = child->next;
        }

        ptr = ensure(p, fmt ? (depth + 1) : 2);
1600
        if (ptr == NULL)
M
Max Bruckner 已提交
1601
        {
1602
            return NULL;
M
Max Bruckner 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
        }
        if (fmt)
        {
            for (i = 0; i < (depth - 1); i++)
            {
                *ptr++ = '\t';
            }
        }
        *ptr++ = '}';
        *ptr = '\0';
        out = (p->buffer) + i;
    }
    else
    {
        /* Allocate space for the names and the objects */
1618
        entries = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1619 1620
        if (!entries)
        {
1621
            return NULL;
M
Max Bruckner 已提交
1622
        }
1623
        names = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1624 1625 1626
        if (!names)
        {
            cJSON_free(entries);
1627
            return NULL;
M
Max Bruckner 已提交
1628
        }
1629 1630
        memset(entries, '\0', sizeof(unsigned char*) * numentries);
        memset(names, '\0', sizeof(unsigned char*) * numentries);
M
Max Bruckner 已提交
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640

        /* Collect all the results into our arrays: */
        child = item->child;
        depth++;
        if (fmt)
        {
            len += depth;
        }
        while (child && !fail)
        {
1641
            names[i] = str = print_string_ptr((unsigned char*)child->string, 0); /* print key */
M
Max Bruckner 已提交
1642 1643 1644
            entries[i++] = ret = print_value(child, depth, fmt, 0);
            if (str && ret)
            {
1645
                len += strlen((char*)ret) + strlen((char*)str) + 2 + (fmt ? 2 + depth : 0);
M
Max Bruckner 已提交
1646 1647 1648
            }
            else
            {
M
Max Bruckner 已提交
1649
                fail = true;
M
Max Bruckner 已提交
1650 1651 1652 1653 1654 1655 1656
            }
            child = child->next;
        }

        /* Try to allocate the output string */
        if (!fail)
        {
1657
            out = (unsigned char*)cJSON_malloc(len);
M
Max Bruckner 已提交
1658 1659 1660
        }
        if (!out)
        {
M
Max Bruckner 已提交
1661
            fail = true;
M
Max Bruckner 已提交
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
        }

        /* Handle failure */
        if (fail)
        {
            /* free all the printed keys and values */
            for (i = 0; i < numentries; i++)
            {
                if (names[i])
                {
                    cJSON_free(names[i]);
                }
                if (entries[i])
                {
                    cJSON_free(entries[i]);
                }
            }
            cJSON_free(names);
            cJSON_free(entries);
1681
            return NULL;
M
Max Bruckner 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690
        }

        /* Compose the output: */
        *out = '{';
        ptr = out + 1;
        if (fmt)
        {
            *ptr++ = '\n';
        }
1691
        *ptr = '\0';
M
Max Bruckner 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700
        for (i = 0; i < numentries; i++)
        {
            if (fmt)
            {
                for (j = 0; j < depth; j++)
                {
                    *ptr++='\t';
                }
            }
1701
            tmplen = strlen((char*)names[i]);
M
Max Bruckner 已提交
1702 1703 1704 1705 1706 1707 1708
            memcpy(ptr, names[i], tmplen);
            ptr += tmplen;
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
1709 1710
            strcpy((char*)ptr, (char*)entries[i]);
            ptr += strlen((char*)entries[i]);
M
Max Bruckner 已提交
1711 1712 1713 1714 1715 1716 1717 1718
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
            }
            if (fmt)
            {
                *ptr++ = '\n';
            }
1719
            *ptr = '\0';
M
Max Bruckner 已提交
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
            cJSON_free(names[i]);
            cJSON_free(entries[i]);
        }

        cJSON_free(names);
        cJSON_free(entries);
        if (fmt)
        {
            for (i = 0; i < (depth - 1); i++)
            {
                *ptr++ = '\t';
            }
        }
        *ptr++ = '}';
        *ptr++ = '\0';
    }

    return out;
K
Kevin Branigan 已提交
1738 1739 1740
}

/* Get Array size/item / object item. */
M
Max Bruckner 已提交
1741
int cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1742 1743
{
    cJSON *c = array->child;
1744
    size_t i = 0;
M
Max Bruckner 已提交
1745 1746 1747 1748 1749
    while(c)
    {
        i++;
        c = c->next;
    }
1750 1751 1752

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

M
Max Bruckner 已提交
1753
    return (int)i;
M
Max Bruckner 已提交
1754 1755
}

1756
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1757
{
1758
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1768
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1769
{
1770
    cJSON *c = object ? object->child : NULL;
1771
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1772 1773 1774 1775 1776 1777
    {
        c = c->next;
    }
    return c;
}

1778
cjbool cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1779 1780 1781
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1782 1783

/* Utility for array list handling. */
M
Max Bruckner 已提交
1784 1785 1786 1787 1788 1789
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1790
/* Utility for handling references. */
1791
static cJSON *create_reference(const cJSON *item)
M
Max Bruckner 已提交
1792 1793 1794 1795
{
    cJSON *ref = cJSON_New_Item();
    if (!ref)
    {
1796
        return NULL;
M
Max Bruckner 已提交
1797 1798
    }
    memcpy(ref, item, sizeof(cJSON));
1799
    ref->string = NULL;
M
Max Bruckner 已提交
1800
    ref->type |= cJSON_IsReference;
1801
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1802 1803
    return ref;
}
K
Kevin Branigan 已提交
1804 1805

/* Add item to array/object. */
1806
void cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1807
{
1808 1809 1810
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1811 1812 1813
    {
        return;
    }
1814 1815 1816 1817

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1818 1819 1820 1821 1822 1823 1824
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1825
        while (child->next)
M
Max Bruckner 已提交
1826
        {
1827
            child = child->next;
M
Max Bruckner 已提交
1828
        }
1829
        suffix_object(child, item);
M
Max Bruckner 已提交
1830 1831 1832
    }
}

M
Max Bruckner 已提交
1833 1834
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
1835 1836 1837 1838
    /* call cJSON_AddItemToObjectCS for code reuse */
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string), item);
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1839 1840
}

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
/* Add an item to an object with constant string as key */
void   cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
        cJSON_free(item->string);
    }
1852 1853
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1854
    item->string = (char*)string;
1855
#pragma GCC diagnostic pop
1856 1857 1858 1859
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1860 1861 1862 1863 1864
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    cJSON_AddItemToArray(array, create_reference(item));
}

1865 1866 1867 1868 1869
void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
    cJSON_AddItemToObject(object, string, create_reference(item));
}

M
Max Bruckner 已提交
1870
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1881
        return NULL;
1882
    }
1883
    if (c->prev)
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    {
        /* 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 */
1897
    c->prev = c->next = NULL;
1898 1899 1900

    return c;
}
M
Max Bruckner 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909
cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
    if (which < 0)
    {
        return NULL;
    }

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

1911 1912 1913 1914 1915
void cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1916 1917
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
1918
    size_t i = 0;
1919
    cJSON *c = object->child;
1920
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1921 1922 1923 1924 1925 1926
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1927
        return DetachItemFromArray(object, i);
1928 1929
    }

1930
    return NULL;
1931 1932
}

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

/* Replace array/object items with new ones. */
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
void cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
{
    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 已提交
1965
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
{
    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;
    }
1991
    c->next = c->prev = NULL;
1992 1993
    cJSON_Delete(c);
}
M
Max Bruckner 已提交
1994 1995 1996 1997 1998 1999 2000 2001 2002
void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    if (which < 0)
    {
        return;
    }

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

2004 2005
void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
2006
    size_t i = 0;
2007
    cJSON *c = object->child;
2008
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
2009 2010 2011 2012 2013 2014
    {
        i++;
        c = c->next;
    }
    if(c)
    {
2015 2016 2017 2018 2019 2020
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
             cJSON_free(newitem->string);
        }

2021
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
2022
        ReplaceItemInArray(object, i, newitem);
2023 2024
    }
}
K
Kevin Branigan 已提交
2025 2026

/* Create basic types: */
M
Max Bruckner 已提交
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
cJSON *cJSON_CreateNull(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

M
Max Bruckner 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
cJSON *cJSON_CreateTrue(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

M
Max Bruckner 已提交
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
cJSON *cJSON_CreateFalse(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
2060
cJSON *cJSON_CreateBool(cjbool b)
M
Max Bruckner 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
2071 2072 2073 2074 2075 2076 2077
cJSON *cJSON_CreateNumber(double num)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091

        /* 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 已提交
2092 2093 2094 2095 2096
    }

    return item;
}

M
Max Bruckner 已提交
2097 2098 2099 2100 2101 2102
cJSON *cJSON_CreateString(const char *string)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_String;
2103
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
2104 2105 2106
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2107
            return NULL;
M
Max Bruckner 已提交
2108 2109 2110 2111 2112 2113
        }
    }

    return item;
}

J
Jiri Zouhar 已提交
2114 2115
extern cJSON *cJSON_CreateRaw(const char *raw)
{
M
Max Bruckner 已提交
2116 2117 2118 2119
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Raw;
2120
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw);
M
Max Bruckner 已提交
2121 2122 2123 2124 2125 2126 2127 2128
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2129 2130
}

M
Max Bruckner 已提交
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
cJSON *cJSON_CreateArray(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

M
Max Bruckner 已提交
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
cJSON *cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item();
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2152 2153

/* Create Arrays: */
M
Max Bruckner 已提交
2154 2155
cJSON *cJSON_CreateIntArray(const int *numbers, int count)
{
2156
    size_t i = 0;
2157 2158
    cJSON *n = NULL;
    cJSON *p = NULL;
2159 2160 2161 2162 2163 2164 2165 2166 2167
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

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

    return a;
}

M
Max Bruckner 已提交
2189 2190
cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
{
2191
    size_t i = 0;
2192 2193
    cJSON *n = NULL;
    cJSON *p = NULL;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2204 2205 2206 2207 2208
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2209
            return NULL;
M
Max Bruckner 已提交
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2225 2226
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
2227
    size_t i = 0;
2228 2229
    cJSON *n = NULL;
    cJSON *p = NULL;
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2240 2241 2242 2243 2244
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2245
            return NULL;
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2261 2262
cJSON *cJSON_CreateStringArray(const char **strings, int count)
{
2263
    size_t i = 0;
2264 2265
    cJSON *n = NULL;
    cJSON *p = NULL;
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2276 2277 2278 2279 2280
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2281
            return NULL;
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2296 2297

/* Duplication */
M
Max Bruckner 已提交
2298
cJSON *cJSON_Duplicate(const cJSON *item, cjbool recurse)
2299
{
M
Max Bruckner 已提交
2300
    cJSON *newitem = NULL;
2301 2302
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2303
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2304 2305 2306 2307

    /* Bail on bad ptr */
    if (!item)
    {
2308
        goto fail;
M
Max Bruckner 已提交
2309 2310 2311 2312 2313
    }
    /* Create new item */
    newitem = cJSON_New_Item();
    if (!newitem)
    {
2314
        goto fail;
M
Max Bruckner 已提交
2315 2316 2317 2318 2319 2320 2321
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2322
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring);
M
Max Bruckner 已提交
2323 2324
        if (!newitem->valuestring)
        {
2325
            goto fail;
M
Max Bruckner 已提交
2326 2327 2328 2329
        }
    }
    if (item->string)
    {
2330
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string);
M
Max Bruckner 已提交
2331 2332
        if (!newitem->string)
        {
2333
            goto fail;
M
Max Bruckner 已提交
2334 2335 2336 2337 2338 2339 2340 2341
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2342 2343
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2344
    {
2345
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2346 2347
        if (!newchild)
        {
2348
            goto fail;
M
Max Bruckner 已提交
2349
        }
2350
        if (next != NULL)
M
Max Bruckner 已提交
2351 2352
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2353 2354 2355
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2356 2357 2358 2359
        }
        else
        {
            /* Set newitem->child and move to it */
2360 2361
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2362
        }
2363
        child = child->next;
M
Max Bruckner 已提交
2364 2365 2366
    }

    return newitem;
2367 2368 2369 2370 2371 2372 2373 2374

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

    return NULL;
2375
}
2376 2377 2378

void cJSON_Minify(char *json)
{
2379
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
    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 已提交
2419
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2420 2421 2422 2423
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2424
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2425
                }
M
Max Bruckner 已提交
2426
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2427
            }
M
Max Bruckner 已提交
2428
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2429 2430 2431 2432
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2433
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2434 2435 2436 2437 2438
        }
    }

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