cJSON.c 49.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 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

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

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

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

    return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
K
Kevin Branigan 已提交
81 82 83 84 85 86 87
}

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

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

M
Max Bruckner 已提交
91 92 93
    len = strlen(str) + 1;
    if (!(copy = (char*)cJSON_malloc(len)))
    {
94
        return NULL;
M
Max Bruckner 已提交
95 96 97 98
    }
    memcpy(copy, str, len);

    return copy;
K
Kevin Branigan 已提交
99 100 101 102
}

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

M
Max Bruckner 已提交
111 112
    cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
    cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
K
Kevin Branigan 已提交
113 114 115
}

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

    return node;
K
Kevin Branigan 已提交
125 126 127 128 129
}

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

/* Parse the input text to generate a number, and populate the result into item. */
M
Max Bruckner 已提交
152
static const char *parse_number(cJSON *item, const char *num)
K
Kevin Branigan 已提交
153
{
M
Max Bruckner 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 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
    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;
    item->valueint = (int)n;
    item->type = cJSON_Number;

    return num;
K
Kevin Branigan 已提交
219 220
}

M
Max Bruckner 已提交
221 222 223 224 225 226 227 228
/* 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 已提交
229
#if INTEGER_SIZE & 0x1110 /* at least 16 bit */
M
Max Bruckner 已提交
230
    x |= x >> 8;
M
Max Bruckner 已提交
231 232
#endif
#if INTEGER_SIZE & 0x1100 /* at least 32 bit */
M
Max Bruckner 已提交
233
    x |= x >> 16;
M
Max Bruckner 已提交
234 235 236 237
#endif
#if INT_SIZE & 0x1000 /* 64 bit */
    x |= x >> 32;
#endif
M
Max Bruckner 已提交
238 239 240

    return x + 1;
}
241

M
Max Bruckner 已提交
242 243 244 245 246
typedef struct
{
    char *buffer;
    int length;
    int offset;
247
    cjbool noalloc;
M
Max Bruckner 已提交
248
} printbuffer;
249

M
Max Bruckner 已提交
250 251
/* realloc printbuffer if necessary to have at least "needed" bytes more */
static char* ensure(printbuffer *p, int needed)
252
{
M
Max Bruckner 已提交
253 254
    char *newbuffer = NULL;
    int newsize = 0;
M
Max Bruckner 已提交
255 256
    if (!p || !p->buffer)
    {
257
        return NULL;
M
Max Bruckner 已提交
258 259 260 261 262 263 264
    }
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

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

M
Max Bruckner 已提交
269 270 271 272 273 274
    newsize = pow2gt(needed);
    newbuffer = (char*)cJSON_malloc(newsize);
    if (!newbuffer)
    {
        cJSON_free(p->buffer);
        p->length = 0;
275
        p->buffer = NULL;
M
Max Bruckner 已提交
276

277
        return NULL;
M
Max Bruckner 已提交
278 279 280 281 282 283 284 285 286 287
    }
    if (newbuffer)
    {
        memcpy(newbuffer, p->buffer, p->length);
    }
    cJSON_free(p->buffer);
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
288 289
}

M
Max Bruckner 已提交
290
/* calculate the new length of the string in a printbuffer */
291
static int update(const printbuffer *p)
K
Kevin Branigan 已提交
292
{
M
Max Bruckner 已提交
293
    char *str = NULL;
M
Max Bruckner 已提交
294 295 296 297 298 299 300
    if (!p || !p->buffer)
    {
        return 0;
    }
    str = p->buffer + p->offset;

    return p->offset + strlen(str);
301 302 303
}

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

M
Max Bruckner 已提交
378
/* parse 4 digit hexadecimal number */
379 380
static unsigned parse_hex4(const char *str)
{
M
Max Bruckner 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    unsigned h = 0;
    /* first digit */
    if ((*str >= '0') && (*str <= '9'))
    {
        h += (*str) - '0';
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
        h += 10 + (*str) - 'A';
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
        h += 10 + (*str) - 'a';
    }
    else /* invalid */
    {
        return 0;
    }


    /* second digit */
    h = h << 4;
    str++;
    if ((*str >= '0') && (*str <= '9'))
    {
        h += (*str) - '0';
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
        h += 10 + (*str) - 'A';
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
        h += 10 + (*str) - 'a';
    }
    else /* invalid */
    {
        return 0;
    }

    /* third digit */
    h = h << 4;
    str++;
    if ((*str >= '0') && (*str <= '9'))
    {
        h += (*str) - '0';
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
        h += 10 + (*str) - 'A';
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
        h += 10 + (*str) - 'a';
    }
    else /* invalid */
    {
        return 0;
    }

    /* fourth digit */
    h = h << 4;
    str++;
    if ((*str >= '0') && (*str <= '9'))
    {
        h += (*str) - '0';
    }
    else if ((*str >= 'A') && (*str <= 'F'))
    {
        h += 10 + (*str) - 'A';
    }
    else if ((*str >= 'a') && (*str <= 'f'))
    {
        h += 10 + (*str) - 'a';
    }
    else /* invalid */
    {
        return 0;
    }

    return h;
462 463
}

M
Max Bruckner 已提交
464 465 466 467 468 469 470 471 472 473 474 475
/* 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 已提交
476
/* Parse the input text into an unescaped cstring, and populate item. */
M
Max Bruckner 已提交
477
static const char *parse_string(cJSON *item, const char *str, const char **ep)
K
Kevin Branigan 已提交
478
{
M
Max Bruckner 已提交
479 480
    const char *ptr = str + 1;
    const char *end_ptr =str + 1;
M
Max Bruckner 已提交
481 482
    char *ptr2 = NULL;
    char *out = NULL;
M
Max Bruckner 已提交
483
    int len = 0;
M
Max Bruckner 已提交
484 485
    unsigned uc = 0;
    unsigned uc2 = 0;
M
Max Bruckner 已提交
486 487 488 489 490

    /* not a string! */
    if (*str != '\"')
    {
        *ep = str;
491
        return NULL;
M
Max Bruckner 已提交
492
    }
M
Max Bruckner 已提交
493

M
Max Bruckner 已提交
494 495 496 497 498 499 500
    while ((*end_ptr != '\"') && *end_ptr && ++len)
    {
        if (*end_ptr++ == '\\')
        {
            if (*end_ptr == '\0')
            {
                /* prevent buffer overflow when last input character is a backslash */
501
                return NULL;
M
Max Bruckner 已提交
502 503 504 505 506
            }
            /* Skip escaped quotes. */
            end_ptr++;
        }
    }
M
Max Bruckner 已提交
507

M
Max Bruckner 已提交
508 509 510 511
    /* This is at most how long we need for the string, roughly. */
    out = (char*)cJSON_malloc(len + 1);
    if (!out)
    {
512
        return NULL;
M
Max Bruckner 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    }
    item->valuestring = out; /* assign here so out will be deleted during cJSON_Delete() later */
    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;
547 548 549 550 551
                case '\"':
                case '\\':
                case '/':
                    *ptr2++ = *ptr;
                    break;
M
Max Bruckner 已提交
552 553 554 555 556 557 558 559
                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;
560
                        return NULL;
M
Max Bruckner 已提交
561 562 563 564 565
                    }
                    /* check for invalid. */
                    if (((uc >= 0xDC00) && (uc <= 0xDFFF)) || (uc == 0))
                    {
                        *ep = str;
566
                        return NULL;
M
Max Bruckner 已提交
567 568 569 570 571 572 573 574 575
                    }

                    /* UTF16 surrogate pairs. */
                    if ((uc >= 0xD800) && (uc<=0xDBFF))
                    {
                        if ((ptr + 6) > end_ptr)
                        {
                            /* invalid */
                            *ep = str;
576
                            return NULL;
M
Max Bruckner 已提交
577 578 579 580 581
                        }
                        if ((ptr[1] != '\\') || (ptr[2] != 'u'))
                        {
                            /* missing second-half of surrogate. */
                            *ep = str;
582
                            return NULL;
M
Max Bruckner 已提交
583 584 585 586 587 588 589
                        }
                        uc2 = parse_hex4(ptr + 3);
                        ptr += 6; /* \uXXXX */
                        if ((uc2 < 0xDC00) || (uc2 > 0xDFFF))
                        {
                            /* invalid second-half of surrogate. */
                            *ep = str;
590
                            return NULL;
M
Max Bruckner 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
                        }
                        /* 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 */
                            *--ptr2 = ((uc | 0x80) & 0xBF);
                            uc >>= 6;
                        case 3:
                            /* 10xxxxxx */
                            *--ptr2 = ((uc | 0x80) & 0xBF);
                            uc >>= 6;
                        case 2:
                            /* 10xxxxxx */
                            *--ptr2 = ((uc | 0x80) & 0xBF);
                            uc >>= 6;
                        case 1:
                            /* depending on the length in bytes this determines the
                             * encoding ofthe first UTF8 byte */
                            *--ptr2 = (uc | firstByteMark[len]);
                    }
                    ptr2 += len;
                    break;
                default:
638
                    *ep = str;
639
                    return NULL;
M
Max Bruckner 已提交
640 641 642 643 644 645 646 647 648 649 650
            }
            ptr++;
        }
    }
    *ptr2 = '\0';
    if (*ptr == '\"')
    {
        ptr++;
    }

    return ptr;
K
Kevin Branigan 已提交
651 652 653
}

/* Render the cstring provided to an escaped version that can be printed. */
M
Max Bruckner 已提交
654
static char *print_string_ptr(const char *str, printbuffer *p)
K
Kevin Branigan 已提交
655
{
M
Max Bruckner 已提交
656 657 658
    const char *ptr = NULL;
    char *ptr2 = NULL;
    char *out = NULL;
M
Max Bruckner 已提交
659
    int len = 0;
M
Max Bruckner 已提交
660
    cjbool flag = false;
M
Max Bruckner 已提交
661
    unsigned char token = '\0';
M
Max Bruckner 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675

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

        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)
    {
        len = ptr - str;
        if (p)
        {
            out = ensure(p, len + 3);
        }
        else
        {
            out = (char*)cJSON_malloc(len + 3);
        }
        if (!out)
        {
706
            return NULL;
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 740 741 742
        }

        ptr2 = out;
        *ptr2++ = '\"';
        strcpy(ptr2, str);
        ptr2[len] = '\"';
        ptr2[len + 1] = '\0';

        return out;
    }

    ptr = str;
    /* calculate additional space that is needed for escaping */
    while ((token = *ptr) && ++len)
    {
        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
    {
        out = (char*)cJSON_malloc(len + 3);
    }
    if (!out)
    {
743
        return NULL;
M
Max Bruckner 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    }

    ptr2 = out;
    ptr = str;
    *ptr2++ = '\"';
    /* copy the string */
    while (*ptr)
    {
        if (((unsigned char)*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
        {
            /* 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 */
                    sprintf(ptr2, "u%04x", token);
                    ptr2 += 5;
                    break;
            }
        }
    }
    *ptr2++ = '\"';
    *ptr2++ = '\0';

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

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

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

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

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

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

    end = parse_value(c, skip(value), ep);
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
841
        return NULL;
M
Max Bruckner 已提交
842 843 844 845 846 847 848 849 850 851
    }

    /* 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;
852
            return NULL;
M
Max Bruckner 已提交
853 854 855 856 857 858 859 860
        }
    }
    if (return_parse_end)
    {
        *return_parse_end = end;
    }

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

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

/* Render a cJSON item/entity/structure to text. */
870
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
871 872 873 874
{
    return print_value(item, 0, 1, 0);
}

875
char *cJSON_PrintUnformatted(const cJSON *item)
876 877 878
{
    return print_value(item, 0, 0, 0);
}
879

M
Max Bruckner 已提交
880
char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, cjbool fmt)
881
{
M
Max Bruckner 已提交
882 883
    printbuffer p;
    p.buffer = (char*)cJSON_malloc(prebuffer);
884 885
    if (!p.buffer)
    {
886
        return NULL;
887
    }
M
Max Bruckner 已提交
888 889
    p.length = prebuffer;
    p.offset = 0;
890
    p.noalloc = false;
M
Max Bruckner 已提交
891 892

    return print_value(item, 0, fmt, &p);
893 894
}

895
int cJSON_PrintPreallocated(cJSON *item,char *buf, const int len, const cjbool fmt)
896 897 898 899 900
{
    printbuffer p;
    p.buffer = buf;
    p.length = len;
    p.offset = 0;
901
    p.noalloc = true;
K
Kyle Chisholm 已提交
902
    return print_value(item,0,fmt,&p) != NULL;
903
}
K
Kevin Branigan 已提交
904 905

/* Parser core - when encountering text, process appropriately. */
M
Max Bruckner 已提交
906
static const char *parse_value(cJSON *item, const char *value, const char **ep)
K
Kevin Branigan 已提交
907
{
M
Max Bruckner 已提交
908 909 910
    if (!value)
    {
        /* Fail on null. */
911
        return NULL;
M
Max Bruckner 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    }

    /* parse the different types of values */
    if (!strncmp(value, "null", 4))
    {
        item->type = cJSON_NULL;
        return value + 4;
    }
    if (!strncmp(value, "false", 5))
    {
        item->type = cJSON_False;
        return value + 5;
    }
    if (!strncmp(value, "true", 4))
    {
        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 已提交
948 949
    /* failure. */
    *ep = value;
950
    return NULL;
K
Kevin Branigan 已提交
951 952 953
}

/* Render a value to text. */
M
Max Bruckner 已提交
954
static char *print_value(const cJSON *item, int depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
955
{
956
    char *out = NULL;
M
Max Bruckner 已提交
957 958 959

    if (!item)
    {
960
        return NULL;
M
Max Bruckner 已提交
961 962 963
    }
    if (p)
    {
964
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        {
            case cJSON_NULL:
                out = ensure(p, 5);
                if (out)
                {
                    strcpy(out, "null");
                }
                break;
            case cJSON_False:
                out = ensure(p, 6);
                if (out)
                {
                    strcpy(out, "false");
                }
                break;
            case cJSON_True:
                out = ensure(p, 5);
                if (out)
                {
                    strcpy(out, "true");
                }
                break;
            case cJSON_Number:
                out = print_number(item, p);
                break;
            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;
        }
    }
    else
    {
1003
        switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
        {
            case cJSON_NULL:
                out = cJSON_strdup("null");
                break;
            case cJSON_False:
                out = cJSON_strdup("false");
                break;
            case cJSON_True:
                out = cJSON_strdup("true");
                break;
            case cJSON_Number:
                out = print_number(item, 0);
                break;
            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;
        }
    }

    return out;
K
Kevin Branigan 已提交
1030 1031 1032
}

/* Build an array from input text. */
1033
static const char *parse_array(cJSON *item,const char *value,const char **ep)
K
Kevin Branigan 已提交
1034
{
M
Max Bruckner 已提交
1035
    cJSON *child = NULL;
M
Max Bruckner 已提交
1036 1037 1038 1039
    if (*value != '[')
    {
        /* not an array! */
        *ep = value;
1040
        return NULL;
M
Max Bruckner 已提交
1041
    }
K
Kevin Branigan 已提交
1042

M
Max Bruckner 已提交
1043 1044 1045 1046 1047 1048 1049
    item->type = cJSON_Array;
    value = skip(value + 1);
    if (*value == ']')
    {
        /* empty array. */
        return value + 1;
    }
K
Kevin Branigan 已提交
1050

M
Max Bruckner 已提交
1051 1052 1053 1054
    item->child = child = cJSON_New_Item();
    if (!item->child)
    {
        /* memory fail */
1055
        return NULL;
M
Max Bruckner 已提交
1056 1057 1058 1059 1060
    }
    /* skip any spacing, get the value. */
    value = skip(parse_value(child, skip(value), ep));
    if (!value)
    {
1061
        return NULL;
M
Max Bruckner 已提交
1062
    }
K
Kevin Branigan 已提交
1063

M
Max Bruckner 已提交
1064 1065 1066
    /* loop through the comma separated array elements */
    while (*value == ',')
    {
M
Max Bruckner 已提交
1067
        cJSON *new_item = NULL;
M
Max Bruckner 已提交
1068 1069 1070
        if (!(new_item = cJSON_New_Item()))
        {
            /* memory fail */
1071
            return NULL;
M
Max Bruckner 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        }
        /* 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 */
1083
            return NULL;
M
Max Bruckner 已提交
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        }
    }

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

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

1096
    return NULL;
K
Kevin Branigan 已提交
1097 1098 1099
}

/* Render an array to text */
M
Max Bruckner 已提交
1100
static char *print_array(const cJSON *item, int depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1101
{
M
Max Bruckner 已提交
1102
    char **entries;
1103
    char *out = NULL;
M
Max Bruckner 已提交
1104 1105
    char *ptr = NULL;
    char *ret = NULL;
M
Max Bruckner 已提交
1106 1107 1108 1109
    int len = 5;
    cJSON *child = item->child;
    int numentries = 0;
    int i = 0;
M
Max Bruckner 已提交
1110
    cjbool fail = false;
M
Max Bruckner 已提交
1111
    size_t tmplen = 0;
K
Kevin Branigan 已提交
1112

M
Max Bruckner 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    /* 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
        {
            out = (char*)cJSON_malloc(3);
        }
        if (out)
        {
            strcpy(out,"[]");
        }

        return out;
    }

    if (p)
    {
        /* Compose the output array. */
        /* opening square bracket */
        i = p->offset;
        ptr = ensure(p, 1);
        if (!ptr)
        {
1147
            return NULL;
M
Max Bruckner 已提交
1148 1149 1150 1151 1152 1153 1154
        }
        *ptr = '[';
        p->offset++;

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

        /* Retrieve all the results: */
        child = item->child;
        while (child && !fail)
        {
            ret = print_value(child, depth + 1, fmt, 0);
            entries[i++] = ret;
            if (ret)
            {
                len += strlen(ret) + 2 + (fmt ? 1 : 0);
            }
            else
            {
M
Max Bruckner 已提交
1209
                fail = true;
M
Max Bruckner 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
            }
            child = child->next;
        }

        /* If we didn't fail, try to malloc the output string */
        if (!fail)
        {
            out = (char*)cJSON_malloc(len);
        }
        /* If that fails, we fail. */
        if (!out)
        {
M
Max Bruckner 已提交
1222
            fail = true;
M
Max Bruckner 已提交
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        }

        /* 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);
1237
            return NULL;
M
Max Bruckner 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        }

        /* Compose the output array. */
        *out='[';
        ptr = out + 1;
        *ptr = '\0';
        for (i = 0; i < numentries; i++)
        {
            tmplen = strlen(entries[i]);
            memcpy(ptr, entries[i], tmplen);
            ptr += tmplen;
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
                if(fmt)
                {
                    *ptr++ = ' ';
                }
1256
                *ptr = '\0';
M
Max Bruckner 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265
            }
            cJSON_free(entries[i]);
        }
        cJSON_free(entries);
        *ptr++ = ']';
        *ptr++ = '\0';
    }

    return out;
K
Kevin Branigan 已提交
1266 1267 1268
}

/* Build an object from the text. */
M
Max Bruckner 已提交
1269
static const char *parse_object(cJSON *item, const char *value, const char **ep)
K
Kevin Branigan 已提交
1270
{
M
Max Bruckner 已提交
1271
    cJSON *child = NULL;
M
Max Bruckner 已提交
1272 1273 1274 1275
    if (*value != '{')
    {
        /* not an object! */
        *ep = value;
1276
        return NULL;
M
Max Bruckner 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    }

    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)
    {
1291
        return NULL;
M
Max Bruckner 已提交
1292 1293 1294 1295 1296
    }
    /* parse first key */
    value = skip(parse_string(child, skip(value), ep));
    if (!value)
    {
1297
        return NULL;
M
Max Bruckner 已提交
1298 1299 1300
    }
    /* use string as key, not value */
    child->string = child->valuestring;
1301
    child->valuestring = NULL;
M
Max Bruckner 已提交
1302 1303 1304 1305 1306

    if (*value != ':')
    {
        /* invalid object. */
        *ep = value;
1307
        return NULL;
M
Max Bruckner 已提交
1308 1309 1310 1311 1312
    }
    /* skip any spacing, get the value. */
    value = skip(parse_value(child, skip(value + 1), ep));
    if (!value)
    {
1313
        return NULL;
M
Max Bruckner 已提交
1314 1315 1316 1317
    }

    while (*value == ',')
    {
M
Max Bruckner 已提交
1318
        cJSON *new_item = NULL;
M
Max Bruckner 已提交
1319 1320 1321
        if (!(new_item = cJSON_New_Item()))
        {
            /* memory fail */
1322
            return NULL;
M
Max Bruckner 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331
        }
        /* 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)
        {
1332
            return NULL;
M
Max Bruckner 已提交
1333 1334 1335 1336
        }

        /* use string as key, not value */
        child->string = child->valuestring;
1337
        child->valuestring = NULL;
M
Max Bruckner 已提交
1338 1339 1340 1341 1342

        if (*value != ':')
        {
            /* invalid object. */
            *ep = value;
1343
            return NULL;
M
Max Bruckner 已提交
1344 1345 1346 1347 1348
        }
        /* skip any spacing, get the value. */
        value = skip(parse_value(child, skip(value + 1), ep));
        if (!value)
        {
1349
            return NULL;
M
Max Bruckner 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
        }
    }
    /* end of object */
    if (*value == '}')
    {
        return value + 1;
    }

    /* malformed */
    *ep = value;
1360
    return NULL;
K
Kevin Branigan 已提交
1361 1362 1363
}

/* Render an object to text. */
M
Max Bruckner 已提交
1364
static char *print_object(const cJSON *item, int depth, cjbool fmt, printbuffer *p)
K
Kevin Branigan 已提交
1365
{
1366 1367 1368
    char **entries = NULL;
    char **names = NULL;
    char *out = NULL;
M
Max Bruckner 已提交
1369 1370 1371
    char *ptr = NULL;
    char *ret = NULL;
    char *str = NULL;
M
Max Bruckner 已提交
1372 1373
    int len = 7;
    int i = 0;
M
Max Bruckner 已提交
1374
    int j = 0;
M
Max Bruckner 已提交
1375 1376
    cJSON *child = item->child;
    int numentries = 0;
M
Max Bruckner 已提交
1377
    cjbool fail = false;
M
Max Bruckner 已提交
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
    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
        {
            out = (char*)cJSON_malloc(fmt ? depth + 4 : 3);
        }
        if (!out)
        {
1400
            return NULL;
M
Max Bruckner 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
        }
        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)
        {
1425
            return NULL;
M
Max Bruckner 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
        }

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

        child = item->child;
        depth++;
        while (child)
        {
            if (fmt)
            {
                ptr = ensure(p, depth);
                if (!ptr)
                {
1445
                    return NULL;
M
Max Bruckner 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454
                }
                for (j = 0; j < depth; j++)
                {
                    *ptr++ = '\t';
                }
                p->offset += depth;
            }

            /* print key */
1455 1456 1457 1458
            if (!print_string_ptr(child->string, p))
            {
                return NULL;
            }
M
Max Bruckner 已提交
1459 1460 1461 1462 1463 1464
            p->offset = update(p);

            len = fmt ? 2 : 1;
            ptr = ensure(p, len);
            if (!ptr)
            {
1465
                return NULL;
M
Max Bruckner 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474
            }
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
            p->offset+=len;

            /* print value */
K
Kyle Chisholm 已提交
1475 1476 1477 1478
            if (!print_value(child, depth, fmt, p))
            {
                return NULL;
            };
M
Max Bruckner 已提交
1479 1480 1481 1482 1483 1484 1485
            p->offset = update(p);

            /* print comma if not last */
            len = (fmt ? 1 : 0) + (child->next ? 1 : 0);
            ptr = ensure(p, len + 1);
            if (!ptr)
            {
1486
                return NULL;
M
Max Bruckner 已提交
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
            }
            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)
        {
1506
            return NULL;
M
Max Bruckner 已提交
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
        }
        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 */
        entries = (char**)cJSON_malloc(numentries * sizeof(char*));
        if (!entries)
        {
1525
            return NULL;
M
Max Bruckner 已提交
1526 1527 1528 1529 1530
        }
        names = (char**)cJSON_malloc(numentries * sizeof(char*));
        if (!names)
        {
            cJSON_free(entries);
1531
            return NULL;
M
Max Bruckner 已提交
1532
        }
1533 1534
        memset(entries, '\0', sizeof(char*) * numentries);
        memset(names, '\0', sizeof(char*) * numentries);
M
Max Bruckner 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552

        /* Collect all the results into our arrays: */
        child = item->child;
        depth++;
        if (fmt)
        {
            len += depth;
        }
        while (child && !fail)
        {
            names[i] = str = print_string_ptr(child->string, 0); /* print key */
            entries[i++] = ret = print_value(child, depth, fmt, 0);
            if (str && ret)
            {
                len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0);
            }
            else
            {
M
Max Bruckner 已提交
1553
                fail = true;
M
Max Bruckner 已提交
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
            }
            child = child->next;
        }

        /* Try to allocate the output string */
        if (!fail)
        {
            out = (char*)cJSON_malloc(len);
        }
        if (!out)
        {
M
Max Bruckner 已提交
1565
            fail = true;
M
Max Bruckner 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
        }

        /* 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);
1585
            return NULL;
M
Max Bruckner 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594
        }

        /* Compose the output: */
        *out = '{';
        ptr = out + 1;
        if (fmt)
        {
            *ptr++ = '\n';
        }
1595
        *ptr = '\0';
M
Max Bruckner 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
        for (i = 0; i < numentries; i++)
        {
            if (fmt)
            {
                for (j = 0; j < depth; j++)
                {
                    *ptr++='\t';
                }
            }
            tmplen = strlen(names[i]);
            memcpy(ptr, names[i], tmplen);
            ptr += tmplen;
            *ptr++ = ':';
            if (fmt)
            {
                *ptr++ = '\t';
            }
            strcpy(ptr, entries[i]);
            ptr += strlen(entries[i]);
            if (i != (numentries - 1))
            {
                *ptr++ = ',';
            }
            if (fmt)
            {
                *ptr++ = '\n';
            }
1623
            *ptr = '\0';
M
Max Bruckner 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
            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 已提交
1642 1643 1644
}

/* Get Array size/item / object item. */
1645
int    cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
{
    cJSON *c = array->child;
    int i = 0;
    while(c)
    {
        i++;
        c = c->next;
    }
    return i;
}

1657
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1658
{
1659
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1660 1661 1662 1663 1664 1665 1666 1667 1668
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1669
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1670
{
1671
    cJSON *c = object ? object->child : NULL;
M
Max Bruckner 已提交
1672 1673 1674 1675 1676 1677 1678
    while (c && cJSON_strcasecmp(c->string, string))
    {
        c = c->next;
    }
    return c;
}

M
Max Bruckner 已提交
1679
cjbool cJSON_HasObjectItem(const cJSON *object,const char *string)
M
Max Bruckner 已提交
1680 1681 1682
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1683 1684

/* Utility for array list handling. */
M
Max Bruckner 已提交
1685 1686 1687 1688 1689 1690
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1691
/* Utility for handling references. */
1692
static cJSON *create_reference(const cJSON *item)
M
Max Bruckner 已提交
1693 1694 1695 1696
{
    cJSON *ref = cJSON_New_Item();
    if (!ref)
    {
1697
        return NULL;
M
Max Bruckner 已提交
1698 1699
    }
    memcpy(ref, item, sizeof(cJSON));
1700
    ref->string = NULL;
M
Max Bruckner 已提交
1701
    ref->type |= cJSON_IsReference;
1702
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1703 1704
    return ref;
}
K
Kevin Branigan 已提交
1705 1706

/* Add item to array/object. */
M
Max Bruckner 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
void   cJSON_AddItemToArray(cJSON *array, cJSON *item)
{
    cJSON *c = array->child;
    if (!item)
    {
        return;
    }
    if (!c)
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1722
        while (c->next)
M
Max Bruckner 已提交
1723 1724 1725 1726 1727 1728 1729
        {
            c = c->next;
        }
        suffix_object(c, item);
    }
}

M
Max Bruckner 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
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);
    }
    item->string = cJSON_strdup(string);

    cJSON_AddItemToArray(object,item);
}

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
/* 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);
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1763 1764 1765 1766 1767
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    cJSON_AddItemToArray(array, create_reference(item));
}

1768 1769 1770 1771 1772
void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
    cJSON_AddItemToObject(object, string, create_reference(item));
}

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1784
        return NULL;
1785
    }
1786
    if (c->prev)
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
    {
        /* 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 */
1800
    c->prev = c->next = NULL;
1801 1802 1803

    return c;
}
K
Kevin Branigan 已提交
1804

1805 1806 1807 1808 1809
void cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
    int i = 0;
    cJSON *c = object->child;
    while (c && cJSON_strcasecmp(c->string,string))
    {
        i++;
        c = c->next;
    }
    if (c)
    {
        return cJSON_DetachItemFromArray(object, i);
    }

1824
    return NULL;
1825 1826
}

1827 1828 1829 1830
void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1831 1832

/* Replace array/object items with new ones. */
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
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;
    }
}

1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    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;
    }
1885
    c->next = c->prev = NULL;
1886 1887 1888
    cJSON_Delete(c);
}

1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
    int i = 0;
    cJSON *c = object->child;
    while(c && cJSON_strcasecmp(c->string, string))
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1900 1901 1902 1903 1904 1905
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
             cJSON_free(newitem->string);
        }

1906 1907 1908 1909
        newitem->string = cJSON_strdup(string);
        cJSON_ReplaceItemInArray(object, i, newitem);
    }
}
K
Kevin Branigan 已提交
1910 1911

/* Create basic types: */
M
Max Bruckner 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
cJSON *cJSON_CreateNull(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

M
Max Bruckner 已提交
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
cJSON *cJSON_CreateTrue(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

M
Max Bruckner 已提交
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
cJSON *cJSON_CreateFalse(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1945
cJSON *cJSON_CreateBool(cjbool b)
M
Max Bruckner 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
cJSON *cJSON_CreateNumber(double num)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
        item->valueint = (int)num;
    }

    return item;
}

M
Max Bruckner 已提交
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
cJSON *cJSON_CreateString(const char *string)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type = cJSON_String;
        item->valuestring = cJSON_strdup(string);
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1979
            return NULL;
M
Max Bruckner 已提交
1980 1981 1982 1983 1984 1985
        }
    }

    return item;
}

M
Max Bruckner 已提交
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
cJSON *cJSON_CreateArray(void)
{
    cJSON *item = cJSON_New_Item();
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

M
Max Bruckner 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
cJSON *cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item();
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
2007 2008

/* Create Arrays: */
M
Max Bruckner 已提交
2009 2010
cJSON *cJSON_CreateIntArray(const int *numbers, int count)
{
M
Max Bruckner 已提交
2011
    int i = 0;
2012 2013
    cJSON *n = NULL;
    cJSON *p = NULL;
M
Max Bruckner 已提交
2014 2015 2016 2017 2018 2019 2020
    cJSON *a = cJSON_CreateArray();
    for(i = 0; a && (i < count); i++)
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
2021
            return NULL;
M
Max Bruckner 已提交
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

M
Max Bruckner 已提交
2037 2038
cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
{
M
Max Bruckner 已提交
2039
    int i = 0;
2040 2041
    cJSON *n = NULL;
    cJSON *p = NULL;
M
Max Bruckner 已提交
2042 2043 2044 2045 2046 2047 2048
    cJSON *a = cJSON_CreateArray();
    for(i = 0; a && (i < count); i++)
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2049
            return NULL;
M
Max Bruckner 已提交
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2065 2066
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
M
Max Bruckner 已提交
2067
    int i = 0;
2068 2069
    cJSON *n = NULL;
    cJSON *p = NULL;
2070 2071 2072 2073 2074 2075 2076
    cJSON *a = cJSON_CreateArray();
    for(i = 0;a && (i < count); i++)
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
2077
            return NULL;
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2093 2094
cJSON *cJSON_CreateStringArray(const char **strings, int count)
{
M
Max Bruckner 已提交
2095
    int i = 0;
2096 2097
    cJSON *n = NULL;
    cJSON *p = NULL;
2098 2099 2100 2101 2102 2103 2104
    cJSON *a = cJSON_CreateArray();
    for (i = 0; a && (i < count); i++)
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2105
            return NULL;
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2120 2121

/* Duplication */
M
Max Bruckner 已提交
2122
cJSON *cJSON_Duplicate(const cJSON *item, cjbool recurse)
2123
{
M
Max Bruckner 已提交
2124 2125
    cJSON *newitem = NULL;
    cJSON *cptr = NULL;
2126
    cJSON *nptr = NULL;
M
Max Bruckner 已提交
2127
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2128 2129 2130 2131

    /* Bail on bad ptr */
    if (!item)
    {
2132
        return NULL;
M
Max Bruckner 已提交
2133 2134 2135 2136 2137
    }
    /* Create new item */
    newitem = cJSON_New_Item();
    if (!newitem)
    {
2138
        return NULL;
M
Max Bruckner 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
        newitem->valuestring = cJSON_strdup(item->valuestring);
        if (!newitem->valuestring)
        {
            cJSON_Delete(newitem);
2150
            return NULL;
M
Max Bruckner 已提交
2151 2152 2153 2154 2155 2156 2157 2158
        }
    }
    if (item->string)
    {
        newitem->string = cJSON_strdup(item->string);
        if (!newitem->string)
        {
            cJSON_Delete(newitem);
2159
            return NULL;
M
Max Bruckner 已提交
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
    cptr = item->child;
    while (cptr)
    {
        newchild = cJSON_Duplicate(cptr, 1); /* Duplicate (with recurse) each item in the ->next chain */
        if (!newchild)
        {
            cJSON_Delete(newitem);
2175
            return NULL;
M
Max Bruckner 已提交
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
        }
        if (nptr)
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
            nptr->next = newchild;
            newchild->prev = nptr;
            nptr = newchild;
        }
        else
        {
            /* Set newitem->child and move to it */
            newitem->child = newchild; nptr = newchild;
        }
        cptr = cptr->next;
    }

    return newitem;
2193
}
2194 2195 2196

void cJSON_Minify(char *json)
{
M
Max Bruckner 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    char *into = json;
    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. */
            *into++ = *json++;
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
                    *into++=*json++;
                }
                *into++ = *json++;
            }
            *into++ = *json++;
        }
        else
        {
            /* All other characters. */
            *into++ = *json++;
        }
    }

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