cJSON.c 49.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 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 * const p, size_t needed)
240
{
241
    unsigned char *newbuffer = NULL;
242 243
    size_t newsize = 0;

244
    if ((p == NULL) || (p->buffer == NULL))
245
    {
246
        return NULL;
247 248
    }

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

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

261 262 263 264
    if (p->noalloc) {
        return NULL;
    }

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    /* 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 已提交
280
    if (cJSON_realloc != NULL)
M
Max Bruckner 已提交
281
    {
M
Max Bruckner 已提交
282 283
        /* reallocate with realloc if available */
        newbuffer = (unsigned char*)cJSON_realloc(p->buffer, newsize);
M
Max Bruckner 已提交
284
    }
M
Max Bruckner 已提交
285
    else
M
Max Bruckner 已提交
286
    {
M
Max Bruckner 已提交
287 288 289 290 291 292 293 294 295 296 297 298
        /* 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)
        {
299
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
300 301
        }
        cJSON_free(p->buffer);
M
Max Bruckner 已提交
302 303 304 305 306
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
307 308
}

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

M
Max Bruckner 已提交
319
    return p->offset + strlen((const char*)str);
320 321 322
}

/* Render the number nicely from the given item into a string. */
M
Max Bruckner 已提交
323
static unsigned char *print_number(const cJSON * const item, printbuffer * const output_buffer)
324
{
M
Max Bruckner 已提交
325
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
326
    double d = item->valuedouble;
M
Max Bruckner 已提交
327

M
Max Bruckner 已提交
328
    if (output_buffer == NULL)
M
Max Bruckner 已提交
329 330 331 332
    {
        return NULL;
    }

M
Max Bruckner 已提交
333
    /* value is an int */
334
    if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
M
Max Bruckner 已提交
335
    {
M
Max Bruckner 已提交
336 337 338
        /* 2^64+1 can be represented in 21 chars. */
        output_pointer = ensure(output_buffer, 21);
        if (output_pointer != NULL)
M
Max Bruckner 已提交
339
        {
M
Max Bruckner 已提交
340
            sprintf((char*)output_pointer, "%d", item->valueint);
M
Max Bruckner 已提交
341 342 343 344 345
        }
    }
    /* value is a floating point number */
    else
    {
346
        /* This is a nice tradeoff. */
M
Max Bruckner 已提交
347 348
        output_pointer = ensure(output_buffer, 64);
        if (output_pointer != NULL)
M
Max Bruckner 已提交
349 350 351 352
        {
            /* This checks for NaN and Infinity */
            if ((d * 0) != 0)
            {
M
Max Bruckner 已提交
353
                sprintf((char*)output_pointer, "null");
M
Max Bruckner 已提交
354
            }
355
            else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
M
Max Bruckner 已提交
356
            {
M
Max Bruckner 已提交
357
                sprintf((char*)output_pointer, "%.0f", d);
M
Max Bruckner 已提交
358 359 360
            }
            else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
            {
M
Max Bruckner 已提交
361
                sprintf((char*)output_pointer, "%e", d);
M
Max Bruckner 已提交
362 363 364
            }
            else
            {
M
Max Bruckner 已提交
365
                sprintf((char*)output_pointer, "%f", d);
M
Max Bruckner 已提交
366 367 368
            }
        }
    }
369

M
Max Bruckner 已提交
370
    return output_pointer;
K
Kevin Branigan 已提交
371 372
}

M
Max Bruckner 已提交
373
/* parse 4 digit hexadecimal number */
374
static unsigned parse_hex4(const unsigned char * const input)
375
{
M
Max Bruckner 已提交
376
    unsigned int h = 0;
377
    size_t i = 0;
M
Max Bruckner 已提交
378

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

399 400 401 402 403
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
404 405 406
    }

    return h;
407 408
}

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

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

438 439
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
440
    {
441
        *error_pointer = first_sequence;
442
        goto fail;
M
Max Bruckner 已提交
443
    }
M
Max Bruckner 已提交
444

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

        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 已提交
484
    }
M
Max Bruckner 已提交
485

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

516 517 518 519 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
    /* 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. */
548
static const unsigned char *parse_string(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer)
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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
{
    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 已提交
596
    /* loop through the string literal */
597
    while (input_pointer < input_end)
M
Max Bruckner 已提交
598
    {
599
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
600
        {
601
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
602 603 604 605
        }
        /* escape sequence */
        else
        {
606
            unsigned char sequence_length = 2;
607
            switch (input_pointer[1])
M
Max Bruckner 已提交
608 609
            {
                case 'b':
610
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
611 612
                    break;
                case 'f':
613
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
614 615
                    break;
                case 'n':
616
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
617 618
                    break;
                case 'r':
619
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
620 621
                    break;
                case 't':
622
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
623
                    break;
624 625 626
                case '\"':
                case '\\':
                case '/':
627
                    *output_pointer++ = input_pointer[1];
628
                    break;
629 630

                /* UTF-16 literal */
M
Max Bruckner 已提交
631
                case 'u':
632 633
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer, error_pointer);
                    if (sequence_length == 0)
M
Max Bruckner 已提交
634
                    {
635
                        /* failed to convert UTF16-literal to UTF-8 */
636
                        goto fail;
M
Max Bruckner 已提交
637 638
                    }
                    break;
639

M
Max Bruckner 已提交
640
                default:
641
                    *error_pointer = input_pointer;
642
                    goto fail;
M
Max Bruckner 已提交
643
            }
644
            input_pointer += sequence_length;
M
Max Bruckner 已提交
645 646
        }
    }
647 648 649

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

651
    item->type = cJSON_String;
652
    item->valuestring = (char*)output;
653

654
    return input_end + 1;
655 656

fail:
657
    if (output != NULL)
658
    {
659
        cJSON_free(output);
660 661 662
    }

    return NULL;
K
Kevin Branigan 已提交
663 664 665
}

/* Render the cstring provided to an escaped version that can be printed. */
666
static unsigned char *print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
K
Kevin Branigan 已提交
667
{
668 669 670 671 672
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
    size_t length = 0;
    cjbool contains_special_char = false;
M
Max Bruckner 已提交
673
    unsigned char token = '\0';
M
Max Bruckner 已提交
674

675
    if (output_buffer == NULL)
M
Max Bruckner 已提交
676 677 678 679
    {
        return NULL;
    }

M
Max Bruckner 已提交
680
    /* empty string */
681
    if (input == NULL)
M
Max Bruckner 已提交
682
    {
683 684
        output = ensure(output_buffer, 3);
        if (output == NULL)
M
Max Bruckner 已提交
685
        {
686
            return NULL;
M
Max Bruckner 已提交
687
        }
688
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
689

690
        return output;
M
Max Bruckner 已提交
691 692 693
    }

    /* set "flag" to 1 if something needs to be escaped */
694
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
695
    {
696 697 698
        contains_special_char |= (((*input_pointer > 0) && (*input_pointer < 32)) /* unprintable characters */
                || (*input_pointer == '\"') /* double quote */
                || (*input_pointer == '\\')) /* backslash */
M
Max Bruckner 已提交
699 700 701 702
            ? 1
            : 0;
    }
    /* no characters have to be escaped */
703
    if (!contains_special_char)
M
Max Bruckner 已提交
704
    {
705
        length = (size_t)(input_pointer - input);
706

707 708
        output = ensure(output_buffer, length + 3);
        if (output == NULL)
M
Max Bruckner 已提交
709
        {
710
            return NULL;
M
Max Bruckner 已提交
711 712
        }

713 714 715 716 717
        output_pointer = output;
        *output_pointer++ = '\"';
        strcpy((char*)output_pointer, (const char*)input);
        output_pointer[length] = '\"';
        output_pointer[length + 1] = '\0';
M
Max Bruckner 已提交
718

719
        return output;
M
Max Bruckner 已提交
720 721
    }

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

738 739
    output = ensure(output_buffer, length + 3);
    if (output == NULL)
M
Max Bruckner 已提交
740
    {
741
        return NULL;
M
Max Bruckner 已提交
742 743
    }

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

793
    return output;
K
Kevin Branigan 已提交
794
}
M
Max Bruckner 已提交
795

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

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

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

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

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

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

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

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

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

M
Max Bruckner 已提交
867 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
#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 已提交
918
/* Render a cJSON item/entity/structure to text. */
919
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
920
{
M
Max Bruckner 已提交
921
    return (char*)print(item, true);
M
Max Bruckner 已提交
922 923
}

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

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

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

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

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

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

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

    if (len < 0)
    {
        return false;
    }

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

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

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

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

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

    if (!item)
    {
1028
        return NULL;
M
Max Bruckner 已提交
1029
    }
M
Max Bruckner 已提交
1030 1031 1032 1033 1034 1035 1036

    if (p == NULL)
    {
        return NULL;
    }

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

            raw_length = strlen(item->valuestring) + sizeof('\0');
            out = ensure(p, raw_length);
            if (out != NULL)
            {
                memcpy(out, item->valuestring, raw_length);
            }
            break;
M
Max Bruckner 已提交
1082
        }
M
Max Bruckner 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        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;
        default:
            out = NULL;
            break;
M
Max Bruckner 已提交
1095 1096 1097
    }

    return out;
K
Kevin Branigan 已提交
1098 1099 1100
}

/* Build an array from input text. */
1101
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer)
K
Kevin Branigan 已提交
1102
{
1103
    cJSON *head = NULL; /* head of the linked list */
1104 1105
    cJSON *current_item = NULL;

1106
    if (*input != '[')
M
Max Bruckner 已提交
1107
    {
1108
        /* not an array */
1109
        *error_pointer = input;
1110
        goto fail;
M
Max Bruckner 已提交
1111
    }
K
Kevin Branigan 已提交
1112

M
Max Bruckner 已提交
1113
    input = skip_whitespace(input + 1);
1114
    if (*input == ']')
M
Max Bruckner 已提交
1115
    {
1116
        /* empty array */
1117
        goto success;
M
Max Bruckner 已提交
1118
    }
K
Kevin Branigan 已提交
1119

1120
    /* step back to character in front of the first element */
1121
    input--;
M
Max Bruckner 已提交
1122
    /* loop through the comma separated array elements */
1123
    do
M
Max Bruckner 已提交
1124
    {
1125 1126 1127
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item();
        if (new_item == NULL)
M
Max Bruckner 已提交
1128
        {
1129
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1130
        }
1131 1132 1133

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1134
        {
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
            /* 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 已提交
1147
        input = skip_whitespace(input + 1);
1148
        input = parse_value(current_item, input, error_pointer);
M
Max Bruckner 已提交
1149
        input = skip_whitespace(input);
1150
        if (input == NULL)
1151 1152
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1153 1154
        }
    }
1155
    while (*input == ',');
M
Max Bruckner 已提交
1156

1157
    if (*input != ']')
M
Max Bruckner 已提交
1158
    {
1159 1160
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1161 1162
    }

1163 1164
success:
    item->type = cJSON_Array;
1165
    item->child = head;
1166

1167
    return input + 1;
K
Kevin Branigan 已提交
1168

1169
fail:
1170
    if (head != NULL)
1171
    {
1172
        cJSON_Delete(head);
1173 1174
    }

1175
    return NULL;
K
Kevin Branigan 已提交
1176 1177 1178
}

/* Render an array to text */
1179
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1180
{
1181 1182
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
1183
    size_t len = 5;
M
Max Bruckner 已提交
1184
    cJSON *child = item->child;
1185 1186
    size_t numentries = 0;
    size_t i = 0;
M
Max Bruckner 已提交
1187
    cjbool fail = false;
M
Max Bruckner 已提交
1188 1189 1190 1191 1192

    if (p == NULL)
    {
        return NULL;
    }
K
Kevin Branigan 已提交
1193

M
Max Bruckner 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    /* How many entries in the array? */
    while (child)
    {
        numentries++;
        child = child->next;
    }

    /* Explicitly handle numentries == 0 */
    if (!numentries)
    {
1204 1205
        out = ensure(p, 3);
        if (out != NULL)
M
Max Bruckner 已提交
1206
        {
1207
            strcpy((char*)out, "[]");
M
Max Bruckner 已提交
1208 1209 1210 1211 1212
        }

        return out;
    }

M
Max Bruckner 已提交
1213 1214 1215 1216 1217
    /* Compose the output array. */
    /* opening square bracket */
    i = p->offset;
    ptr = ensure(p, 1);
    if (ptr == NULL)
M
Max Bruckner 已提交
1218
    {
M
Max Bruckner 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227
        return NULL;
    }
    *ptr = '[';
    p->offset++;

    child = item->child;
    while (child && !fail)
    {
        if (!print_value(child, depth + 1, fmt, p))
M
Max Bruckner 已提交
1228
        {
1229
            return NULL;
M
Max Bruckner 已提交
1230
        }
M
Max Bruckner 已提交
1231 1232
        p->offset = update(p);
        if (child->next)
M
Max Bruckner 已提交
1233
        {
M
Max Bruckner 已提交
1234 1235 1236
            len = fmt ? 2 : 1;
            ptr = ensure(p, len + 1);
            if (ptr == NULL)
1237 1238 1239
            {
                return NULL;
            }
M
Max Bruckner 已提交
1240 1241
            *ptr++ = ',';
            if(fmt)
M
Max Bruckner 已提交
1242
            {
M
Max Bruckner 已提交
1243
                *ptr++ = ' ';
M
Max Bruckner 已提交
1244
            }
M
Max Bruckner 已提交
1245 1246
            *ptr = '\0';
            p->offset += len;
M
Max Bruckner 已提交
1247
        }
M
Max Bruckner 已提交
1248
        child = child->next;
M
Max Bruckner 已提交
1249
    }
M
Max Bruckner 已提交
1250 1251
    ptr = ensure(p, 2);
    if (ptr == NULL)
M
Max Bruckner 已提交
1252
    {
M
Max Bruckner 已提交
1253
        return NULL;
M
Max Bruckner 已提交
1254
    }
M
Max Bruckner 已提交
1255 1256 1257
    *ptr++ = ']';
    *ptr = '\0';
    out = (p->buffer) + i;
M
Max Bruckner 已提交
1258 1259

    return out;
K
Kevin Branigan 已提交
1260 1261 1262
}

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

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

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

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

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

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

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

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

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

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

1342 1343
success:
    item->type = cJSON_Object;
1344
    item->child = head;
1345

1346
    return input + 1;
1347 1348

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

1354
    return NULL;
K
Kevin Branigan 已提交
1355 1356 1357
}

/* Render an object to text. */
1358
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
1359 1360 1361
{
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
1362 1363 1364
    size_t len = 7;
    size_t i = 0;
    size_t j = 0;
M
Max Bruckner 已提交
1365
    cJSON *child = item->child;
1366
    size_t numentries = 0;
M
Max Bruckner 已提交
1367 1368 1369 1370 1371

    if (p == NULL)
    {
        return NULL;
    }
M
Max Bruckner 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

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

    /* Explicitly handle empty object case */
    if (!numentries)
    {
1383 1384
        out = ensure(p, fmt ? depth + 4 : 3);
        if (out == NULL)
M
Max Bruckner 已提交
1385
        {
1386
            return NULL;
M
Max Bruckner 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        }
        ptr = out;
        *ptr++ = '{';
        if (fmt) {
            *ptr++ = '\n';
            for (i = 0; i < depth; i++)
            {
                *ptr++ = '\t';
            }
        }
        *ptr++ = '}';
        *ptr++ = '\0';

        return out;
    }

M
Max Bruckner 已提交
1403 1404 1405 1406 1407
    /* Compose the output: */
    i = p->offset;
    len = fmt ? 2 : 1; /* fmt: {\n */
    ptr = ensure(p, len + 1);
    if (ptr == NULL)
M
Max Bruckner 已提交
1408
    {
M
Max Bruckner 已提交
1409 1410
        return NULL;
    }
M
Max Bruckner 已提交
1411

M
Max Bruckner 已提交
1412 1413 1414 1415 1416 1417 1418
    *ptr++ = '{';
    if (fmt)
    {
        *ptr++ = '\n';
    }
    *ptr = '\0';
    p->offset += len;
M
Max Bruckner 已提交
1419

M
Max Bruckner 已提交
1420 1421 1422 1423 1424
    child = item->child;
    depth++;
    while (child)
    {
        if (fmt)
M
Max Bruckner 已提交
1425
        {
M
Max Bruckner 已提交
1426
            ptr = ensure(p, depth);
1427
            if (ptr == NULL)
M
Max Bruckner 已提交
1428
            {
1429
                return NULL;
M
Max Bruckner 已提交
1430
            }
M
Max Bruckner 已提交
1431
            for (j = 0; j < depth; j++)
M
Max Bruckner 已提交
1432 1433 1434
            {
                *ptr++ = '\t';
            }
M
Max Bruckner 已提交
1435
            p->offset += depth;
M
Max Bruckner 已提交
1436 1437
        }

M
Max Bruckner 已提交
1438 1439
        /* print key */
        if (!print_string_ptr((unsigned char*)child->string, p))
M
Max Bruckner 已提交
1440
        {
1441
            return NULL;
M
Max Bruckner 已提交
1442
        }
M
Max Bruckner 已提交
1443 1444 1445 1446 1447
        p->offset = update(p);

        len = fmt ? 2 : 1;
        ptr = ensure(p, len);
        if (ptr == NULL)
M
Max Bruckner 已提交
1448
        {
1449
            return NULL;
M
Max Bruckner 已提交
1450
        }
M
Max Bruckner 已提交
1451
        *ptr++ = ':';
M
Max Bruckner 已提交
1452 1453
        if (fmt)
        {
M
Max Bruckner 已提交
1454
            *ptr++ = '\t';
M
Max Bruckner 已提交
1455
        }
M
Max Bruckner 已提交
1456
        p->offset+=len;
M
Max Bruckner 已提交
1457

M
Max Bruckner 已提交
1458 1459
        /* print value */
        if (!print_value(child, depth, fmt, p))
M
Max Bruckner 已提交
1460
        {
M
Max Bruckner 已提交
1461
            return NULL;
M
Max Bruckner 已提交
1462
        }
M
Max Bruckner 已提交
1463
        p->offset = update(p);
M
Max Bruckner 已提交
1464

M
Max Bruckner 已提交
1465 1466 1467 1468
        /* print comma if not last */
        len = (size_t) (fmt ? 1 : 0) + (child->next ? 1 : 0);
        ptr = ensure(p, len + 1);
        if (ptr == NULL)
M
Max Bruckner 已提交
1469
        {
1470
            return NULL;
M
Max Bruckner 已提交
1471
        }
M
Max Bruckner 已提交
1472 1473 1474 1475
        if (child->next)
        {
            *ptr++ = ',';
        }
M
Max Bruckner 已提交
1476 1477 1478 1479 1480

        if (fmt)
        {
            *ptr++ = '\n';
        }
1481
        *ptr = '\0';
M
Max Bruckner 已提交
1482
        p->offset += len;
M
Max Bruckner 已提交
1483

M
Max Bruckner 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        child = child->next;
    }

    ptr = ensure(p, fmt ? (depth + 1) : 2);
    if (ptr == NULL)
    {
        return NULL;
    }
    if (fmt)
    {
        for (i = 0; i < (depth - 1); i++)
M
Max Bruckner 已提交
1495
        {
M
Max Bruckner 已提交
1496
            *ptr++ = '\t';
M
Max Bruckner 已提交
1497 1498
        }
    }
M
Max Bruckner 已提交
1499 1500 1501
    *ptr++ = '}';
    *ptr = '\0';
    out = (p->buffer) + i;
M
Max Bruckner 已提交
1502 1503

    return out;
K
Kevin Branigan 已提交
1504 1505 1506
}

/* Get Array size/item / object item. */
M
Max Bruckner 已提交
1507
int cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1508 1509
{
    cJSON *c = array->child;
1510
    size_t i = 0;
M
Max Bruckner 已提交
1511 1512 1513 1514 1515
    while(c)
    {
        i++;
        c = c->next;
    }
1516 1517 1518

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

M
Max Bruckner 已提交
1519
    return (int)i;
M
Max Bruckner 已提交
1520 1521
}

1522
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1523
{
1524
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1534
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1535
{
1536
    cJSON *c = object ? object->child : NULL;
1537
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1538 1539 1540 1541 1542 1543
    {
        c = c->next;
    }
    return c;
}

1544
cjbool cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1545 1546 1547
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1548 1549

/* Utility for array list handling. */
M
Max Bruckner 已提交
1550 1551 1552 1553 1554 1555
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1556
/* Utility for handling references. */
1557
static cJSON *create_reference(const cJSON *item)
M
Max Bruckner 已提交
1558 1559 1560 1561
{
    cJSON *ref = cJSON_New_Item();
    if (!ref)
    {
1562
        return NULL;
M
Max Bruckner 已提交
1563 1564
    }
    memcpy(ref, item, sizeof(cJSON));
1565
    ref->string = NULL;
M
Max Bruckner 已提交
1566
    ref->type |= cJSON_IsReference;
1567
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1568 1569
    return ref;
}
K
Kevin Branigan 已提交
1570 1571

/* Add item to array/object. */
1572
void cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1573
{
1574 1575 1576
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1577 1578 1579
    {
        return;
    }
1580 1581 1582 1583

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1584 1585 1586 1587 1588 1589 1590
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1591
        while (child->next)
M
Max Bruckner 已提交
1592
        {
1593
            child = child->next;
M
Max Bruckner 已提交
1594
        }
1595
        suffix_object(child, item);
M
Max Bruckner 已提交
1596 1597 1598
    }
}

M
Max Bruckner 已提交
1599 1600
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
1601 1602 1603 1604
    /* 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 已提交
1605 1606
}

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
/* 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);
    }
1618 1619
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1620
    item->string = (char*)string;
1621
#pragma GCC diagnostic pop
1622 1623 1624 1625
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1626 1627 1628 1629 1630
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    cJSON_AddItemToArray(array, create_reference(item));
}

1631 1632 1633 1634 1635
void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
    cJSON_AddItemToObject(object, string, create_reference(item));
}

M
Max Bruckner 已提交
1636
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1647
        return NULL;
1648
    }
1649
    if (c->prev)
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
    {
        /* 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 */
1663
    c->prev = c->next = NULL;
1664 1665 1666

    return c;
}
M
Max Bruckner 已提交
1667 1668 1669 1670 1671 1672 1673 1674 1675
cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
    if (which < 0)
    {
        return NULL;
    }

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

1677 1678 1679 1680 1681
void cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1682 1683
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
1684
    size_t i = 0;
1685
    cJSON *c = object->child;
1686
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1687 1688 1689 1690 1691 1692
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1693
        return DetachItemFromArray(object, i);
1694 1695
    }

1696
    return NULL;
1697 1698
}

1699 1700 1701 1702
void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1703 1704

/* Replace array/object items with new ones. */
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
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 已提交
1731
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
{
    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;
    }
1757
    c->next = c->prev = NULL;
1758 1759
    cJSON_Delete(c);
}
M
Max Bruckner 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768
void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    if (which < 0)
    {
        return;
    }

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

1770 1771
void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
1772
    size_t i = 0;
1773
    cJSON *c = object->child;
1774
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1775 1776 1777 1778 1779 1780
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1781 1782 1783 1784 1785 1786
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
             cJSON_free(newitem->string);
        }

1787
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
1788
        ReplaceItemInArray(object, i, newitem);
1789 1790
    }
}
K
Kevin Branigan 已提交
1791 1792

/* Create basic types: */
M
Max Bruckner 已提交
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
cJSON *cJSON_CreateNull(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

M
Max Bruckner 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
cJSON *cJSON_CreateTrue(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

M
Max Bruckner 已提交
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
cJSON *cJSON_CreateFalse(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1826
cJSON *cJSON_CreateBool(cjbool b)
M
Max Bruckner 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1837 1838 1839 1840 1841 1842 1843
cJSON *cJSON_CreateNumber(double num)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857

        /* 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 已提交
1858 1859 1860 1861 1862
    }

    return item;
}

M
Max Bruckner 已提交
1863 1864 1865 1866 1867 1868
cJSON *cJSON_CreateString(const char *string)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_String;
1869
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
1870 1871 1872
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1873
            return NULL;
M
Max Bruckner 已提交
1874 1875 1876 1877 1878 1879
        }
    }

    return item;
}

J
Jiri Zouhar 已提交
1880 1881
extern cJSON *cJSON_CreateRaw(const char *raw)
{
M
Max Bruckner 已提交
1882 1883 1884 1885
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Raw;
1886
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw);
M
Max Bruckner 已提交
1887 1888 1889 1890 1891 1892 1893 1894
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
1895 1896
}

M
Max Bruckner 已提交
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
cJSON *cJSON_CreateArray(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

M
Max Bruckner 已提交
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
cJSON *cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item();
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
1918 1919

/* Create Arrays: */
M
Max Bruckner 已提交
1920 1921
cJSON *cJSON_CreateIntArray(const int *numbers, int count)
{
1922
    size_t i = 0;
1923 1924
    cJSON *n = NULL;
    cJSON *p = NULL;
1925 1926 1927 1928 1929 1930 1931 1932 1933
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1934 1935 1936 1937 1938
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
1939
            return NULL;
M
Max Bruckner 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

M
Max Bruckner 已提交
1955 1956
cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
{
1957
    size_t i = 0;
1958 1959
    cJSON *n = NULL;
    cJSON *p = NULL;
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}

1991 1992
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
1993
    size_t i = 0;
1994 1995
    cJSON *n = NULL;
    cJSON *p = NULL;
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}

2027 2028
cJSON *cJSON_CreateStringArray(const char **strings, int count)
{
2029
    size_t i = 0;
2030 2031
    cJSON *n = NULL;
    cJSON *p = NULL;
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}
2062 2063

/* Duplication */
M
Max Bruckner 已提交
2064
cJSON *cJSON_Duplicate(const cJSON *item, cjbool recurse)
2065
{
M
Max Bruckner 已提交
2066
    cJSON *newitem = NULL;
2067 2068
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2069
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2070 2071 2072 2073

    /* Bail on bad ptr */
    if (!item)
    {
2074
        goto fail;
M
Max Bruckner 已提交
2075 2076 2077 2078 2079
    }
    /* Create new item */
    newitem = cJSON_New_Item();
    if (!newitem)
    {
2080
        goto fail;
M
Max Bruckner 已提交
2081 2082 2083 2084 2085 2086 2087
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2088
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring);
M
Max Bruckner 已提交
2089 2090
        if (!newitem->valuestring)
        {
2091
            goto fail;
M
Max Bruckner 已提交
2092 2093 2094 2095
        }
    }
    if (item->string)
    {
2096
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string);
M
Max Bruckner 已提交
2097 2098
        if (!newitem->string)
        {
2099
            goto fail;
M
Max Bruckner 已提交
2100 2101 2102 2103 2104 2105 2106 2107
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2108 2109
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2110
    {
2111
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2112 2113
        if (!newchild)
        {
2114
            goto fail;
M
Max Bruckner 已提交
2115
        }
2116
        if (next != NULL)
M
Max Bruckner 已提交
2117 2118
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2119 2120 2121
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2122 2123 2124 2125
        }
        else
        {
            /* Set newitem->child and move to it */
2126 2127
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2128
        }
2129
        child = child->next;
M
Max Bruckner 已提交
2130 2131 2132
    }

    return newitem;
2133 2134 2135 2136 2137 2138 2139 2140

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

    return NULL;
2141
}
2142 2143 2144

void cJSON_Minify(char *json)
{
2145
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
    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 已提交
2185
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2186 2187 2188 2189
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2190
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2191
                }
M
Max Bruckner 已提交
2192
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2193
            }
M
Max Bruckner 已提交
2194
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2195 2196 2197 2198
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2199
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2200 2201 2202 2203 2204
        }
    }

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