cJSON.c 54.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 36 37 38 39 40 41 42 43 44 45 46 47 48
/* Determine the number of bits that an integer has using the preprocessor */
#if INT_MAX == 32767
    /* 16 bits */
    #define INTEGER_SIZE 0x0010
#elif INT_MAX == 2147483647
    /* 32 bits */
    #define INTEGER_SIZE 0x0100
#elif INT_MAX == 9223372036854775807
    /* 64 bits */
    #define INTEGER_SIZE 0x1000
#else
    #error "Failed to determine the size of an integer"
#endif

M
Max Bruckner 已提交
49
/* define our own boolean type */
M
Max Bruckner 已提交
50 51 52
typedef int cjbool;
#define true ((cjbool)1)
#define false ((cjbool)0)
M
Max Bruckner 已提交
53

54
static const unsigned char *global_ep = NULL;
K
Kevin Branigan 已提交
55

M
Max Bruckner 已提交
56 57
const char *cJSON_GetErrorPtr(void)
{
58
    return (const char*) global_ep;
M
Max Bruckner 已提交
59
}
K
Kevin Branigan 已提交
60

61 62 63 64 65 66 67 68
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 已提交
69
/* case insensitive strcmp */
70
static int cJSON_strcasecmp(const unsigned char *s1, const unsigned char *s2)
K
Kevin Branigan 已提交
71
{
M
Max Bruckner 已提交
72 73 74 75 76 77 78 79
    if (!s1)
    {
        return (s1 == s2) ? 0 : 1; /* both NULL? */
    }
    if (!s2)
    {
        return 1;
    }
80
    for(; tolower(*s1) == tolower(*s2); ++s1, ++s2)
M
Max Bruckner 已提交
81
    {
82
        if (*s1 == '\0')
M
Max Bruckner 已提交
83 84 85 86 87
        {
            return 0;
        }
    }

88
    return tolower(*s1) - tolower(*s2);
K
Kevin Branigan 已提交
89 90 91 92 93
}

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

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

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

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

    return copy;
K
Kevin Branigan 已提交
112 113 114 115
}

void cJSON_InitHooks(cJSON_Hooks* hooks)
{
M
Max Bruckner 已提交
116 117 118
    if (!hooks)
    {
        /* Reset hooks */
K
Kevin Branigan 已提交
119 120 121 122 123
        cJSON_malloc = malloc;
        cJSON_free = free;
        return;
    }

M
Max Bruckner 已提交
124 125
    cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
    cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
K
Kevin Branigan 已提交
126 127 128
}

/* Internal constructor. */
D
Dave Gamble 已提交
129
static cJSON *cJSON_New_Item(void)
K
Kevin Branigan 已提交
130
{
M
Max Bruckner 已提交
131 132 133
    cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
    if (node)
    {
134
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
135 136 137
    }

    return node;
K
Kevin Branigan 已提交
138 139 140 141 142
}

/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
M
Max Bruckner 已提交
143
    cJSON *next = NULL;
M
Max Bruckner 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    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 已提交
162 163 164
}

/* Parse the input text to generate a number, and populate the result into item. */
165
static const unsigned char *parse_number(cJSON *item, const unsigned char *num)
K
Kevin Branigan 已提交
166
{
M
Max Bruckner 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    double n = 0;
    double sign = 1;
    double scale = 0;
    int subscale = 0;
    int signsubscale = 1;

    /* Has sign? */
    if (*num == '-')
    {
        sign = -1;
        num++;
    }
    /* is zero */
    if (*num == '0')
    {
        num++;
    }
    /* Number? */
    if ((*num >= '1') && (*num <= '9'))
    {
        do
        {
            n = (n * 10.0) + (*num++ - '0');
        }
        while ((*num >= '0') && (*num<='9'));
    }
    /* Fractional part? */
    if ((*num == '.') && (num[1] >= '0') && (num[1] <= '9'))
    {
        num++;
        do
        {
            n = (n  *10.0) + (*num++ - '0');
            scale--;
        } while ((*num >= '0') && (*num <= '9'));
    }
    /* Exponent? */
    if ((*num == 'e') || (*num == 'E'))
    {
        num++;
        /* With sign? */
        if (*num == '+')
        {
            num++;
        }
        else if (*num == '-')
        {
            signsubscale = -1;
            num++;
        }
        /* Number? */
        while ((*num>='0') && (*num<='9'))
        {
            subscale = (subscale * 10) + (*num++ - '0');
        }
    }

    /* number = +/- number.fraction * 10^+/- exponent */
    n = sign * n * pow(10.0, (scale + subscale * signsubscale));

    item->valuedouble = n;
228 229 230 231 232 233 234 235 236 237 238 239 240
    /* use saturation in case of overflow */
    if (n >= INT_MAX)
    {
        item->valueint = INT_MAX;
    }
    else if (n <= INT_MIN)
    {
        item->valueint = INT_MIN;
    }
    else
    {
        item->valueint = (int)n;
    }
M
Max Bruckner 已提交
241 242 243
    item->type = cJSON_Number;

    return num;
K
Kevin Branigan 已提交
244 245
}

M
Max Bruckner 已提交
246 247 248 249 250 251 252 253
/* calculate the next largest power of 2 */
static int pow2gt (int x)
{
    --x;

    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
M
Max Bruckner 已提交
254
#if INTEGER_SIZE & 0x1110 /* at least 16 bit */
M
Max Bruckner 已提交
255
    x |= x >> 8;
M
Max Bruckner 已提交
256 257
#endif
#if INTEGER_SIZE & 0x1100 /* at least 32 bit */
M
Max Bruckner 已提交
258
    x |= x >> 16;
M
Max Bruckner 已提交
259
#endif
260
#if INTEGER_SIZE & 0x1000 /* 64 bit */
M
Max Bruckner 已提交
261 262
    x |= x >> 32;
#endif
M
Max Bruckner 已提交
263 264 265

    return x + 1;
}
266

M
Max Bruckner 已提交
267 268
typedef struct
{
269
    unsigned char *buffer;
270 271
    size_t length;
    size_t offset;
272
    cjbool noalloc;
M
Max Bruckner 已提交
273
} printbuffer;
274

M
Max Bruckner 已提交
275
/* realloc printbuffer if necessary to have at least "needed" bytes more */
276
static unsigned char* ensure(printbuffer *p, size_t needed)
277
{
278
    unsigned char *newbuffer = NULL;
279 280 281 282 283 284 285 286
    size_t newsize = 0;

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

M
Max Bruckner 已提交
287 288
    if (!p || !p->buffer)
    {
289
        return NULL;
M
Max Bruckner 已提交
290 291 292 293 294 295 296
    }
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

297 298 299 300
    if (p->noalloc) {
        return NULL;
    }

M
Max Bruckner 已提交
301
    newsize = (size_t) pow2gt((int)needed);
302
    newbuffer = (unsigned char*)cJSON_malloc(newsize);
M
Max Bruckner 已提交
303 304 305 306
    if (!newbuffer)
    {
        cJSON_free(p->buffer);
        p->length = 0;
307
        p->buffer = NULL;
M
Max Bruckner 已提交
308

309
        return NULL;
M
Max Bruckner 已提交
310 311 312 313 314 315 316 317 318 319
    }
    if (newbuffer)
    {
        memcpy(newbuffer, p->buffer, p->length);
    }
    cJSON_free(p->buffer);
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
320 321
}

M
Max Bruckner 已提交
322
/* calculate the new length of the string in a printbuffer */
323
static size_t update(const printbuffer *p)
K
Kevin Branigan 已提交
324
{
M
Max Bruckner 已提交
325
    const unsigned char *str = NULL;
M
Max Bruckner 已提交
326 327 328 329 330 331
    if (!p || !p->buffer)
    {
        return 0;
    }
    str = p->buffer + p->offset;

M
Max Bruckner 已提交
332
    return p->offset + strlen((const char*)str);
333 334 335
}

/* Render the number nicely from the given item into a string. */
336
static unsigned char *print_number(const cJSON *item, printbuffer *p)
337
{
338
    unsigned char *str = NULL;
M
Max Bruckner 已提交
339 340 341 342 343 344 345 346 347 348
    double d = item->valuedouble;
    /* special case for 0. */
    if (d == 0)
    {
        if (p)
        {
            str = ensure(p, 2);
        }
        else
        {
349
            str = (unsigned char*)cJSON_malloc(2);
M
Max Bruckner 已提交
350 351 352
        }
        if (str)
        {
353
            strcpy((char*)str,"0");
M
Max Bruckner 已提交
354 355 356 357 358 359 360 361 362 363 364 365
        }
    }
    /* 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. */
366
            str = (unsigned char*)cJSON_malloc(21);
M
Max Bruckner 已提交
367 368 369
        }
        if (str)
        {
370
            sprintf((char*)str, "%d", item->valueint);
M
Max Bruckner 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383
        }
    }
    /* value is a floating point number */
    else
    {
        if (p)
        {
            /* This is a nice tradeoff. */
            str = ensure(p, 64);
        }
        else
        {
            /* This is a nice tradeoff. */
384
            str = (unsigned char*)cJSON_malloc(64);
M
Max Bruckner 已提交
385 386 387 388 389 390
        }
        if (str)
        {
            /* This checks for NaN and Infinity */
            if ((d * 0) != 0)
            {
391
                sprintf((char*)str, "null");
M
Max Bruckner 已提交
392
            }
393
            else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
M
Max Bruckner 已提交
394
            {
395
                sprintf((char*)str, "%.0f", d);
M
Max Bruckner 已提交
396 397 398
            }
            else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
            {
399
                sprintf((char*)str, "%e", d);
M
Max Bruckner 已提交
400 401 402
            }
            else
            {
403
                sprintf((char*)str, "%f", d);
M
Max Bruckner 已提交
404 405 406 407
            }
        }
    }
    return str;
K
Kevin Branigan 已提交
408 409
}

M
Max Bruckner 已提交
410
/* parse 4 digit hexadecimal number */
411
static unsigned parse_hex4(const unsigned char *str)
412
{
M
Max Bruckner 已提交
413 414
    unsigned int h = 0;

M
Max Bruckner 已提交
415 416 417
    /* first digit */
    if ((*str >= '0') && (*str <= '9'))
    {
M
Max Bruckner 已提交
418
        h += (unsigned int) (*str) - '0';
M
Max Bruckner 已提交
419 420 421
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
M
Max Bruckner 已提交
422
        h += (unsigned int) 10 + (*str) - 'A';
M
Max Bruckner 已提交
423 424 425
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
M
Max Bruckner 已提交
426
        h += (unsigned int) 10 + (*str) - 'a';
M
Max Bruckner 已提交
427 428 429 430 431 432 433 434 435 436 437 438
    }
    else /* invalid */
    {
        return 0;
    }


    /* second digit */
    h = h << 4;
    str++;
    if ((*str >= '0') && (*str <= '9'))
    {
M
Max Bruckner 已提交
439
        h += (unsigned int) (*str) - '0';
M
Max Bruckner 已提交
440 441 442
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
M
Max Bruckner 已提交
443
        h += (unsigned int) 10 + (*str) - 'A';
M
Max Bruckner 已提交
444 445 446
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
M
Max Bruckner 已提交
447
        h += (unsigned int) 10 + (*str) - 'a';
M
Max Bruckner 已提交
448 449 450 451 452 453 454 455 456 457 458
    }
    else /* invalid */
    {
        return 0;
    }

    /* third digit */
    h = h << 4;
    str++;
    if ((*str >= '0') && (*str <= '9'))
    {
M
Max Bruckner 已提交
459
        h += (unsigned int) (*str) - '0';
M
Max Bruckner 已提交
460 461 462
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
M
Max Bruckner 已提交
463
        h += (unsigned int) 10 + (*str) - 'A';
M
Max Bruckner 已提交
464 465 466
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
M
Max Bruckner 已提交
467
        h += (unsigned int) 10 + (*str) - 'a';
M
Max Bruckner 已提交
468 469 470 471 472 473 474 475 476 477 478
    }
    else /* invalid */
    {
        return 0;
    }

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

    return h;
495 496
}

M
Max Bruckner 已提交
497 498 499 500 501 502 503 504 505 506 507 508
/* first bytes of UTF8 encoding for a given length in bytes */
static const unsigned char firstByteMark[7] =
{
    0x00, /* should never happen */
    0x00, /* 0xxxxxxx */
    0xC0, /* 110xxxxx */
    0xE0, /* 1110xxxx */
    0xF0, /* 11110xxx */
    0xF8,
    0xFC
};

K
Kevin Branigan 已提交
509
/* Parse the input text into an unescaped cstring, and populate item. */
510
static const unsigned char *parse_string(cJSON *item, const unsigned char *str, const unsigned char **ep)
K
Kevin Branigan 已提交
511
{
512
    const unsigned char *ptr = str + 1;
M
Max Bruckner 已提交
513
    const unsigned char *end_ptr = str + 1;
514 515
    unsigned char *ptr2 = NULL;
    unsigned char *out = NULL;
516
    size_t len = 0;
M
Max Bruckner 已提交
517 518
    unsigned uc = 0;
    unsigned uc2 = 0;
M
Max Bruckner 已提交
519 520 521 522 523

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

527
    while ((*end_ptr != '\"') && *end_ptr)
M
Max Bruckner 已提交
528 529 530 531 532 533
    {
        if (*end_ptr++ == '\\')
        {
            if (*end_ptr == '\0')
            {
                /* prevent buffer overflow when last input character is a backslash */
534
                goto fail;
M
Max Bruckner 已提交
535 536 537 538
            }
            /* Skip escaped quotes. */
            end_ptr++;
        }
539
        len++;
M
Max Bruckner 已提交
540
    }
M
Max Bruckner 已提交
541

M
Max Bruckner 已提交
542
    /* This is at most how long we need for the string, roughly. */
543
    out = (unsigned char*)cJSON_malloc(len + 1);
M
Max Bruckner 已提交
544 545
    if (!out)
    {
546
        goto fail;
M
Max Bruckner 已提交
547
    }
548
    item->valuestring = (char*)out; /* assign here so out will be deleted during cJSON_Delete() later */
M
Max Bruckner 已提交
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
    item->type = cJSON_String;

    ptr = str + 1;
    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;
581 582 583 584 585
                case '\"':
                case '\\':
                case '/':
                    *ptr2++ = *ptr;
                    break;
M
Max Bruckner 已提交
586 587 588 589 590 591 592 593
                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;
594
                        goto fail;
M
Max Bruckner 已提交
595 596 597 598 599
                    }
                    /* check for invalid. */
                    if (((uc >= 0xDC00) && (uc <= 0xDFFF)) || (uc == 0))
                    {
                        *ep = str;
600
                        goto fail;
M
Max Bruckner 已提交
601 602 603 604 605 606 607 608 609
                    }

                    /* UTF16 surrogate pairs. */
                    if ((uc >= 0xD800) && (uc<=0xDBFF))
                    {
                        if ((ptr + 6) > end_ptr)
                        {
                            /* invalid */
                            *ep = str;
610
                            goto fail;
M
Max Bruckner 已提交
611 612 613 614 615
                        }
                        if ((ptr[1] != '\\') || (ptr[2] != 'u'))
                        {
                            /* missing second-half of surrogate. */
                            *ep = str;
616
                            goto fail;
M
Max Bruckner 已提交
617 618 619 620 621 622 623
                        }
                        uc2 = parse_hex4(ptr + 3);
                        ptr += 6; /* \uXXXX */
                        if ((uc2 < 0xDC00) || (uc2 > 0xDFFF))
                        {
                            /* invalid second-half of surrogate. */
                            *ep = str;
624
                            goto fail;
M
Max Bruckner 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
                        }
                        /* 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 已提交
654
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
655 656 657
                            uc >>= 6;
                        case 3:
                            /* 10xxxxxx */
M
Max Bruckner 已提交
658
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
659 660 661
                            uc >>= 6;
                        case 2:
                            /* 10xxxxxx */
M
Max Bruckner 已提交
662
                            *--ptr2 = (unsigned char)((uc | 0x80) & 0xBF);
M
Max Bruckner 已提交
663 664 665 666
                            uc >>= 6;
                        case 1:
                            /* depending on the length in bytes this determines the
                             * encoding ofthe first UTF8 byte */
M
Max Bruckner 已提交
667
                            *--ptr2 = (unsigned char)((uc | firstByteMark[len]) & 0xFF);
M
Max Bruckner 已提交
668
                            break;
669 670
                        default:
                            *ep = str;
671
                            goto fail;
M
Max Bruckner 已提交
672 673 674 675
                    }
                    ptr2 += len;
                    break;
                default:
676
                    *ep = str;
677
                    goto fail;
M
Max Bruckner 已提交
678 679 680 681 682 683 684 685 686 687 688
            }
            ptr++;
        }
    }
    *ptr2 = '\0';
    if (*ptr == '\"')
    {
        ptr++;
    }

    return ptr;
689 690 691 692 693 694 695 696

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

    return NULL;
K
Kevin Branigan 已提交
697 698 699
}

/* Render the cstring provided to an escaped version that can be printed. */
700
static unsigned char *print_string_ptr(const unsigned char *str, printbuffer *p)
K
Kevin Branigan 已提交
701
{
702 703 704
    const unsigned char *ptr = NULL;
    unsigned char *ptr2 = NULL;
    unsigned char *out = NULL;
705
    size_t len = 0;
M
Max Bruckner 已提交
706
    cjbool flag = false;
M
Max Bruckner 已提交
707
    unsigned char token = '\0';
M
Max Bruckner 已提交
708 709 710 711 712 713 714 715 716 717

    /* empty string */
    if (!str)
    {
        if (p)
        {
            out = ensure(p, 3);
        }
        else
        {
718
            out = (unsigned char*)cJSON_malloc(3);
M
Max Bruckner 已提交
719 720 721
        }
        if (!out)
        {
722
            return NULL;
M
Max Bruckner 已提交
723
        }
724
        strcpy((char*)out, "\"\"");
M
Max Bruckner 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

        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 已提交
741
        len = (size_t)(ptr - str);
M
Max Bruckner 已提交
742 743 744 745 746 747
        if (p)
        {
            out = ensure(p, len + 3);
        }
        else
        {
748
            out = (unsigned char*)cJSON_malloc(len + 3);
M
Max Bruckner 已提交
749 750 751
        }
        if (!out)
        {
752
            return NULL;
M
Max Bruckner 已提交
753 754 755 756
        }

        ptr2 = out;
        *ptr2++ = '\"';
757
        strcpy((char*)ptr2, (const char*)str);
M
Max Bruckner 已提交
758 759 760 761 762 763 764 765
        ptr2[len] = '\"';
        ptr2[len + 1] = '\0';

        return out;
    }

    ptr = str;
    /* calculate additional space that is needed for escaping */
S
Stephan 已提交
766
    while ((token = *ptr))
M
Max Bruckner 已提交
767
    {
S
Stephan 已提交
768
        ++len;
M
Max Bruckner 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
        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
    {
786
        out = (unsigned char*)cJSON_malloc(len + 3);
M
Max Bruckner 已提交
787 788 789
    }
    if (!out)
    {
790
        return NULL;
M
Max Bruckner 已提交
791 792 793 794 795 796 797 798
    }

    ptr2 = out;
    ptr = str;
    *ptr2++ = '\"';
    /* copy the string */
    while (*ptr)
    {
799
        if ((*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
M
Max Bruckner 已提交
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        {
            /* 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 */
833
                    sprintf((char*)ptr2, "u%04x", token);
M
Max Bruckner 已提交
834 835 836 837 838 839 840 841 842
                    ptr2 += 5;
                    break;
            }
        }
    }
    *ptr2++ = '\"';
    *ptr2++ = '\0';

    return out;
K
Kevin Branigan 已提交
843
}
M
Max Bruckner 已提交
844

M
Max Bruckner 已提交
845
/* Invoke print_string_ptr (which is useful) on an item. */
846
static unsigned char *print_string(const cJSON *item, printbuffer *p)
M
Max Bruckner 已提交
847
{
848
    return print_string_ptr((unsigned char*)item->valuestring, p);
M
Max Bruckner 已提交
849
}
K
Kevin Branigan 已提交
850 851

/* Predeclare these prototypes. */
852
static const unsigned char *parse_value(cJSON *item, const unsigned char *value, const unsigned char **ep);
853
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
854
static const unsigned char *parse_array(cJSON *item, const unsigned char *value, const unsigned char **ep);
855
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
856
static const unsigned char *parse_object(cJSON *item, const unsigned char *value, const unsigned char **ep);
857
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p);
K
Kevin Branigan 已提交
858 859

/* Utility to jump whitespace and cr/lf */
860
static const unsigned char *skip(const unsigned char *in)
M
Max Bruckner 已提交
861
{
862
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
863 864 865 866 867 868
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
869 870

/* Parse an object - create a new root, and populate. */
M
Max Bruckner 已提交
871
cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cjbool require_null_terminated)
K
Kevin Branigan 已提交
872
{
873
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
874
    /* use global error pointer if no specific one was given */
875
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
M
Max Bruckner 已提交
876
    cJSON *c = cJSON_New_Item();
877
    *ep = NULL;
M
Max Bruckner 已提交
878 879
    if (!c) /* memory fail */
    {
880
        return NULL;
M
Max Bruckner 已提交
881 882
    }

883
    end = parse_value(c, skip((const unsigned char*)value), ep);
M
Max Bruckner 已提交
884 885 886 887
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
888
        return NULL;
M
Max Bruckner 已提交
889 890 891 892 893 894 895 896 897 898
    }

    /* 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;
899
            return NULL;
M
Max Bruckner 已提交
900 901 902 903
        }
    }
    if (return_parse_end)
    {
904
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
905 906 907
    }

    return c;
K
Kevin Branigan 已提交
908
}
M
Max Bruckner 已提交
909

910
/* Default options for cJSON_Parse */
M
Max Bruckner 已提交
911 912 913 914
cJSON *cJSON_Parse(const char *value)
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
915 916

/* Render a cJSON item/entity/structure to text. */
917
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
918
{
919
    return (char*)print_value(item, 0, 1, 0);
M
Max Bruckner 已提交
920 921
}

922
char *cJSON_PrintUnformatted(const cJSON *item)
923
{
924
    return (char*)print_value(item, 0, 0, 0);
925
}
926

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

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

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

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

946
    return (char*)print_value(item, 0, fmt, &p);
947 948
}

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

    if (len < 0)
    {
        return false;
    }

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

/* Parser core - when encountering text, process appropriately. */
966
static const unsigned  char *parse_value(cJSON *item, const unsigned char *value, const unsigned char **ep)
K
Kevin Branigan 已提交
967
{
M
Max Bruckner 已提交
968 969 970
    if (!value)
    {
        /* Fail on null. */
971
        return NULL;
M
Max Bruckner 已提交
972 973 974
    }

    /* parse the different types of values */
975
    if (!strncmp((const char*)value, "null", 4))
M
Max Bruckner 已提交
976 977 978 979
    {
        item->type = cJSON_NULL;
        return value + 4;
    }
980
    if (!strncmp((const char*)value, "false", 5))
M
Max Bruckner 已提交
981 982 983 984
    {
        item->type = cJSON_False;
        return value + 5;
    }
985
    if (!strncmp((const char*)value, "true", 4))
M
Max Bruckner 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    {
        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 已提交
1008 1009
    /* failure. */
    *ep = value;
1010
    return NULL;
K
Kevin Branigan 已提交
1011 1012 1013
}

/* Render a value to text. */
1014
static unsigned char *print_value(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1015
{
1016
    unsigned char *out = NULL;
M
Max Bruckner 已提交
1017 1018 1019

    if (!item)
    {
1020
        return NULL;
M
Max Bruckner 已提交
1021 1022 1023
    }
    if (p)
    {
1024
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1025 1026 1027 1028 1029
        {
            case cJSON_NULL:
                out = ensure(p, 5);
                if (out)
                {
1030
                    strcpy((char*)out, "null");
M
Max Bruckner 已提交
1031 1032 1033 1034 1035 1036
                }
                break;
            case cJSON_False:
                out = ensure(p, 6);
                if (out)
                {
1037
                    strcpy((char*)out, "false");
M
Max Bruckner 已提交
1038 1039 1040 1041 1042 1043
                }
                break;
            case cJSON_True:
                out = ensure(p, 5);
                if (out)
                {
1044
                    strcpy((char*)out, "true");
M
Max Bruckner 已提交
1045 1046 1047 1048 1049
                }
                break;
            case cJSON_Number:
                out = print_number(item, p);
                break;
J
Jiri Zouhar 已提交
1050
            case cJSON_Raw:
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            {
                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 已提交
1065 1066
                if (out)
                {
1067
                    memcpy(out, item->valuestring, raw_length);
J
Jiri Zouhar 已提交
1068 1069
                }
                break;
1070
            }
M
Max Bruckner 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079
            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;
1080 1081 1082
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
1083 1084 1085 1086
        }
    }
    else
    {
1087
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1088 1089
        {
            case cJSON_NULL:
1090
                out = cJSON_strdup((const unsigned char*)"null");
M
Max Bruckner 已提交
1091 1092
                break;
            case cJSON_False:
1093
                out = cJSON_strdup((const unsigned char*)"false");
M
Max Bruckner 已提交
1094 1095
                break;
            case cJSON_True:
1096
                out = cJSON_strdup((const unsigned char*)"true");
M
Max Bruckner 已提交
1097 1098 1099 1100
                break;
            case cJSON_Number:
                out = print_number(item, 0);
                break;
J
Jiri Zouhar 已提交
1101
            case cJSON_Raw:
1102
                out = cJSON_strdup((unsigned char*)item->valuestring);
J
Jiri Zouhar 已提交
1103
                break;
M
Max Bruckner 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112
            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;
1113 1114 1115
            default:
                out = NULL;
                break;
M
Max Bruckner 已提交
1116 1117 1118 1119
        }
    }

    return out;
K
Kevin Branigan 已提交
1120 1121 1122
}

/* Build an array from input text. */
1123
static const unsigned char *parse_array(cJSON *item, const unsigned char *value, const unsigned char **ep)
K
Kevin Branigan 已提交
1124
{
M
Max Bruckner 已提交
1125
    cJSON *child = NULL;
M
Max Bruckner 已提交
1126 1127 1128 1129
    if (*value != '[')
    {
        /* not an array! */
        *ep = value;
1130
        goto fail;
M
Max Bruckner 已提交
1131
    }
K
Kevin Branigan 已提交
1132

M
Max Bruckner 已提交
1133 1134 1135 1136 1137 1138 1139
    item->type = cJSON_Array;
    value = skip(value + 1);
    if (*value == ']')
    {
        /* empty array. */
        return value + 1;
    }
K
Kevin Branigan 已提交
1140

M
Max Bruckner 已提交
1141 1142 1143 1144
    item->child = child = cJSON_New_Item();
    if (!item->child)
    {
        /* memory fail */
1145
        goto fail;
M
Max Bruckner 已提交
1146 1147 1148 1149 1150
    }
    /* skip any spacing, get the value. */
    value = skip(parse_value(child, skip(value), ep));
    if (!value)
    {
1151
        goto fail;
M
Max Bruckner 已提交
1152
    }
K
Kevin Branigan 已提交
1153

M
Max Bruckner 已提交
1154 1155 1156
    /* loop through the comma separated array elements */
    while (*value == ',')
    {
M
Max Bruckner 已提交
1157
        cJSON *new_item = NULL;
M
Max Bruckner 已提交
1158 1159 1160
        if (!(new_item = cJSON_New_Item()))
        {
            /* memory fail */
1161
            goto fail;
M
Max Bruckner 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        }
        /* add new item to end of the linked list */
        child->next = new_item;
        new_item->prev = child;
        child = new_item;

        /* go to the next comma */
        value = skip(parse_value(child, skip(value + 1), ep));
        if (!value)
        {
            /* memory fail */
1173
            goto fail;
M
Max Bruckner 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        }
    }

    if (*value == ']')
    {
        /* end of array */
        return value + 1;
    }

    /* malformed. */
    *ep = value;
K
Kevin Branigan 已提交
1185

1186 1187 1188 1189 1190 1191 1192
fail:
    if (item->child != NULL)
    {
        cJSON_Delete(item->child);
        item->child = NULL;
    }

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

/* Render an array to text */
1197
static unsigned char *print_array(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1198
{
1199 1200 1201 1202
    unsigned char **entries;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
1203
    size_t len = 5;
M
Max Bruckner 已提交
1204
    cJSON *child = item->child;
1205 1206
    size_t numentries = 0;
    size_t i = 0;
M
Max Bruckner 已提交
1207
    cjbool fail = false;
M
Max Bruckner 已提交
1208
    size_t tmplen = 0;
K
Kevin Branigan 已提交
1209

M
Max Bruckner 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    /* 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
        {
1226
            out = (unsigned char*)cJSON_malloc(3);
M
Max Bruckner 已提交
1227 1228 1229
        }
        if (out)
        {
1230
            strcpy((char*)out, "[]");
M
Max Bruckner 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        }

        return out;
    }

    if (p)
    {
        /* Compose the output array. */
        /* opening square bracket */
        i = p->offset;
        ptr = ensure(p, 1);
        if (!ptr)
        {
1244
            return NULL;
M
Max Bruckner 已提交
1245 1246 1247 1248 1249 1250 1251
        }
        *ptr = '[';
        p->offset++;

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

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

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

        /* 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);
1334
            return NULL;
M
Max Bruckner 已提交
1335 1336 1337 1338 1339 1340 1341 1342
        }

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

    return out;
K
Kevin Branigan 已提交
1363 1364 1365
}

/* Build an object from the text. */
1366
static const unsigned char *parse_object(cJSON *item, const unsigned char *value, const unsigned char **ep)
K
Kevin Branigan 已提交
1367
{
M
Max Bruckner 已提交
1368
    cJSON *child = NULL;
M
Max Bruckner 已提交
1369 1370 1371 1372
    if (*value != '{')
    {
        /* not an object! */
        *ep = value;
1373
        goto fail;
M
Max Bruckner 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    }

    item->type = cJSON_Object;
    value = skip(value + 1);
    if (*value == '}')
    {
        /* empty object. */
        return value + 1;
    }

    child = cJSON_New_Item();
    item->child = child;
    if (!item->child)
    {
1388
        goto fail;
M
Max Bruckner 已提交
1389 1390 1391 1392 1393
    }
    /* parse first key */
    value = skip(parse_string(child, skip(value), ep));
    if (!value)
    {
1394
        goto fail;
M
Max Bruckner 已提交
1395 1396 1397
    }
    /* use string as key, not value */
    child->string = child->valuestring;
1398
    child->valuestring = NULL;
M
Max Bruckner 已提交
1399 1400 1401 1402 1403

    if (*value != ':')
    {
        /* invalid object. */
        *ep = value;
1404
        goto fail;
M
Max Bruckner 已提交
1405 1406 1407 1408 1409
    }
    /* skip any spacing, get the value. */
    value = skip(parse_value(child, skip(value + 1), ep));
    if (!value)
    {
1410
        goto fail;
M
Max Bruckner 已提交
1411 1412 1413 1414
    }

    while (*value == ',')
    {
M
Max Bruckner 已提交
1415
        cJSON *new_item = NULL;
M
Max Bruckner 已提交
1416 1417 1418
        if (!(new_item = cJSON_New_Item()))
        {
            /* memory fail */
1419
            goto fail;
M
Max Bruckner 已提交
1420 1421 1422 1423 1424 1425 1426 1427 1428
        }
        /* 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)
        {
1429
            goto fail;
M
Max Bruckner 已提交
1430 1431 1432 1433
        }

        /* use string as key, not value */
        child->string = child->valuestring;
1434
        child->valuestring = NULL;
M
Max Bruckner 已提交
1435 1436 1437 1438 1439

        if (*value != ':')
        {
            /* invalid object. */
            *ep = value;
1440
            goto fail;
M
Max Bruckner 已提交
1441 1442 1443 1444 1445
        }
        /* skip any spacing, get the value. */
        value = skip(parse_value(child, skip(value + 1), ep));
        if (!value)
        {
1446
            goto fail;
M
Max Bruckner 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
        }
    }
    /* end of object */
    if (*value == '}')
    {
        return value + 1;
    }

    /* malformed */
    *ep = value;
1457 1458 1459 1460 1461 1462 1463 1464

fail:
    if (item->child != NULL)
    {
        cJSON_Delete(child);
        item->child = NULL;
    }

1465
    return NULL;
K
Kevin Branigan 已提交
1466 1467 1468
}

/* Render an object to text. */
1469
static unsigned char *print_object(const cJSON *item, size_t depth, cjbool fmt, printbuffer *p)
1470 1471 1472 1473 1474 1475 1476
{
    unsigned char **entries = NULL;
    unsigned char **names = NULL;
    unsigned char *out = NULL;
    unsigned char *ptr = NULL;
    unsigned char *ret = NULL;
    unsigned char *str = NULL;
1477 1478 1479
    size_t len = 7;
    size_t i = 0;
    size_t j = 0;
M
Max Bruckner 已提交
1480
    cJSON *child = item->child;
1481
    size_t numentries = 0;
M
Max Bruckner 已提交
1482
    cjbool fail = false;
M
Max Bruckner 已提交
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    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
        {
1501
            out = (unsigned char*)cJSON_malloc(fmt ? depth + 4 : 3);
M
Max Bruckner 已提交
1502 1503 1504
        }
        if (!out)
        {
1505
            return NULL;
M
Max Bruckner 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
        }
        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)
        {
1530
            return NULL;
M
Max Bruckner 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        }

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

        child = item->child;
        depth++;
        while (child)
        {
            if (fmt)
            {
                ptr = ensure(p, depth);
                if (!ptr)
                {
1550
                    return NULL;
M
Max Bruckner 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559
                }
                for (j = 0; j < depth; j++)
                {
                    *ptr++ = '\t';
                }
                p->offset += depth;
            }

            /* print key */
1560
            if (!print_string_ptr((unsigned char*)child->string, p))
1561 1562 1563
            {
                return NULL;
            }
M
Max Bruckner 已提交
1564 1565 1566 1567 1568 1569
            p->offset = update(p);

            len = fmt ? 2 : 1;
            ptr = ensure(p, len);
            if (!ptr)
            {
1570
                return NULL;
M
Max Bruckner 已提交
1571 1572 1573 1574 1575 1576 1577 1578 1579
            }
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
            p->offset+=len;

            /* print value */
K
Kyle Chisholm 已提交
1580 1581 1582 1583
            if (!print_value(child, depth, fmt, p))
            {
                return NULL;
            };
M
Max Bruckner 已提交
1584 1585 1586
            p->offset = update(p);

            /* print comma if not last */
M
Max Bruckner 已提交
1587
            len = (size_t) (fmt ? 1 : 0) + (child->next ? 1 : 0);
M
Max Bruckner 已提交
1588 1589 1590
            ptr = ensure(p, len + 1);
            if (!ptr)
            {
1591
                return NULL;
M
Max Bruckner 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
            }
            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)
        {
1611
            return NULL;
M
Max Bruckner 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
        }
        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 */
1627
        entries = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1628 1629
        if (!entries)
        {
1630
            return NULL;
M
Max Bruckner 已提交
1631
        }
1632
        names = (unsigned char**)cJSON_malloc(numentries * sizeof(unsigned char*));
M
Max Bruckner 已提交
1633 1634 1635
        if (!names)
        {
            cJSON_free(entries);
1636
            return NULL;
M
Max Bruckner 已提交
1637
        }
1638 1639
        memset(entries, '\0', sizeof(unsigned char*) * numentries);
        memset(names, '\0', sizeof(unsigned char*) * numentries);
M
Max Bruckner 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

        /* Collect all the results into our arrays: */
        child = item->child;
        depth++;
        if (fmt)
        {
            len += depth;
        }
        while (child && !fail)
        {
1650
            names[i] = str = print_string_ptr((unsigned char*)child->string, 0); /* print key */
M
Max Bruckner 已提交
1651 1652 1653
            entries[i++] = ret = print_value(child, depth, fmt, 0);
            if (str && ret)
            {
1654
                len += strlen((char*)ret) + strlen((char*)str) + 2 + (fmt ? 2 + depth : 0);
M
Max Bruckner 已提交
1655 1656 1657
            }
            else
            {
M
Max Bruckner 已提交
1658
                fail = true;
M
Max Bruckner 已提交
1659 1660 1661 1662 1663 1664 1665
            }
            child = child->next;
        }

        /* Try to allocate the output string */
        if (!fail)
        {
1666
            out = (unsigned char*)cJSON_malloc(len);
M
Max Bruckner 已提交
1667 1668 1669
        }
        if (!out)
        {
M
Max Bruckner 已提交
1670
            fail = true;
M
Max Bruckner 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
        }

        /* 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);
1690
            return NULL;
M
Max Bruckner 已提交
1691 1692 1693 1694 1695 1696 1697 1698 1699
        }

        /* Compose the output: */
        *out = '{';
        ptr = out + 1;
        if (fmt)
        {
            *ptr++ = '\n';
        }
1700
        *ptr = '\0';
M
Max Bruckner 已提交
1701 1702 1703 1704 1705 1706 1707 1708 1709
        for (i = 0; i < numentries; i++)
        {
            if (fmt)
            {
                for (j = 0; j < depth; j++)
                {
                    *ptr++='\t';
                }
            }
1710
            tmplen = strlen((char*)names[i]);
M
Max Bruckner 已提交
1711 1712 1713 1714 1715 1716 1717
            memcpy(ptr, names[i], tmplen);
            ptr += tmplen;
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
1718 1719
            strcpy((char*)ptr, (char*)entries[i]);
            ptr += strlen((char*)entries[i]);
M
Max Bruckner 已提交
1720 1721 1722 1723 1724 1725 1726 1727
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
            }
            if (fmt)
            {
                *ptr++ = '\n';
            }
1728
            *ptr = '\0';
M
Max Bruckner 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
            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 已提交
1747 1748 1749
}

/* Get Array size/item / object item. */
M
Max Bruckner 已提交
1750
int cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1751 1752
{
    cJSON *c = array->child;
1753
    size_t i = 0;
M
Max Bruckner 已提交
1754 1755 1756 1757 1758
    while(c)
    {
        i++;
        c = c->next;
    }
1759 1760 1761

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

M
Max Bruckner 已提交
1762
    return (int)i;
M
Max Bruckner 已提交
1763 1764
}

1765
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1766
{
1767
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1777
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1778
{
1779
    cJSON *c = object ? object->child : NULL;
1780
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1781 1782 1783 1784 1785 1786
    {
        c = c->next;
    }
    return c;
}

1787
cjbool cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1788 1789 1790
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1791 1792

/* Utility for array list handling. */
M
Max Bruckner 已提交
1793 1794 1795 1796 1797 1798
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1799
/* Utility for handling references. */
1800
static cJSON *create_reference(const cJSON *item)
M
Max Bruckner 已提交
1801 1802 1803 1804
{
    cJSON *ref = cJSON_New_Item();
    if (!ref)
    {
1805
        return NULL;
M
Max Bruckner 已提交
1806 1807
    }
    memcpy(ref, item, sizeof(cJSON));
1808
    ref->string = NULL;
M
Max Bruckner 已提交
1809
    ref->type |= cJSON_IsReference;
1810
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1811 1812
    return ref;
}
K
Kevin Branigan 已提交
1813 1814

/* Add item to array/object. */
1815
void cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1816
{
1817 1818 1819
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1820 1821 1822
    {
        return;
    }
1823 1824 1825 1826

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1827 1828 1829 1830 1831 1832 1833
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1834
        while (child->next)
M
Max Bruckner 已提交
1835
        {
1836
            child = child->next;
M
Max Bruckner 已提交
1837
        }
1838
        suffix_object(child, item);
M
Max Bruckner 已提交
1839 1840 1841
    }
}

M
Max Bruckner 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
    if (!item)
    {
        return;
    }

    /* free old key and set new one */
    if (item->string)
    {
        cJSON_free(item->string);
    }
1854
    item->string = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
1855 1856 1857 1858

    cJSON_AddItemToArray(object,item);
}

1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
/* 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);
    }
1870 1871
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1872
    item->string = (char*)string;
1873
#pragma GCC diagnostic pop
1874 1875 1876 1877
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1878 1879 1880 1881 1882
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    cJSON_AddItemToArray(array, create_reference(item));
}

1883 1884 1885 1886 1887
void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
    cJSON_AddItemToObject(object, string, create_reference(item));
}

M
Max Bruckner 已提交
1888
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1899
        return NULL;
1900
    }
1901
    if (c->prev)
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
    {
        /* 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 */
1915
    c->prev = c->next = NULL;
1916 1917 1918

    return c;
}
M
Max Bruckner 已提交
1919 1920 1921 1922 1923 1924 1925 1926 1927
cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
    if (which < 0)
    {
        return NULL;
    }

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

1929 1930 1931 1932 1933
void cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1934 1935
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
1936
    size_t i = 0;
1937
    cJSON *c = object->child;
1938
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1939 1940 1941 1942 1943 1944
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1945
        return DetachItemFromArray(object, i);
1946 1947
    }

1948
    return NULL;
1949 1950
}

1951 1952 1953 1954
void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1955 1956

/* Replace array/object items with new ones. */
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
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 已提交
1983
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
{
    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;
    }
2009
    c->next = c->prev = NULL;
2010 2011
    cJSON_Delete(c);
}
M
Max Bruckner 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020
void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    if (which < 0)
    {
        return;
    }

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

2022 2023
void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
2024
    size_t i = 0;
2025
    cJSON *c = object->child;
2026
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
2027 2028 2029 2030 2031 2032
    {
        i++;
        c = c->next;
    }
    if(c)
    {
2033 2034 2035 2036 2037 2038
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
             cJSON_free(newitem->string);
        }

2039
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
2040
        ReplaceItemInArray(object, i, newitem);
2041 2042
    }
}
K
Kevin Branigan 已提交
2043 2044

/* Create basic types: */
M
Max Bruckner 已提交
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
cJSON *cJSON_CreateNull(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

M
Max Bruckner 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
cJSON *cJSON_CreateTrue(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

M
Max Bruckner 已提交
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
cJSON *cJSON_CreateFalse(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
2078
cJSON *cJSON_CreateBool(cjbool b)
M
Max Bruckner 已提交
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
2089 2090 2091 2092 2093 2094 2095
cJSON *cJSON_CreateNumber(double num)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109

        /* 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 已提交
2110 2111 2112 2113 2114
    }

    return item;
}

M
Max Bruckner 已提交
2115 2116 2117 2118 2119 2120
cJSON *cJSON_CreateString(const char *string)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_String;
2121
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string);
M
Max Bruckner 已提交
2122 2123 2124
        if(!item->valuestring)
        {
            cJSON_Delete(item);
2125
            return NULL;
M
Max Bruckner 已提交
2126 2127 2128 2129 2130 2131
        }
    }

    return item;
}

J
Jiri Zouhar 已提交
2132 2133
extern cJSON *cJSON_CreateRaw(const char *raw)
{
M
Max Bruckner 已提交
2134 2135 2136 2137
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Raw;
2138
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw);
M
Max Bruckner 已提交
2139 2140 2141 2142 2143 2144 2145 2146
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
2147 2148
}

M
Max Bruckner 已提交
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
cJSON *cJSON_CreateArray(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

M
Max Bruckner 已提交
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
cJSON *cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item();
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2170 2171

/* Create Arrays: */
M
Max Bruckner 已提交
2172 2173
cJSON *cJSON_CreateIntArray(const int *numbers, int count)
{
2174
    size_t i = 0;
2175 2176
    cJSON *n = NULL;
    cJSON *p = NULL;
2177 2178 2179 2180 2181 2182 2183 2184 2185
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2186 2187 2188 2189 2190
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2191
            return NULL;
M
Max Bruckner 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

M
Max Bruckner 已提交
2207 2208
cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
{
2209
    size_t i = 0;
2210 2211
    cJSON *n = NULL;
    cJSON *p = NULL;
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
2222 2223 2224 2225 2226
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2227
            return NULL;
M
Max Bruckner 已提交
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2243 2244
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
2245
    size_t i = 0;
2246 2247
    cJSON *n = NULL;
    cJSON *p = NULL;
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
2258 2259 2260 2261 2262
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2263
            return NULL;
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2279 2280
cJSON *cJSON_CreateStringArray(const char **strings, int count)
{
2281
    size_t i = 0;
2282 2283
    cJSON *n = NULL;
    cJSON *p = NULL;
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2294 2295 2296 2297 2298
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2299
            return NULL;
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2314 2315

/* Duplication */
M
Max Bruckner 已提交
2316
cJSON *cJSON_Duplicate(const cJSON *item, cjbool recurse)
2317
{
M
Max Bruckner 已提交
2318
    cJSON *newitem = NULL;
2319 2320
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2321
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2322 2323 2324 2325

    /* Bail on bad ptr */
    if (!item)
    {
2326
        goto fail;
M
Max Bruckner 已提交
2327 2328 2329 2330 2331
    }
    /* Create new item */
    newitem = cJSON_New_Item();
    if (!newitem)
    {
2332
        goto fail;
M
Max Bruckner 已提交
2333 2334 2335 2336 2337 2338 2339
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2340
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring);
M
Max Bruckner 已提交
2341 2342
        if (!newitem->valuestring)
        {
2343
            goto fail;
M
Max Bruckner 已提交
2344 2345 2346 2347
        }
    }
    if (item->string)
    {
2348
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string);
M
Max Bruckner 已提交
2349 2350
        if (!newitem->string)
        {
2351
            goto fail;
M
Max Bruckner 已提交
2352 2353 2354 2355 2356 2357 2358 2359
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2360 2361
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2362
    {
2363
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2364 2365
        if (!newchild)
        {
2366
            goto fail;
M
Max Bruckner 已提交
2367
        }
2368
        if (next != NULL)
M
Max Bruckner 已提交
2369 2370
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2371 2372 2373
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2374 2375 2376 2377
        }
        else
        {
            /* Set newitem->child and move to it */
2378 2379
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2380
        }
2381
        child = child->next;
M
Max Bruckner 已提交
2382 2383 2384
    }

    return newitem;
2385 2386 2387 2388 2389 2390 2391 2392

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

    return NULL;
2393
}
2394 2395 2396

void cJSON_Minify(char *json)
{
2397
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    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 已提交
2437
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2438 2439 2440 2441
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2442
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2443
                }
M
Max Bruckner 已提交
2444
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2445
            }
M
Max Bruckner 已提交
2446
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2447 2448 2449 2450
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2451
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2452 2453 2454 2455 2456
        }
    }

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