cJSON.c 53.5 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 48 49 50 51
/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 2) || (CJSON_VERSION_PATCH != 1)
    #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 84
}

static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;

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

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

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

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

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

M
Max Bruckner 已提交
115 116
    cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
    cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
K
Kevin Branigan 已提交
117 118 119
}

/* Internal constructor. */
D
Dave Gamble 已提交
120
static cJSON *cJSON_New_Item(void)
K
Kevin Branigan 已提交
121
{
M
Max Bruckner 已提交
122 123 124
    cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
    if (node)
    {
125
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
126 127 128
    }

    return node;
K
Kevin Branigan 已提交
129 130 131 132 133
}

/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
M
Max Bruckner 已提交
134
    cJSON *next = NULL;
M
Max Bruckner 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    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 已提交
153 154 155
}

/* Parse the input text to generate a number, and populate the result into item. */
156
static const unsigned char *parse_number(cJSON *item, const unsigned char *num)
K
Kevin Branigan 已提交
157
{
158 159
    double number = 0;
    unsigned char *endpointer = NULL;
M
Max Bruckner 已提交
160

161 162 163 164 165
    if (num == NULL)
    {
        return NULL;
    }

166 167
    number = strtod((const char*)num, (char**)&endpointer);
    if ((num == endpointer) || (num == NULL))
M
Max Bruckner 已提交
168
    {
169 170
        /* parse_error */
        return NULL;
M
Max Bruckner 已提交
171 172
    }

173
    item->valuedouble = number;
M
Max Bruckner 已提交
174

175
    /* use saturation in case of overflow */
176
    if (number >= INT_MAX)
177 178 179
    {
        item->valueint = INT_MAX;
    }
180
    else if (number <= INT_MIN)
181 182 183 184 185
    {
        item->valueint = INT_MIN;
    }
    else
    {
186
        item->valueint = (int)number;
187
    }
M
Max Bruckner 已提交
188 189
    item->type = cJSON_Number;

190
    return endpointer;
K
Kevin Branigan 已提交
191 192
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
/* 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 已提交
212 213
typedef struct
{
214
    unsigned char *buffer;
215 216
    size_t length;
    size_t offset;
217
    cjbool noalloc;
M
Max Bruckner 已提交
218
} printbuffer;
219

M
Max Bruckner 已提交
220
/* realloc printbuffer if necessary to have at least "needed" bytes more */
221
static unsigned char* ensure(printbuffer *p, size_t needed)
222
{
223
    unsigned char *newbuffer = NULL;
224 225 226 227 228 229 230 231
    size_t newsize = 0;

    if (needed > INT_MAX)
    {
        /* sizes bigger than INT_MAX are currently not supported */
        return NULL;
    }

M
Max Bruckner 已提交
232 233
    if (!p || !p->buffer)
    {
234
        return NULL;
M
Max Bruckner 已提交
235 236 237 238 239 240 241
    }
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

242 243 244 245
    if (p->noalloc) {
        return NULL;
    }

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    /* 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;
        }
    }

261
    newbuffer = (unsigned char*)cJSON_malloc(newsize);
M
Max Bruckner 已提交
262 263 264 265
    if (!newbuffer)
    {
        cJSON_free(p->buffer);
        p->length = 0;
266
        p->buffer = NULL;
M
Max Bruckner 已提交
267

268
        return NULL;
M
Max Bruckner 已提交
269 270 271 272 273 274 275 276 277 278
    }
    if (newbuffer)
    {
        memcpy(newbuffer, p->buffer, p->length);
    }
    cJSON_free(p->buffer);
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
279 280
}

M
Max Bruckner 已提交
281
/* calculate the new length of the string in a printbuffer */
282
static size_t update(const printbuffer *p)
K
Kevin Branigan 已提交
283
{
M
Max Bruckner 已提交
284
    const unsigned char *str = NULL;
M
Max Bruckner 已提交
285 286 287 288 289 290
    if (!p || !p->buffer)
    {
        return 0;
    }
    str = p->buffer + p->offset;

M
Max Bruckner 已提交
291
    return p->offset + strlen((const char*)str);
292 293 294
}

/* Render the number nicely from the given item into a string. */
295
static unsigned char *print_number(const cJSON *item, printbuffer *p)
296
{
297
    unsigned char *str = NULL;
M
Max Bruckner 已提交
298 299 300 301 302 303 304 305 306 307
    double d = item->valuedouble;
    /* special case for 0. */
    if (d == 0)
    {
        if (p)
        {
            str = ensure(p, 2);
        }
        else
        {
308
            str = (unsigned char*)cJSON_malloc(2);
M
Max Bruckner 已提交
309 310 311
        }
        if (str)
        {
312
            strcpy((char*)str,"0");
M
Max Bruckner 已提交
313 314 315 316 317 318 319 320 321 322 323 324
        }
    }
    /* value is an int */
    else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
    {
        if (p)
        {
            str = ensure(p, 21);
        }
        else
        {
            /* 2^64+1 can be represented in 21 chars. */
325
            str = (unsigned char*)cJSON_malloc(21);
M
Max Bruckner 已提交
326 327 328
        }
        if (str)
        {
329
            sprintf((char*)str, "%d", item->valueint);
M
Max Bruckner 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342
        }
    }
    /* value is a floating point number */
    else
    {
        if (p)
        {
            /* This is a nice tradeoff. */
            str = ensure(p, 64);
        }
        else
        {
            /* This is a nice tradeoff. */
343
            str = (unsigned char*)cJSON_malloc(64);
M
Max Bruckner 已提交
344 345 346 347 348 349
        }
        if (str)
        {
            /* This checks for NaN and Infinity */
            if ((d * 0) != 0)
            {
350
                sprintf((char*)str, "null");
M
Max Bruckner 已提交
351
            }
352
            else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
M
Max Bruckner 已提交
353
            {
354
                sprintf((char*)str, "%.0f", d);
M
Max Bruckner 已提交
355 356 357
            }
            else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
            {
358
                sprintf((char*)str, "%e", d);
M
Max Bruckner 已提交
359 360 361
            }
            else
            {
362
                sprintf((char*)str, "%f", d);
M
Max Bruckner 已提交
363 364 365 366
            }
        }
    }
    return str;
K
Kevin Branigan 已提交
367 368
}

M
Max Bruckner 已提交
369
/* parse 4 digit hexadecimal number */
370
static unsigned parse_hex4(const unsigned char *str)
371
{
M
Max Bruckner 已提交
372
    unsigned int h = 0;
373
    size_t i = 0;
M
Max Bruckner 已提交
374

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

395 396 397 398 399 400
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
            str++;
        }
M
Max Bruckner 已提交
401 402 403
    }

    return h;
404 405
}

M
Max Bruckner 已提交
406
/* first bytes of UTF8 encoding for a given length in bytes */
407
static const unsigned char firstByteMark[5] =
M
Max Bruckner 已提交
408 409 410 411 412
{
    0x00, /* should never happen */
    0x00, /* 0xxxxxxx */
    0xC0, /* 110xxxxx */
    0xE0, /* 1110xxxx */
413
    0xF0 /* 11110xxx */
M
Max Bruckner 已提交
414 415
};

K
Kevin Branigan 已提交
416
/* Parse the input text into an unescaped cstring, and populate item. */
417
static const unsigned char *parse_string(cJSON *item, const unsigned char *str, const unsigned char **ep)
K
Kevin Branigan 已提交
418
{
419
    const unsigned char *ptr = str + 1;
M
Max Bruckner 已提交
420
    const unsigned char *end_ptr = str + 1;
421 422
    unsigned char *ptr2 = NULL;
    unsigned char *out = NULL;
423
    size_t len = 0;
M
Max Bruckner 已提交
424 425
    unsigned uc = 0;
    unsigned uc2 = 0;
M
Max Bruckner 已提交
426 427 428 429 430

    /* not a string! */
    if (*str != '\"')
    {
        *ep = str;
431
        goto fail;
M
Max Bruckner 已提交
432
    }
M
Max Bruckner 已提交
433

434
    while ((*end_ptr != '\"') && *end_ptr)
M
Max Bruckner 已提交
435 436 437 438 439 440
    {
        if (*end_ptr++ == '\\')
        {
            if (*end_ptr == '\0')
            {
                /* prevent buffer overflow when last input character is a backslash */
441
                goto fail;
M
Max Bruckner 已提交
442 443 444 445
            }
            /* Skip escaped quotes. */
            end_ptr++;
        }
446
        len++;
M
Max Bruckner 已提交
447
    }
M
Max Bruckner 已提交
448

M
Max Bruckner 已提交
449
    /* This is at most how long we need for the string, roughly. */
450
    out = (unsigned char*)cJSON_malloc(len + 1);
M
Max Bruckner 已提交
451 452
    if (!out)
    {
453
        goto fail;
M
Max Bruckner 已提交
454 455 456 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 484
    }

    ptr2 = out;
    /* loop through the string literal */
    while (ptr < end_ptr)
    {
        if (*ptr != '\\')
        {
            *ptr2++ = *ptr++;
        }
        /* escape sequence */
        else
        {
            ptr++;
            switch (*ptr)
            {
                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;
485 486 487 488 489
                case '\"':
                case '\\':
                case '/':
                    *ptr2++ = *ptr;
                    break;
M
Max Bruckner 已提交
490 491 492 493 494 495 496 497
                case 'u':
                    /* transcode utf16 to utf8. See RFC2781 and RFC3629. */
                    uc = parse_hex4(ptr + 1); /* get the unicode char. */
                    ptr += 4;
                    if (ptr >= end_ptr)
                    {
                        /* invalid */
                        *ep = str;
498
                        goto fail;
M
Max Bruckner 已提交
499 500 501 502 503
                    }
                    /* check for invalid. */
                    if (((uc >= 0xDC00) && (uc <= 0xDFFF)) || (uc == 0))
                    {
                        *ep = str;
504
                        goto fail;
M
Max Bruckner 已提交
505 506 507 508 509 510 511 512 513
                    }

                    /* UTF16 surrogate pairs. */
                    if ((uc >= 0xD800) && (uc<=0xDBFF))
                    {
                        if ((ptr + 6) > end_ptr)
                        {
                            /* invalid */
                            *ep = str;
514
                            goto fail;
M
Max Bruckner 已提交
515 516 517 518 519
                        }
                        if ((ptr[1] != '\\') || (ptr[2] != 'u'))
                        {
                            /* missing second-half of surrogate. */
                            *ep = str;
520
                            goto fail;
M
Max Bruckner 已提交
521 522 523 524 525 526 527
                        }
                        uc2 = parse_hex4(ptr + 3);
                        ptr += 6; /* \uXXXX */
                        if ((uc2 < 0xDC00) || (uc2 > 0xDFFF))
                        {
                            /* invalid second-half of surrogate. */
                            *ep = str;
528
                            goto fail;
M
Max Bruckner 已提交
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 554 555 556 557
                        }
                        /* calculate unicode codepoint from the surrogate pair */
                        uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF));
                    }

                    /* encode as UTF8
                     * takes at maximum 4 bytes to encode:
                     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
                    len = 4;
                    if (uc < 0x80)
                    {
                        /* normal ascii, encoding 0xxxxxxx */
                        len = 1;
                    }
                    else if (uc < 0x800)
                    {
                        /* two bytes, encoding 110xxxxx 10xxxxxx */
                        len = 2;
                    }
                    else if (uc < 0x10000)
                    {
                        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
                        len = 3;
                    }
                    ptr2 += len;

                    switch (len) {
                        case 4:
                            /* 10xxxxxx */
M
Max Bruckner 已提交
558
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
559 560 561
                            uc >>= 6;
                        case 3:
                            /* 10xxxxxx */
M
Max Bruckner 已提交
562
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
563 564 565
                            uc >>= 6;
                        case 2:
                            /* 10xxxxxx */
M
Max Bruckner 已提交
566
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
567 568 569 570
                            uc >>= 6;
                        case 1:
                            /* depending on the length in bytes this determines the
                             * encoding ofthe first UTF8 byte */
M
Max Bruckner 已提交
571
                            *--ptr2 = (unsigned char)((uc | firstByteMark[len]) & 0xFF);
M
Max Bruckner 已提交
572
                            break;
573 574
                        default:
                            *ep = str;
575
                            goto fail;
M
Max Bruckner 已提交
576 577 578 579
                    }
                    ptr2 += len;
                    break;
                default:
580
                    *ep = str;
581
                    goto fail;
M
Max Bruckner 已提交
582 583 584 585 586 587 588 589 590 591
            }
            ptr++;
        }
    }
    *ptr2 = '\0';
    if (*ptr == '\"')
    {
        ptr++;
    }

592
    item->type = cJSON_String;
593 594
    item->valuestring = (char*)out;

M
Max Bruckner 已提交
595
    return ptr;
596 597 598 599 600 601 602 603

fail:
    if (out != NULL)
    {
        cJSON_free(out);
    }

    return NULL;
K
Kevin Branigan 已提交
604 605 606
}

/* Render the cstring provided to an escaped version that can be printed. */
607
static unsigned char *print_string_ptr(const unsigned char *str, printbuffer *p)
K
Kevin Branigan 已提交
608
{
609 610 611
    const unsigned char *ptr = NULL;
    unsigned char *ptr2 = NULL;
    unsigned char *out = NULL;
612
    size_t len = 0;
M
Max Bruckner 已提交
613
    cjbool flag = false;
M
Max Bruckner 已提交
614
    unsigned char token = '\0';
M
Max Bruckner 已提交
615 616 617 618 619 620 621 622 623 624

    /* empty string */
    if (!str)
    {
        if (p)
        {
            out = ensure(p, 3);
        }
        else
        {
625
            out = (unsigned char*)cJSON_malloc(3);
M
Max Bruckner 已提交
626 627 628
        }
        if (!out)
        {
629
            return NULL;
M
Max Bruckner 已提交
630
        }
631
        strcpy((char*)out, "\"\"");
M
Max Bruckner 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

        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 已提交
648
        len = (size_t)(ptr - str);
M
Max Bruckner 已提交
649 650 651 652 653 654
        if (p)
        {
            out = ensure(p, len + 3);
        }
        else
        {
655
            out = (unsigned char*)cJSON_malloc(len + 3);
M
Max Bruckner 已提交
656 657 658
        }
        if (!out)
        {
659
            return NULL;
M
Max Bruckner 已提交
660 661 662 663
        }

        ptr2 = out;
        *ptr2++ = '\"';
664
        strcpy((char*)ptr2, (const char*)str);
M
Max Bruckner 已提交
665 666 667 668 669 670 671 672
        ptr2[len] = '\"';
        ptr2[len + 1] = '\0';

        return out;
    }

    ptr = str;
    /* calculate additional space that is needed for escaping */
S
Stephan 已提交
673
    while ((token = *ptr))
M
Max Bruckner 已提交
674
    {
S
Stephan 已提交
675
        ++len;
M
Max Bruckner 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        if (strchr("\"\\\b\f\n\r\t", token))
        {
            len++; /* +1 for the backslash */
        }
        else if (token < 32)
        {
            len += 5; /* +5 for \uXXXX */
        }
        ptr++;
    }

    if (p)
    {
        out = ensure(p, len + 3);
    }
    else
    {
693
        out = (unsigned char*)cJSON_malloc(len + 3);
M
Max Bruckner 已提交
694 695 696
    }
    if (!out)
    {
697
        return NULL;
M
Max Bruckner 已提交
698 699 700 701 702 703 704 705
    }

    ptr2 = out;
    ptr = str;
    *ptr2++ = '\"';
    /* copy the string */
    while (*ptr)
    {
706
        if ((*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
M
Max Bruckner 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
        {
            /* 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 */
740
                    sprintf((char*)ptr2, "u%04x", token);
M
Max Bruckner 已提交
741 742 743 744 745 746 747 748 749
                    ptr2 += 5;
                    break;
            }
        }
    }
    *ptr2++ = '\"';
    *ptr2++ = '\0';

    return out;
K
Kevin Branigan 已提交
750
}
M
Max Bruckner 已提交
751

M
Max Bruckner 已提交
752
/* Invoke print_string_ptr (which is useful) on an item. */
753
static unsigned char *print_string(const cJSON *item, printbuffer *p)
M
Max Bruckner 已提交
754
{
755
    return print_string_ptr((unsigned char*)item->valuestring, p);
M
Max Bruckner 已提交
756
}
K
Kevin Branigan 已提交
757 758

/* Predeclare these prototypes. */
759
static const unsigned char *parse_value(cJSON *item, const unsigned char *value, const unsigned char **ep);
760
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
761
static const unsigned char *parse_array(cJSON *item, const unsigned char *value, const unsigned char **ep);
762
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
763
static const unsigned char *parse_object(cJSON *item, const unsigned char *value, const unsigned char **ep);
764
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
K
Kevin Branigan 已提交
765 766

/* Utility to jump whitespace and cr/lf */
767
static const unsigned char *skip(const unsigned char *in)
M
Max Bruckner 已提交
768
{
769
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
770 771 772 773 774 775
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
776 777

/* Parse an object - create a new root, and populate. */
M
Max Bruckner 已提交
778
cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cjbool require_null_terminated)
K
Kevin Branigan 已提交
779
{
780
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
781
    /* use global error pointer if no specific one was given */
782
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
M
Max Bruckner 已提交
783
    cJSON *c = cJSON_New_Item();
784
    *ep = NULL;
M
Max Bruckner 已提交
785 786
    if (!c) /* memory fail */
    {
787
        return NULL;
M
Max Bruckner 已提交
788 789
    }

790
    end = parse_value(c, skip((const unsigned char*)value), ep);
M
Max Bruckner 已提交
791 792 793 794
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
795
        return NULL;
M
Max Bruckner 已提交
796 797 798 799 800 801 802 803 804 805
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
        end = skip(end);
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
806
            return NULL;
M
Max Bruckner 已提交
807 808 809 810
        }
    }
    if (return_parse_end)
    {
811
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
812 813 814
    }

    return c;
K
Kevin Branigan 已提交
815
}
M
Max Bruckner 已提交
816

817
/* Default options for cJSON_Parse */
M
Max Bruckner 已提交
818 819 820 821
cJSON *cJSON_Parse(const char *value)
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
822 823

/* Render a cJSON item/entity/structure to text. */
824
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
825
{
826
    return (char*)print_value(item, 0, 1, 0);
M
Max Bruckner 已提交
827 828
}

829
char *cJSON_PrintUnformatted(const cJSON *item)
830
{
831
    return (char*)print_value(item, 0, 0, 0);
832
}
833

M
Max Bruckner 已提交
834
char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, cjbool fmt)
835
{
M
Max Bruckner 已提交
836
    printbuffer p;
M
Max Bruckner 已提交
837 838 839

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
840
        return NULL;
M
Max Bruckner 已提交
841 842 843
    }

    p.buffer = (unsigned char*)cJSON_malloc((size_t)prebuffer);
844 845
    if (!p.buffer)
    {
846
        return NULL;
847
    }
M
Max Bruckner 已提交
848 849

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
850
    p.offset = 0;
851
    p.noalloc = false;
M
Max Bruckner 已提交
852

853
    return (char*)print_value(item, 0, fmt, &p);
854 855
}

856
int cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cjbool fmt)
857 858
{
    printbuffer p;
M
Max Bruckner 已提交
859 860 861 862 863 864

    if (len < 0)
    {
        return false;
    }

865
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
866
    p.length = (size_t)len;
867
    p.offset = 0;
868
    p.noalloc = true;
M
Max Bruckner 已提交
869
    return print_value(item, 0, fmt, &p) != NULL;
870
}
K
Kevin Branigan 已提交
871 872

/* Parser core - when encountering text, process appropriately. */
873
static const unsigned  char *parse_value(cJSON *item, const unsigned char *value, const unsigned char **ep)
K
Kevin Branigan 已提交
874
{
M
Max Bruckner 已提交
875 876 877
    if (!value)
    {
        /* Fail on null. */
878
        return NULL;
M
Max Bruckner 已提交
879 880 881
    }

    /* parse the different types of values */
882
    if (!strncmp((const char*)value, "null", 4))
M
Max Bruckner 已提交
883 884 885 886
    {
        item->type = cJSON_NULL;
        return value + 4;
    }
887
    if (!strncmp((const char*)value, "false", 5))
M
Max Bruckner 已提交
888 889 890 891
    {
        item->type = cJSON_False;
        return value + 5;
    }
892
    if (!strncmp((const char*)value, "true", 4))
M
Max Bruckner 已提交
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    {
        item->type = cJSON_True;
        item->valueint = 1;
        return value + 4;
    }
    if (*value == '\"')
    {
        return parse_string(item, value, ep);
    }
    if ((*value == '-') || ((*value >= '0') && (*value <= '9')))
    {
        return parse_number(item, value);
    }
    if (*value == '[')
    {
        return parse_array(item, value, ep);
    }
    if (*value == '{')
    {
        return parse_object(item, value, ep);
    }

M
Max Bruckner 已提交
915 916
    /* failure. */
    *ep = value;
917
    return NULL;
K
Kevin Branigan 已提交
918 919 920
}

/* Render a value to text. */
921
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
922
{
923
    unsigned char *out = NULL;
M
Max Bruckner 已提交
924 925 926

    if (!item)
    {
927
        return NULL;
M
Max Bruckner 已提交
928 929 930
    }
    if (p)
    {
931
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
932 933 934 935 936
        {
            case cJSON_NULL:
                out = ensure(p, 5);
                if (out)
                {
937
                    strcpy((char*)out, "null");
M
Max Bruckner 已提交
938 939 940 941 942 943
                }
                break;
            case cJSON_False:
                out = ensure(p, 6);
                if (out)
                {
944
                    strcpy((char*)out, "false");
M
Max Bruckner 已提交
945 946 947 948 949 950
                }
                break;
            case cJSON_True:
                out = ensure(p, 5);
                if (out)
                {
951
                    strcpy((char*)out, "true");
M
Max Bruckner 已提交
952 953 954 955 956
                }
                break;
            case cJSON_Number:
                out = print_number(item, p);
                break;
J
Jiri Zouhar 已提交
957
            case cJSON_Raw:
958 959 960 961 962 963 964 965 966 967 968 969 970 971
            {
                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);
J
Jiri Zouhar 已提交
972 973
                if (out)
                {
974
                    memcpy(out, item->valuestring, raw_length);
J
Jiri Zouhar 已提交
975 976
                }
                break;
977
            }
M
Max Bruckner 已提交
978 979 980 981 982 983 984 985 986
            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;
987 988 989
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
990 991 992 993
        }
    }
    else
    {
994
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
995 996
        {
            case cJSON_NULL:
997
                out = cJSON_strdup((const unsigned char*)"null");
M
Max Bruckner 已提交
998 999
                break;
            case cJSON_False:
1000
                out = cJSON_strdup((const unsigned char*)"false");
M
Max Bruckner 已提交
1001 1002
                break;
            case cJSON_True:
1003
                out = cJSON_strdup((const unsigned char*)"true");
M
Max Bruckner 已提交
1004 1005 1006 1007
                break;
            case cJSON_Number:
                out = print_number(item, 0);
                break;
J
Jiri Zouhar 已提交
1008
            case cJSON_Raw:
1009
                out = cJSON_strdup((unsigned char*)item->valuestring);
J
Jiri Zouhar 已提交
1010
                break;
M
Max Bruckner 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019
            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;
1020 1021 1022
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
1023 1024 1025 1026
        }
    }

    return out;
K
Kevin Branigan 已提交
1027 1028 1029
}

/* Build an array from input text. */
1030
static const unsigned char *parse_array(cJSON *item, const unsigned char *value, const unsigned char **error_pointer)
K
Kevin Branigan 已提交
1031
{
1032
    cJSON *head = NULL; /* head of the linked list */
1033 1034
    cJSON *current_item = NULL;

M
Max Bruckner 已提交
1035 1036
    if (*value != '[')
    {
1037 1038
        /* not an array */
        *error_pointer = value;
1039
        goto fail;
M
Max Bruckner 已提交
1040
    }
K
Kevin Branigan 已提交
1041

1042
    value = skip(value + 1); /* skip whitespace */
M
Max Bruckner 已提交
1043 1044
    if (*value == ']')
    {
1045
        /* empty array */
1046
        goto success;
M
Max Bruckner 已提交
1047
    }
K
Kevin Branigan 已提交
1048

1049 1050
    /* step back to character in front of the first element */
    value--;
M
Max Bruckner 已提交
1051
    /* loop through the comma separated array elements */
1052
    do
M
Max Bruckner 已提交
1053
    {
1054 1055 1056
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item();
        if (new_item == NULL)
M
Max Bruckner 已提交
1057
        {
1058
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1059
        }
1060 1061 1062

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1063
        {
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
            /* 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 */
        value = skip(value + 1); /* skip whitespace before value */
        value = parse_value(current_item, value, error_pointer);
        value = skip(value); /* skip whitespace after value */
        if (value == NULL)
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1082 1083
        }
    }
1084
    while (*value == ',');
M
Max Bruckner 已提交
1085 1086 1087

    if (*value == ']')
    {
1088
        goto success; /* end of array */
M
Max Bruckner 已提交
1089 1090
    }

1091 1092
    /* malformed array */
    *error_pointer = value;
1093 1094 1095 1096
    goto fail;

success:
    item->type = cJSON_Array;
1097
    item->child = head;
1098 1099

    return value + 1;
K
Kevin Branigan 已提交
1100

1101
fail:
1102
    if (head != NULL)
1103
    {
1104
        cJSON_Delete(head);
1105 1106
    }

1107
    return NULL;
K
Kevin Branigan 已提交
1108 1109 1110
}

/* Render an array to text */
1111
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1112
{
1113 1114 1115 1116
    unsigned char **entries;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
1117
    size_t len = 5;
M
Max Bruckner 已提交
1118
    cJSON *child = item->child;
1119 1120
    size_t numentries = 0;
    size_t i = 0;
M
Max Bruckner 已提交
1121
    cjbool fail = false;
M
Max Bruckner 已提交
1122
    size_t tmplen = 0;
K
Kevin Branigan 已提交
1123

M
Max Bruckner 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    /* How many entries in the array? */
    while (child)
    {
        numentries++;
        child = child->next;
    }

    /* Explicitly handle numentries == 0 */
    if (!numentries)
    {
        if (p)
        {
            out = ensure(p, 3);
        }
        else
        {
1140
            out = (unsigned char*)cJSON_malloc(3);
M
Max Bruckner 已提交
1141 1142 1143
        }
        if (out)
        {
1144
            strcpy((char*)out, "[]");
M
Max Bruckner 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        }

        return out;
    }

    if (p)
    {
        /* Compose the output array. */
        /* opening square bracket */
        i = p->offset;
        ptr = ensure(p, 1);
        if (!ptr)
        {
1158
            return NULL;
M
Max Bruckner 已提交
1159 1160 1161 1162 1163 1164 1165
        }
        *ptr = '[';
        p->offset++;

        child = item->child;
        while (child && !fail)
        {
K
Kyle Chisholm 已提交
1166
            if (!print_value(child, depth + 1, fmt, p))
1167 1168 1169
            {
                return NULL;
            }
M
Max Bruckner 已提交
1170 1171 1172 1173 1174 1175 1176
            p->offset = update(p);
            if (child->next)
            {
                len = fmt ? 2 : 1;
                ptr = ensure(p, len + 1);
                if (!ptr)
                {
1177
                    return NULL;
M
Max Bruckner 已提交
1178 1179 1180 1181 1182 1183
                }
                *ptr++ = ',';
                if(fmt)
                {
                    *ptr++ = ' ';
                }
1184
                *ptr = '\0';
M
Max Bruckner 已提交
1185 1186 1187 1188 1189 1190 1191
                p->offset += len;
            }
            child = child->next;
        }
        ptr = ensure(p, 2);
        if (!ptr)
        {
1192
            return NULL;
M
Max Bruckner 已提交
1193 1194 1195 1196 1197 1198 1199 1200
        }
        *ptr++ = ']';
        *ptr = '\0';
        out = (p->buffer) + i;
    }
    else
    {
        /* Allocate an array to hold the pointers to all printed values */
1201
        entries = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1202 1203
        if (!entries)
        {
1204
            return NULL;
M
Max Bruckner 已提交
1205
        }
1206
        memset(entries, '\0', numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215

        /* Retrieve all the results: */
        child = item->child;
        while (child && !fail)
        {
            ret = print_value(child, depth + 1, fmt, 0);
            entries[i++] = ret;
            if (ret)
            {
1216
                len += strlen((char*)ret) + 2 + (fmt ? 1 : 0);
M
Max Bruckner 已提交
1217 1218 1219
            }
            else
            {
M
Max Bruckner 已提交
1220
                fail = true;
M
Max Bruckner 已提交
1221 1222 1223 1224 1225 1226 1227
            }
            child = child->next;
        }

        /* If we didn't fail, try to malloc the output string */
        if (!fail)
        {
1228
            out = (unsigned char*)cJSON_malloc(len);
M
Max Bruckner 已提交
1229 1230 1231 1232
        }
        /* If that fails, we fail. */
        if (!out)
        {
M
Max Bruckner 已提交
1233
            fail = true;
M
Max Bruckner 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
        }

        /* 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);
1248
            return NULL;
M
Max Bruckner 已提交
1249 1250 1251 1252 1253 1254 1255 1256
        }

        /* Compose the output array. */
        *out='[';
        ptr = out + 1;
        *ptr = '\0';
        for (i = 0; i < numentries; i++)
        {
1257
            tmplen = strlen((char*)entries[i]);
M
Max Bruckner 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266
            memcpy(ptr, entries[i], tmplen);
            ptr += tmplen;
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
                if(fmt)
                {
                    *ptr++ = ' ';
                }
1267
                *ptr = '\0';
M
Max Bruckner 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276
            }
            cJSON_free(entries[i]);
        }
        cJSON_free(entries);
        *ptr++ = ']';
        *ptr++ = '\0';
    }

    return out;
K
Kevin Branigan 已提交
1277 1278 1279
}

/* Build an object from the text. */
1280
static const unsigned char *parse_object(cJSON *item, const unsigned char *value, const unsigned char **ep)
K
Kevin Branigan 已提交
1281
{
1282
    cJSON *head = NULL; /* linked list head */
M
Max Bruckner 已提交
1283
    cJSON *child = NULL;
M
Max Bruckner 已提交
1284 1285 1286 1287
    if (*value != '{')
    {
        /* not an object! */
        *ep = value;
1288
        goto fail;
M
Max Bruckner 已提交
1289 1290 1291 1292 1293 1294
    }

    value = skip(value + 1);
    if (*value == '}')
    {
        /* empty object. */
1295
        goto success;
M
Max Bruckner 已提交
1296 1297
    }

1298 1299
    head = child = cJSON_New_Item();
    if (!child)
M
Max Bruckner 已提交
1300
    {
1301
        goto fail;
M
Max Bruckner 已提交
1302 1303 1304 1305 1306
    }
    /* parse first key */
    value = skip(parse_string(child, skip(value), ep));
    if (!value)
    {
1307
        goto fail;
M
Max Bruckner 已提交
1308 1309 1310
    }
    /* use string as key, not value */
    child->string = child->valuestring;
1311
    child->valuestring = NULL;
M
Max Bruckner 已提交
1312 1313 1314 1315 1316

    if (*value != ':')
    {
        /* invalid object. */
        *ep = value;
1317
        goto fail;
M
Max Bruckner 已提交
1318 1319 1320 1321 1322
    }
    /* skip any spacing, get the value. */
    value = skip(parse_value(child, skip(value + 1), ep));
    if (!value)
    {
1323
        goto fail;
M
Max Bruckner 已提交
1324 1325 1326 1327
    }

    while (*value == ',')
    {
M
Max Bruckner 已提交
1328
        cJSON *new_item = NULL;
M
Max Bruckner 已提交
1329 1330 1331
        if (!(new_item = cJSON_New_Item()))
        {
            /* memory fail */
1332
            goto fail;
M
Max Bruckner 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341
        }
        /* add to linked list */
        child->next = new_item;
        new_item->prev = child;

        child = new_item;
        value = skip(parse_string(child, skip(value + 1), ep));
        if (!value)
        {
1342
            goto fail;
M
Max Bruckner 已提交
1343 1344 1345 1346
        }

        /* use string as key, not value */
        child->string = child->valuestring;
1347
        child->valuestring = NULL;
M
Max Bruckner 已提交
1348 1349 1350 1351 1352

        if (*value != ':')
        {
            /* invalid object. */
            *ep = value;
1353
            goto fail;
M
Max Bruckner 已提交
1354 1355 1356 1357 1358
        }
        /* skip any spacing, get the value. */
        value = skip(parse_value(child, skip(value + 1), ep));
        if (!value)
        {
1359
            goto fail;
M
Max Bruckner 已提交
1360 1361 1362 1363 1364
        }
    }
    /* end of object */
    if (*value == '}')
    {
1365
        goto success;
M
Max Bruckner 已提交
1366 1367 1368 1369
    }

    /* malformed */
    *ep = value;
1370 1371 1372 1373
    goto fail;

success:
    item->type = cJSON_Object;
1374
    item->child = head;
1375 1376

    return value + 1;
1377 1378

fail:
1379
    if (child != NULL)
1380 1381 1382 1383
    {
        cJSON_Delete(child);
    }

1384
    return NULL;
K
Kevin Branigan 已提交
1385 1386 1387
}

/* Render an object to text. */
1388
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
1389 1390 1391 1392 1393 1394 1395
{
    unsigned char **entries = NULL;
    unsigned char **names = NULL;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
    unsigned char *str = NULL;
1396 1397 1398
    size_t len = 7;
    size_t i = 0;
    size_t j = 0;
M
Max Bruckner 已提交
1399
    cJSON *child = item->child;
1400
    size_t numentries = 0;
M
Max Bruckner 已提交
1401
    cjbool fail = false;
M
Max Bruckner 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    size_t tmplen = 0;

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

    /* Explicitly handle empty object case */
    if (!numentries)
    {
        if (p)
        {
            out = ensure(p, fmt ? depth + 4 : 3);
        }
        else
        {
1420
            out = (unsigned char*)cJSON_malloc(fmt ? depth + 4 : 3);
M
Max Bruckner 已提交
1421 1422 1423
        }
        if (!out)
        {
1424
            return NULL;
M
Max Bruckner 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
        }
        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);
        if (!ptr)
        {
1449
            return NULL;
M
Max Bruckner 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
        }

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

        child = item->child;
        depth++;
        while (child)
        {
            if (fmt)
            {
                ptr = ensure(p, depth);
                if (!ptr)
                {
1469
                    return NULL;
M
Max Bruckner 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478
                }
                for (j = 0; j < depth; j++)
                {
                    *ptr++ = '\t';
                }
                p->offset += depth;
            }

            /* print key */
1479
            if (!print_string_ptr((unsigned char*)child->string, p))
1480 1481 1482
            {
                return NULL;
            }
M
Max Bruckner 已提交
1483 1484 1485 1486 1487 1488
            p->offset = update(p);

            len = fmt ? 2 : 1;
            ptr = ensure(p, len);
            if (!ptr)
            {
1489
                return NULL;
M
Max Bruckner 已提交
1490 1491 1492 1493 1494 1495 1496 1497 1498
            }
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
            p->offset+=len;

            /* print value */
K
Kyle Chisholm 已提交
1499 1500 1501 1502
            if (!print_value(child, depth, fmt, p))
            {
                return NULL;
            };
M
Max Bruckner 已提交
1503 1504 1505
            p->offset = update(p);

            /* print comma if not last */
M
Max Bruckner 已提交
1506
            len = (size_t) (fmt ? 1 : 0) + (child->next ? 1 : 0);
M
Max Bruckner 已提交
1507 1508 1509
            ptr = ensure(p, len + 1);
            if (!ptr)
            {
1510
                return NULL;
M
Max Bruckner 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
            }
            if (child->next)
            {
                *ptr++ = ',';
            }

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

            child = child->next;
        }

        ptr = ensure(p, fmt ? (depth + 1) : 2);
        if (!ptr)
        {
1530
            return NULL;
M
Max Bruckner 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
        }
        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 */
1546
        entries = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1547 1548
        if (!entries)
        {
1549
            return NULL;
M
Max Bruckner 已提交
1550
        }
1551
        names = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1552 1553 1554
        if (!names)
        {
            cJSON_free(entries);
1555
            return NULL;
M
Max Bruckner 已提交
1556
        }
1557 1558
        memset(entries, '\0', sizeof(unsigned char*) * numentries);
        memset(names, '\0', sizeof(unsigned char*) * numentries);
M
Max Bruckner 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568

        /* Collect all the results into our arrays: */
        child = item->child;
        depth++;
        if (fmt)
        {
            len += depth;
        }
        while (child && !fail)
        {
1569
            names[i] = str = print_string_ptr((unsigned char*)child->string, 0); /* print key */
M
Max Bruckner 已提交
1570 1571 1572
            entries[i++] = ret = print_value(child, depth, fmt, 0);
            if (str && ret)
            {
1573
                len += strlen((char*)ret) + strlen((char*)str) + 2 + (fmt ? 2 + depth : 0);
M
Max Bruckner 已提交
1574 1575 1576
            }
            else
            {
M
Max Bruckner 已提交
1577
                fail = true;
M
Max Bruckner 已提交
1578 1579 1580 1581 1582 1583 1584
            }
            child = child->next;
        }

        /* Try to allocate the output string */
        if (!fail)
        {
1585
            out = (unsigned char*)cJSON_malloc(len);
M
Max Bruckner 已提交
1586 1587 1588
        }
        if (!out)
        {
M
Max Bruckner 已提交
1589
            fail = true;
M
Max Bruckner 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        }

        /* 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);
1609
            return NULL;
M
Max Bruckner 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618
        }

        /* Compose the output: */
        *out = '{';
        ptr = out + 1;
        if (fmt)
        {
            *ptr++ = '\n';
        }
1619
        *ptr = '\0';
M
Max Bruckner 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628
        for (i = 0; i < numentries; i++)
        {
            if (fmt)
            {
                for (j = 0; j < depth; j++)
                {
                    *ptr++='\t';
                }
            }
1629
            tmplen = strlen((char*)names[i]);
M
Max Bruckner 已提交
1630 1631 1632 1633 1634 1635 1636
            memcpy(ptr, names[i], tmplen);
            ptr += tmplen;
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
1637 1638
            strcpy((char*)ptr, (char*)entries[i]);
            ptr += strlen((char*)entries[i]);
M
Max Bruckner 已提交
1639 1640 1641 1642 1643 1644 1645 1646
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
            }
            if (fmt)
            {
                *ptr++ = '\n';
            }
1647
            *ptr = '\0';
M
Max Bruckner 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
            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 已提交
1666 1667 1668
}

/* Get Array size/item / object item. */
M
Max Bruckner 已提交
1669
int cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1670 1671
{
    cJSON *c = array->child;
1672
    size_t i = 0;
M
Max Bruckner 已提交
1673 1674 1675 1676 1677
    while(c)
    {
        i++;
        c = c->next;
    }
1678 1679 1680

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

M
Max Bruckner 已提交
1681
    return (int)i;
M
Max Bruckner 已提交
1682 1683
}

1684
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1685
{
1686
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1687 1688 1689 1690 1691 1692 1693 1694 1695
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1696
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1697
{
1698
    cJSON *c = object ? object->child : NULL;
1699
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1700 1701 1702 1703 1704 1705
    {
        c = c->next;
    }
    return c;
}

1706
cjbool cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1707 1708 1709
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1710 1711

/* Utility for array list handling. */
M
Max Bruckner 已提交
1712 1713 1714 1715 1716 1717
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

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

/* Add item to array/object. */
1734
void cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1735
{
1736 1737 1738
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1739 1740 1741
    {
        return;
    }
1742 1743 1744 1745

    child = array->child;

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

M
Max Bruckner 已提交
1761 1762
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
1763 1764 1765 1766
    /* 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 已提交
1767 1768
}

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
/* 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);
    }
1780 1781
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1782
    item->string = (char*)string;
1783
#pragma GCC diagnostic pop
1784 1785 1786 1787
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1788 1789 1790 1791 1792
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    cJSON_AddItemToArray(array, create_reference(item));
}

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

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

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

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

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

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

1858
    return NULL;
1859 1860
}

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

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

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

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

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

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

    return item;
}

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

    return item;
}

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

    return item;
}

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

    return item;
}

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

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

    return item;
}

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

    return item;
}

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

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

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

    return item;
}

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

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

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

    if (count < 0)
    {
        return NULL;
    }

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

    return a;
}

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

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}

2153 2154
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
2155
    size_t i = 0;
2156 2157
    cJSON *n = NULL;
    cJSON *p = NULL;
2158 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++)
2168 2169 2170 2171 2172
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2173
            return NULL;
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;
}

2189 2190
cJSON *cJSON_CreateStringArray(const char **strings, 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++)
2204 2205 2206 2207 2208
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2209
            return NULL;
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2224 2225

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

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

    return newitem;
2295 2296 2297 2298 2299 2300 2301 2302

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

    return NULL;
2303
}
2304 2305 2306

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

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