cJSON.c 54.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
/*
  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. */

26
#pragma GCC visibility push(default)
K
Kevin Branigan 已提交
27 28 29 30 31 32 33
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
34 35
#pragma GCC visibility pop

K
Kevin Branigan 已提交
36 37
#include "cJSON.h"

M
Max Bruckner 已提交
38
/* define our own boolean type */
39 40
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)
M
Max Bruckner 已提交
41

42
static const unsigned char *global_ep = NULL;
K
Kevin Branigan 已提交
43

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

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

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

    return version;
}

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

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

84 85 86 87 88 89 90 91
typedef struct internal_hooks
{
    void *(*allocate)(size_t size);
    void (*deallocate)(void *pointer);
    void *(*reallocate)(void *pointer, size_t size);
} internal_hooks;

static internal_hooks global_hooks = { malloc, free, realloc };
K
Kevin Branigan 已提交
92

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

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

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

    return copy;
K
Kevin Branigan 已提交
111 112
}

113
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
K
Kevin Branigan 已提交
114
{
M
Max Bruckner 已提交
115
    if (hooks == NULL)
M
Max Bruckner 已提交
116 117
    {
        /* Reset hooks */
118 119 120
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
K
Kevin Branigan 已提交
121 122 123
        return;
    }

124
    global_hooks.allocate = malloc;
M
Max Bruckner 已提交
125 126
    if (hooks->malloc_fn != NULL)
    {
127
        global_hooks.allocate = hooks->malloc_fn;
M
Max Bruckner 已提交
128 129
    }

130
    global_hooks.deallocate = free;
M
Max Bruckner 已提交
131 132
    if (hooks->free_fn != NULL)
    {
133
        global_hooks.deallocate = hooks->free_fn;
M
Max Bruckner 已提交
134 135 136
    }

    /* use realloc only if both free and malloc are used */
137 138
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
M
Max Bruckner 已提交
139
    {
140
        global_hooks.reallocate = realloc;
M
Max Bruckner 已提交
141
    }
K
Kevin Branigan 已提交
142 143 144
}

/* Internal constructor. */
145
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
K
Kevin Branigan 已提交
146
{
147
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
M
Max Bruckner 已提交
148 149
    if (node)
    {
150
        memset(node, '\0', sizeof(cJSON));
M
Max Bruckner 已提交
151 152 153
    }

    return node;
K
Kevin Branigan 已提交
154 155 156
}

/* Delete a cJSON structure. */
157
CJSON_PUBLIC(void) cJSON_Delete(cJSON *c)
K
Kevin Branigan 已提交
158
{
M
Max Bruckner 已提交
159
    cJSON *next = NULL;
M
Max Bruckner 已提交
160 161 162 163 164 165 166 167 168
    while (c)
    {
        next = c->next;
        if (!(c->type & cJSON_IsReference) && c->child)
        {
            cJSON_Delete(c->child);
        }
        if (!(c->type & cJSON_IsReference) && c->valuestring)
        {
169
            global_hooks.deallocate(c->valuestring);
M
Max Bruckner 已提交
170 171 172
        }
        if (!(c->type & cJSON_StringIsConst) && c->string)
        {
173
            global_hooks.deallocate(c->string);
M
Max Bruckner 已提交
174
        }
175
        global_hooks.deallocate(c);
M
Max Bruckner 已提交
176 177
        c = next;
    }
K
Kevin Branigan 已提交
178 179 180
}

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

186
    if (input == NULL)
187 188 189 190
    {
        return NULL;
    }

191 192
    number = strtod((const char*)input, (char**)&after_end);
    if (input == after_end)
M
Max Bruckner 已提交
193
    {
194
        return NULL; /* parse_error */
M
Max Bruckner 已提交
195 196
    }

197
    item->valuedouble = number;
M
Max Bruckner 已提交
198

199
    /* use saturation in case of overflow */
200
    if (number >= INT_MAX)
201 202 203
    {
        item->valueint = INT_MAX;
    }
204
    else if (number <= INT_MIN)
205 206 207 208 209
    {
        item->valueint = INT_MIN;
    }
    else
    {
210
        item->valueint = (int)number;
211
    }
212

M
Max Bruckner 已提交
213 214
    item->type = cJSON_Number;

215
    return after_end;
K
Kevin Branigan 已提交
216 217
}

218
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
219
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
        object->valueint = cJSON_Number;
    }

    return object->valuedouble = number;
}

M
Max Bruckner 已提交
237 238
typedef struct
{
239
    unsigned char *buffer;
240 241
    size_t length;
    size_t offset;
242
    cJSON_bool noalloc;
M
Max Bruckner 已提交
243
} printbuffer;
244

M
Max Bruckner 已提交
245
/* realloc printbuffer if necessary to have at least "needed" bytes more */
246
static unsigned char* ensure(printbuffer * const p, size_t needed, const internal_hooks * const hooks)
247
{
248
    unsigned char *newbuffer = NULL;
249 250
    size_t newsize = 0;

251
    if ((p == NULL) || (p->buffer == NULL))
252 253 254 255 256
    {
        return NULL;
    }

    if (needed > INT_MAX)
M
Max Bruckner 已提交
257
    {
258
        /* sizes bigger than INT_MAX are currently not supported */
259
        return NULL;
M
Max Bruckner 已提交
260
    }
261

M
Max Bruckner 已提交
262 263 264 265 266 267
    needed += p->offset;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

268 269 270 271
    if (p->noalloc) {
        return NULL;
    }

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    /* calculate new buffer size */
    newsize = needed * 2;
    if (newsize > INT_MAX)
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }

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

            return NULL;
        }
        if (newbuffer)
        {
306
            memcpy(newbuffer, p->buffer, p->offset + 1);
M
Max Bruckner 已提交
307
        }
308
        hooks->deallocate(p->buffer);
M
Max Bruckner 已提交
309 310 311 312 313
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
314 315
}

316 317
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
K
Kevin Branigan 已提交
318
{
319 320
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
M
Max Bruckner 已提交
321
    {
322
        return;
M
Max Bruckner 已提交
323
    }
324
    buffer_pointer = buffer->buffer + buffer->offset;
M
Max Bruckner 已提交
325

326
    buffer->offset += strlen((const char*)buffer_pointer);
327 328
}

329
/* Removes trailing zeroes from the end of a printed number */
330
static cJSON_bool trim_trailing_zeroes(printbuffer * const buffer)
K
Kevin Branigan 已提交
331
{
332 333 334 335 336
    size_t offset = 0;
    unsigned char *content = NULL;

    if ((buffer == NULL) || (buffer->buffer == NULL) || (buffer->offset < 1))
    {
337
        return false;
338 339 340 341 342 343
    }

    offset = buffer->offset - 1;
    content = buffer->buffer;

    while ((offset > 0) && (content[offset] == '0'))
M
Max Bruckner 已提交
344
    {
345
        offset--;
M
Max Bruckner 已提交
346
    }
347 348 349 350 351 352 353
    if ((offset > 0) && (content[offset] == '.'))
    {
        offset--;
    }

    offset++;
    content[offset] = '\0';
M
Max Bruckner 已提交
354

355 356
    buffer->offset = offset;

357
    return true;
358 359 360
}

/* Render the number nicely from the given item into a string. */
361
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
362
{
M
Max Bruckner 已提交
363
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
364
    double d = item->valuedouble;
365
    int length = 0;
366
    cJSON_bool trim_zeroes = true; /* should at the end be removed? */
M
Max Bruckner 已提交
367

M
Max Bruckner 已提交
368
    if (output_buffer == NULL)
M
Max Bruckner 已提交
369
    {
370
        return false;
M
Max Bruckner 已提交
371
    }
M
Max Bruckner 已提交
372

373 374
    /* This is a nice tradeoff. */
    output_pointer = ensure(output_buffer, 64, hooks);
375
    if (output_pointer == NULL)
M
Max Bruckner 已提交
376
    {
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        return false;
    }

    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
        length = sprintf((char*)output_pointer, "null");
    }
    else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
    {
        /* integer */
        length = sprintf((char*)output_pointer, "%.0f", d);
        trim_zeroes = false; /* don't remove zeroes for "big integers" */
    }
    else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
    {
        length = sprintf((char*)output_pointer, "%e", d);
        trim_zeroes = false; /* don't remove zeroes in engineering notation */
    }
    else
    {
        length = sprintf((char*)output_pointer, "%f", d);
M
Max Bruckner 已提交
399
    }
400

401 402 403
    /* sprintf failed */
    if (length < 0)
    {
404
        return false;
405 406 407 408
    }

    output_buffer->offset += (size_t)length;

409 410 411 412 413
    if (trim_zeroes)
    {
        return trim_trailing_zeroes(output_buffer);
    }

414
    return true;
K
Kevin Branigan 已提交
415 416
}

M
Max Bruckner 已提交
417
/* parse 4 digit hexadecimal number */
418
static unsigned parse_hex4(const unsigned char * const input)
419
{
M
Max Bruckner 已提交
420
    unsigned int h = 0;
421
    size_t i = 0;
M
Max Bruckner 已提交
422

423
    for (i = 0; i < 4; i++)
M
Max Bruckner 已提交
424
    {
425
        /* parse digit */
426
        if ((input[i] >= '0') && (input[i] <= '9'))
427
        {
428
            h += (unsigned int) input[i] - '0';
429
        }
430
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
431
        {
432
            h += (unsigned int) 10 + input[i] - 'A';
433
        }
434
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
435
        {
436
            h += (unsigned int) 10 + input[i] - 'a';
437 438 439 440 441
        }
        else /* invalid */
        {
            return 0;
        }
M
Max Bruckner 已提交
442

443 444 445 446 447
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
448 449 450
    }

    return h;
451 452
}

453 454
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
455
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer, const unsigned char **error_pointer)
M
Max Bruckner 已提交
456
{
457 458 459
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
460
    unsigned char utf8_length = 0;
461
    unsigned char utf8_position = 0;
462
    unsigned char sequence_length = 0;
463
    unsigned char first_byte_mark = 0;
464 465 466 467 468 469 470

    if ((input_end - first_sequence) < 6)
    {
        /* input ends unexpectedly */
        *error_pointer = first_sequence;
        goto fail;
    }
M
Max Bruckner 已提交
471

472 473 474
    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

475 476
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
477
    {
478
        *error_pointer = first_sequence;
479
        goto fail;
M
Max Bruckner 已提交
480
    }
M
Max Bruckner 已提交
481

482 483
    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
M
Max Bruckner 已提交
484
    {
485 486 487 488 489
        const unsigned char *second_sequence = first_sequence + 6;
        unsigned int second_code = 0;
        sequence_length = 12; /* \uXXXX\uXXXX */

        if ((input_end - second_sequence) < 6)
M
Max Bruckner 已提交
490
        {
491 492 493
            /* input ends unexpectedly */
            *error_pointer = first_sequence;
            goto fail;
M
Max Bruckner 已提交
494
        }
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

        if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
        {
            /* missing second half of the surrogate pair */
            *error_pointer = first_sequence;
            goto fail;
        }

        /* get the second utf16 sequence */
        second_code = parse_hex4(second_sequence + 2);
        /* check that the code is valid */
        if ((second_code < 0xDC00) || (second_code > 0xDFFF))
        {
            /* invalid second half of the surrogate pair */
            *error_pointer = first_sequence;
            goto fail;
        }


        /* calculate the unicode codepoint from the surrogate pair */
        codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
    }
    else
    {
        sequence_length = 6; /* \uXXXX */
        codepoint = first_code;
M
Max Bruckner 已提交
521
    }
M
Max Bruckner 已提交
522

523 524 525 526 527 528 529 530 531 532 533 534
    /* encode as UTF-8
     * takes at maximum 4 bytes to encode:
     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
    if (codepoint < 0x80)
    {
        /* normal ascii, encoding 0xxxxxxx */
        utf8_length = 1;
    }
    else if (codepoint < 0x800)
    {
        /* two bytes, encoding 110xxxxx 10xxxxxx */
        utf8_length = 2;
535
        first_byte_mark = 0xC0; /* 11000000 */
536 537 538 539 540
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
541
        first_byte_mark = 0xE0; /* 11100000 */
542 543 544 545 546
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
547
        first_byte_mark = 0xF0; /* 11110000 */
548 549
    }
    else
M
Max Bruckner 已提交
550
    {
551 552
        /* invalid unicode codepoint */
        *error_pointer = first_sequence;
553
        goto fail;
M
Max Bruckner 已提交
554 555
    }

556
    /* encode as utf8 */
557 558 559 560 561
    for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
    {
        /* 10xxxxxx */
        (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
        codepoint >>= 6;
562
    }
563 564 565 566 567 568 569 570
    /* encode first byte */
    if (utf8_length > 1)
    {
        (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
    }
    else
    {
        (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
571
    }
572

573 574 575 576 577 578 579 580 581
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
582
static const unsigned char *parse_string(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
583 584 585 586 587 588 589 590 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
{
    const unsigned char *input_pointer = input + 1;
    const unsigned char *input_end = input + 1;
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
    if (*input != '\"')
    {
        *error_pointer = input;
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
        while ((*input_end != '\"') && (*input_end != '\0'))
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
                if (input_end[1] == '\0')
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
        if (*input_end == '\0')
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
        allocation_length = (size_t) (input_end - input) - skipped_bytes;
622
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof('\0'));
623 624 625 626 627 628 629
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
630
    /* loop through the string literal */
631
    while (input_pointer < input_end)
M
Max Bruckner 已提交
632
    {
633
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
634
        {
635
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
636 637 638 639
        }
        /* escape sequence */
        else
        {
640
            unsigned char sequence_length = 2;
641
            switch (input_pointer[1])
M
Max Bruckner 已提交
642 643
            {
                case 'b':
644
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
645 646
                    break;
                case 'f':
647
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
648 649
                    break;
                case 'n':
650
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
651 652
                    break;
                case 'r':
653
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
654 655
                    break;
                case 't':
656
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
657
                    break;
658 659 660
                case '\"':
                case '\\':
                case '/':
661
                    *output_pointer++ = input_pointer[1];
662
                    break;
663 664

                /* UTF-16 literal */
M
Max Bruckner 已提交
665
                case 'u':
666 667
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer, error_pointer);
                    if (sequence_length == 0)
M
Max Bruckner 已提交
668
                    {
669
                        /* failed to convert UTF16-literal to UTF-8 */
670
                        goto fail;
M
Max Bruckner 已提交
671 672
                    }
                    break;
673

M
Max Bruckner 已提交
674
                default:
675
                    *error_pointer = input_pointer;
676
                    goto fail;
M
Max Bruckner 已提交
677
            }
678
            input_pointer += sequence_length;
M
Max Bruckner 已提交
679 680
        }
    }
681 682 683

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

685
    item->type = cJSON_String;
686
    item->valuestring = (char*)output;
687

688
    return input_end + 1;
689 690

fail:
691
    if (output != NULL)
692
    {
693
        hooks->deallocate(output);
694 695 696
    }

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

/* Render the cstring provided to an escaped version that can be printed. */
700
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
701
{
702 703 704
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
705 706 707
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
708

709
    if (output_buffer == NULL)
M
Max Bruckner 已提交
710
    {
711
        return false;
M
Max Bruckner 已提交
712 713 714
    }

    /* empty string */
715
    if (input == NULL)
M
Max Bruckner 已提交
716
    {
717
        output = ensure(output_buffer, sizeof("\"\""), hooks);
718
        if (output == NULL)
M
Max Bruckner 已提交
719
        {
720
            return false;
M
Max Bruckner 已提交
721
        }
722
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
723

724
        return true;
M
Max Bruckner 已提交
725 726 727
    }

    /* set "flag" to 1 if something needs to be escaped */
728
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
729
    {
M
Max Bruckner 已提交
730
        if (strchr("\"\\\b\f\n\r\t", *input_pointer))
M
Max Bruckner 已提交
731
        {
M
Max Bruckner 已提交
732 733
            /* one character escape sequence */
            escape_characters++;
M
Max Bruckner 已提交
734
        }
M
Max Bruckner 已提交
735
        else if (*input_pointer < 32)
M
Max Bruckner 已提交
736
        {
M
Max Bruckner 已提交
737 738
            /* UTF-16 escape sequence uXXXX */
            escape_characters += 5;
M
Max Bruckner 已提交
739 740
        }
    }
M
Max Bruckner 已提交
741
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
742

743
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
744
    if (output == NULL)
M
Max Bruckner 已提交
745
    {
746
        return false;
M
Max Bruckner 已提交
747 748
    }

M
Max Bruckner 已提交
749 750
    /* no characters have to be escaped */
    if (escape_characters == 0)
M
Max Bruckner 已提交
751
    {
M
Max Bruckner 已提交
752 753 754 755 756
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

757
        return true;
M
Max Bruckner 已提交
758 759
    }

M
Max Bruckner 已提交
760 761
    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
762
    /* copy the string */
M
Max Bruckner 已提交
763
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
M
Max Bruckner 已提交
764
    {
765
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
766 767
        {
            /* normal character, copy */
M
Max Bruckner 已提交
768
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
769 770 771 772
        }
        else
        {
            /* character needs to be escaped */
773
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
774
            switch (*input_pointer)
M
Max Bruckner 已提交
775 776
            {
                case '\\':
M
Max Bruckner 已提交
777
                    *output_pointer = '\\';
M
Max Bruckner 已提交
778 779
                    break;
                case '\"':
M
Max Bruckner 已提交
780
                    *output_pointer = '\"';
M
Max Bruckner 已提交
781 782
                    break;
                case '\b':
M
Max Bruckner 已提交
783
                    *output_pointer = 'b';
M
Max Bruckner 已提交
784 785
                    break;
                case '\f':
M
Max Bruckner 已提交
786
                    *output_pointer = 'f';
M
Max Bruckner 已提交
787 788
                    break;
                case '\n':
M
Max Bruckner 已提交
789
                    *output_pointer = 'n';
M
Max Bruckner 已提交
790 791
                    break;
                case '\r':
M
Max Bruckner 已提交
792
                    *output_pointer = 'r';
M
Max Bruckner 已提交
793 794
                    break;
                case '\t':
M
Max Bruckner 已提交
795
                    *output_pointer = 't';
M
Max Bruckner 已提交
796 797 798
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
799 800
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
801 802 803 804
                    break;
            }
        }
    }
M
Max Bruckner 已提交
805 806
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
807

808
    return true;
K
Kevin Branigan 已提交
809
}
M
Max Bruckner 已提交
810

M
Max Bruckner 已提交
811
/* Invoke print_string_ptr (which is useful) on an item. */
812
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
813
{
814
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
815
}
K
Kevin Branigan 已提交
816 817

/* Predeclare these prototypes. */
818
static const unsigned char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const ep, const internal_hooks * const hooks);
819
static cJSON_bool print_value(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
820
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
821
static cJSON_bool print_array(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
822
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
823
static cJSON_bool print_object(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
K
Kevin Branigan 已提交
824 825

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
826
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
827
{
828
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
829 830 831 832 833 834
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
835 836

/* Parse an object - create a new root, and populate. */
837
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
K
Kevin Branigan 已提交
838
{
839
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
840
    /* use global error pointer if no specific one was given */
841
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
842
    cJSON *c = cJSON_New_Item(&global_hooks);
843
    *ep = NULL;
M
Max Bruckner 已提交
844 845
    if (!c) /* memory fail */
    {
846
        return NULL;
M
Max Bruckner 已提交
847 848
    }

849
    end = parse_value(c, skip_whitespace((const unsigned char*)value), ep, &global_hooks);
M
Max Bruckner 已提交
850 851 852 853
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
854
        return NULL;
M
Max Bruckner 已提交
855 856 857 858 859
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
860
        end = skip_whitespace(end);
M
Max Bruckner 已提交
861 862 863 864
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
865
            return NULL;
M
Max Bruckner 已提交
866 867 868 869
        }
    }
    if (return_parse_end)
    {
870
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
871 872 873
    }

    return c;
K
Kevin Branigan 已提交
874
}
M
Max Bruckner 已提交
875

876
/* Default options for cJSON_Parse */
877
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
M
Max Bruckner 已提交
878 879 880
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
881

M
Max Bruckner 已提交
882 883
#define min(a, b) ((a < b) ? a : b)

884
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
885 886 887 888 889 890 891
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
892
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
893 894 895 896 897 898
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
899
    if (!print_value(item, 0, format, buffer, hooks))
M
Max Bruckner 已提交
900 901 902
    {
        goto fail;
    }
903
    update_offset(buffer);
M
Max Bruckner 已提交
904 905

    /* copy the buffer over to a new one */
906
    printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
M
Max Bruckner 已提交
907 908 909 910 911 912 913 914
    if (printed == NULL)
    {
        goto fail;
    }
    strncpy((char*)printed, (char*)buffer->buffer, min(buffer->length, buffer->offset + 1));
    printed[buffer->offset] = '\0'; /* just to be sure */

    /* free the buffer */
915
    hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
916 917 918 919 920 921

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
922
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
923 924 925 926
    }

    if (printed != NULL)
    {
927
        hooks->deallocate(printed);
M
Max Bruckner 已提交
928 929 930 931 932
    }

    return NULL;
}

K
Kevin Branigan 已提交
933
/* Render a cJSON item/entity/structure to text. */
934
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
935
{
936
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
937 938
}

939
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
940
{
941
    return (char*)print(item, false, &global_hooks);
942
}
943

944
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
945
{
M
Max Bruckner 已提交
946
    printbuffer p;
M
Max Bruckner 已提交
947 948 949

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
950
        return NULL;
M
Max Bruckner 已提交
951 952
    }

953
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
954 955
    if (!p.buffer)
    {
956
        return NULL;
957
    }
M
Max Bruckner 已提交
958 959

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
960
    p.offset = 0;
961
    p.noalloc = false;
M
Max Bruckner 已提交
962

963 964 965 966 967 968
    if (!print_value(item, 0, fmt, &p, &global_hooks))
    {
        return NULL;
    }

    return (char*)p.buffer;
969 970
}

971
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
972 973
{
    printbuffer p;
M
Max Bruckner 已提交
974 975 976 977 978 979

    if (len < 0)
    {
        return false;
    }

980
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
981
    p.length = (size_t)len;
982
    p.offset = 0;
983
    p.noalloc = true;
984
    return print_value(item, 0, fmt, &p, &global_hooks);
985
}
K
Kevin Branigan 已提交
986 987

/* Parser core - when encountering text, process appropriately. */
988
static const unsigned  char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
989
{
990
    if (input == NULL)
M
Max Bruckner 已提交
991
    {
992
        return NULL; /* no input */
M
Max Bruckner 已提交
993 994 995
    }

    /* parse the different types of values */
996 997
    /* null */
    if (!strncmp((const char*)input, "null", 4))
M
Max Bruckner 已提交
998 999
    {
        item->type = cJSON_NULL;
1000
        return input + 4;
M
Max Bruckner 已提交
1001
    }
1002 1003
    /* false */
    if (!strncmp((const char*)input, "false", 5))
M
Max Bruckner 已提交
1004 1005
    {
        item->type = cJSON_False;
1006
        return input + 5;
M
Max Bruckner 已提交
1007
    }
1008 1009
    /* true */
    if (!strncmp((const char*)input, "true", 4))
M
Max Bruckner 已提交
1010 1011 1012
    {
        item->type = cJSON_True;
        item->valueint = 1;
1013
        return input + 4;
M
Max Bruckner 已提交
1014
    }
1015 1016
    /* string */
    if (*input == '\"')
M
Max Bruckner 已提交
1017
    {
1018
        return parse_string(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1019
    }
1020 1021
    /* number */
    if ((*input == '-') || ((*input >= '0') && (*input <= '9')))
M
Max Bruckner 已提交
1022
    {
1023
        return parse_number(item, input);
M
Max Bruckner 已提交
1024
    }
1025 1026
    /* array */
    if (*input == '[')
M
Max Bruckner 已提交
1027
    {
1028
        return parse_array(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1029
    }
1030 1031
    /* object */
    if (*input == '{')
M
Max Bruckner 已提交
1032
    {
1033
        return parse_object(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1034 1035
    }

M
Max Bruckner 已提交
1036
    /* failure. */
1037
    *error_pointer = input;
1038
    return NULL;
K
Kevin Branigan 已提交
1039 1040 1041
}

/* Render a value to text. */
1042
static cJSON_bool print_value(const cJSON * const item, const size_t depth, const cJSON_bool format,  printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1043
{
M
Max Bruckner 已提交
1044
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1045

M
Max Bruckner 已提交
1046
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1047
    {
1048
        return false;
M
Max Bruckner 已提交
1049
    }
M
Max Bruckner 已提交
1050 1051

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1052
    {
M
Max Bruckner 已提交
1053
        case cJSON_NULL:
1054
            output = ensure(output_buffer, 5, hooks);
1055
            if (output == NULL)
M
Max Bruckner 已提交
1056
            {
1057
                return false;
M
Max Bruckner 已提交
1058
            }
1059 1060 1061
            strcpy((char*)output, "null");
            return true;

M
Max Bruckner 已提交
1062
        case cJSON_False:
1063
            output = ensure(output_buffer, 6, hooks);
1064
            if (output == NULL)
M
Max Bruckner 已提交
1065
            {
1066
                return false;
M
Max Bruckner 已提交
1067
            }
1068 1069 1070
            strcpy((char*)output, "false");
            return true;

M
Max Bruckner 已提交
1071
        case cJSON_True:
1072
            output = ensure(output_buffer, 5, hooks);
1073
            if (output == NULL)
M
Max Bruckner 已提交
1074
            {
1075
                return false;
M
Max Bruckner 已提交
1076
            }
1077 1078 1079
            strcpy((char*)output, "true");
            return true;

M
Max Bruckner 已提交
1080
        case cJSON_Number:
1081
            return print_number(item, output_buffer, hooks);
1082

M
Max Bruckner 已提交
1083
        case cJSON_Raw:
M
Max Bruckner 已提交
1084
        {
M
Max Bruckner 已提交
1085 1086
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1087
            {
M
Max Bruckner 已提交
1088
                if (!output_buffer->noalloc)
1089
                {
1090
                    hooks->deallocate(output_buffer->buffer);
1091
                }
1092
                return false;
M
Max Bruckner 已提交
1093
            }
1094

M
Max Bruckner 已提交
1095
            raw_length = strlen(item->valuestring) + sizeof('\0');
1096
            output = ensure(output_buffer, raw_length, hooks);
1097
            if (output == NULL)
M
Max Bruckner 已提交
1098
            {
1099
                return false;
1100
            }
1101 1102
            memcpy(output, item->valuestring, raw_length);
            return true;
M
Max Bruckner 已提交
1103
        }
1104

M
Max Bruckner 已提交
1105
        case cJSON_String:
1106
            return print_string(item, output_buffer, hooks);
1107

M
Max Bruckner 已提交
1108
        case cJSON_Array:
1109
            return print_array(item, depth, format, output_buffer, hooks);
1110

M
Max Bruckner 已提交
1111
        case cJSON_Object:
1112
            return print_object(item, depth, format, output_buffer, hooks);
1113

M
Max Bruckner 已提交
1114
        default:
1115
            return false;
M
Max Bruckner 已提交
1116
    }
K
Kevin Branigan 已提交
1117 1118 1119
}

/* Build an array from input text. */
1120
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1121
{
1122
    cJSON *head = NULL; /* head of the linked list */
1123 1124
    cJSON *current_item = NULL;

1125
    if (*input != '[')
M
Max Bruckner 已提交
1126
    {
1127
        /* not an array */
1128
        *error_pointer = input;
1129
        goto fail;
M
Max Bruckner 已提交
1130
    }
K
Kevin Branigan 已提交
1131

M
Max Bruckner 已提交
1132
    input = skip_whitespace(input + 1);
1133
    if (*input == ']')
M
Max Bruckner 已提交
1134
    {
1135
        /* empty array */
1136
        goto success;
M
Max Bruckner 已提交
1137
    }
K
Kevin Branigan 已提交
1138

1139
    /* step back to character in front of the first element */
1140
    input--;
M
Max Bruckner 已提交
1141
    /* loop through the comma separated array elements */
1142
    do
M
Max Bruckner 已提交
1143
    {
1144
        /* allocate next item */
1145
        cJSON *new_item = cJSON_New_Item(hooks);
1146
        if (new_item == NULL)
M
Max Bruckner 已提交
1147
        {
1148
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1149
        }
1150 1151 1152

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1153
        {
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
        }

        /* parse next value */
M
Max Bruckner 已提交
1166
        input = skip_whitespace(input + 1);
1167
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1168
        input = skip_whitespace(input);
1169
        if (input == NULL)
1170 1171
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1172 1173
        }
    }
1174
    while (*input == ',');
M
Max Bruckner 已提交
1175

1176
    if (*input != ']')
M
Max Bruckner 已提交
1177
    {
1178 1179
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1180 1181
    }

1182 1183
success:
    item->type = cJSON_Array;
1184
    item->child = head;
1185

1186
    return input + 1;
K
Kevin Branigan 已提交
1187

1188
fail:
1189
    if (head != NULL)
1190
    {
1191
        cJSON_Delete(head);
1192 1193
    }

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

/* Render an array to text */
1198
static cJSON_bool print_array(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1199
{
M
Max Bruckner 已提交
1200
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1201
    size_t length = 0;
M
Max Bruckner 已提交
1202
    cJSON *current_element = item->child;
K
Kevin Branigan 已提交
1203

M
Max Bruckner 已提交
1204
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1205
    {
1206
        return false;
M
Max Bruckner 已提交
1207 1208
    }

M
Max Bruckner 已提交
1209 1210
    /* Compose the output array. */
    /* opening square bracket */
1211
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1212
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1213
    {
1214
        return false;
M
Max Bruckner 已提交
1215 1216
    }

M
Max Bruckner 已提交
1217 1218
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1219

M
Max Bruckner 已提交
1220
    while (current_element != NULL)
M
Max Bruckner 已提交
1221
    {
1222
        if (!print_value(current_element, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1223
        {
1224
            return false;
M
Max Bruckner 已提交
1225
        }
1226
        update_offset(output_buffer);
M
Max Bruckner 已提交
1227
        if (current_element->next)
M
Max Bruckner 已提交
1228
        {
1229
            length = (size_t) (format ? 2 : 1);
1230
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1231
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1232
            {
1233
                return false;
M
Max Bruckner 已提交
1234
            }
M
Max Bruckner 已提交
1235 1236
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1237
            {
M
Max Bruckner 已提交
1238
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1239
            }
M
Max Bruckner 已提交
1240 1241
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1242
        }
M
Max Bruckner 已提交
1243
        current_element = current_element->next;
M
Max Bruckner 已提交
1244 1245
    }

1246
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1247
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1248
    {
1249
        return false;
M
Max Bruckner 已提交
1250
    }
M
Max Bruckner 已提交
1251 1252
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1253

1254
    return true;
K
Kevin Branigan 已提交
1255 1256 1257
}

/* Build an object from the text. */
1258
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const error_pointer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1259
{
1260
    cJSON *head = NULL; /* linked list head */
1261 1262
    cJSON *current_item = NULL;

1263
    if (*input != '{')
M
Max Bruckner 已提交
1264
    {
1265 1266
        *error_pointer = input;
        goto fail; /* not an object */
M
Max Bruckner 已提交
1267 1268
    }

M
Max Bruckner 已提交
1269
    input = skip_whitespace(input + 1);
1270
    if (*input == '}')
M
Max Bruckner 已提交
1271
    {
1272
        goto success; /* empty object */
M
Max Bruckner 已提交
1273 1274
    }

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

1287 1288
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1289
        {
1290 1291 1292 1293 1294 1295 1296 1297 1298
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
M
Max Bruckner 已提交
1299 1300
        }

1301
        /* parse the name of the child */
M
Max Bruckner 已提交
1302
        input = skip_whitespace(input + 1);
1303
        input = parse_string(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1304
        input = skip_whitespace(input);
1305
        if (input == NULL)
M
Max Bruckner 已提交
1306
        {
1307
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1308 1309
        }

1310 1311 1312
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1313

1314
        if (*input != ':')
M
Max Bruckner 已提交
1315
        {
1316 1317
            *error_pointer = input;
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1318
        }
1319 1320

        /* parse the value */
M
Max Bruckner 已提交
1321
        input = skip_whitespace(input + 1);
1322
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1323
        input = skip_whitespace(input);
1324
        if (input == NULL)
M
Max Bruckner 已提交
1325
        {
1326
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1327 1328
        }
    }
1329
    while (*input == ',');
1330

1331
    if (*input != '}')
M
Max Bruckner 已提交
1332
    {
1333 1334
        *error_pointer = input;
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1335 1336
    }

1337 1338
success:
    item->type = cJSON_Object;
1339
    item->child = head;
1340

1341
    return input + 1;
1342 1343

fail:
1344
    if (head != NULL)
1345
    {
1346
        cJSON_Delete(head);
1347 1348
    }

1349
    return NULL;
K
Kevin Branigan 已提交
1350 1351 1352
}

/* Render an object to text. */
1353
static cJSON_bool print_object(const cJSON * const item, const size_t depth, const cJSON_bool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
1354
{
M
Max Bruckner 已提交
1355
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1356
    size_t length = 0;
M
Max Bruckner 已提交
1357
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1358

M
Max Bruckner 已提交
1359
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1360
    {
1361
        return false;
M
Max Bruckner 已提交
1362 1363
    }

M
Max Bruckner 已提交
1364
    /* Compose the output: */
1365
    length = (size_t) (format ? 2 : 1); /* fmt: {\n */
1366
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1367
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1368
    {
1369
        return false;
M
Max Bruckner 已提交
1370 1371
    }

M
Max Bruckner 已提交
1372 1373
    *output_pointer++ = '{';
    if (format)
M
Max Bruckner 已提交
1374
    {
M
Max Bruckner 已提交
1375
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1376
    }
M
Max Bruckner 已提交
1377
    output_buffer->offset += length;
M
Max Bruckner 已提交
1378

M
Max Bruckner 已提交
1379
    while (current_item)
M
Max Bruckner 已提交
1380
    {
M
Max Bruckner 已提交
1381
        if (format)
M
Max Bruckner 已提交
1382
        {
M
Max Bruckner 已提交
1383
            size_t i;
1384
            output_pointer = ensure(output_buffer, depth + 1, hooks);
M
Max Bruckner 已提交
1385
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1386
            {
1387
                return false;
M
Max Bruckner 已提交
1388
            }
M
Max Bruckner 已提交
1389
            for (i = 0; i < depth + 1; i++)
M
Max Bruckner 已提交
1390
            {
M
Max Bruckner 已提交
1391
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1392
            }
M
Max Bruckner 已提交
1393
            output_buffer->offset += depth + 1;
M
Max Bruckner 已提交
1394 1395
        }

M
Max Bruckner 已提交
1396
        /* print key */
1397
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks))
M
Max Bruckner 已提交
1398
        {
1399
            return false;
M
Max Bruckner 已提交
1400
        }
M
Max Bruckner 已提交
1401
        update_offset(output_buffer);
M
Max Bruckner 已提交
1402

1403
        length = (size_t) (format ? 2 : 1);
1404
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1405
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1406
        {
1407
            return false;
M
Max Bruckner 已提交
1408
        }
M
Max Bruckner 已提交
1409 1410
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1411
        {
M
Max Bruckner 已提交
1412
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1413
        }
M
Max Bruckner 已提交
1414
        output_buffer->offset += length;
M
Max Bruckner 已提交
1415

M
Max Bruckner 已提交
1416
        /* print value */
1417
        if (!print_value(current_item, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1418
        {
1419
            return false;
M
Max Bruckner 已提交
1420
        }
M
Max Bruckner 已提交
1421
        update_offset(output_buffer);
M
Max Bruckner 已提交
1422

M
Max Bruckner 已提交
1423
        /* print comma if not last */
1424
        length = (size_t) ((format ? 1 : 0) + (current_item->next ? 1 : 0));
1425
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1426
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1427
        {
1428
            return false;
M
Max Bruckner 已提交
1429
        }
M
Max Bruckner 已提交
1430
        if (current_item->next)
M
Max Bruckner 已提交
1431
        {
M
Max Bruckner 已提交
1432
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1433 1434
        }

M
Max Bruckner 已提交
1435
        if (format)
M
Max Bruckner 已提交
1436
        {
M
Max Bruckner 已提交
1437
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1438
        }
M
Max Bruckner 已提交
1439 1440
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1441

M
Max Bruckner 已提交
1442
        current_item = current_item->next;
M
Max Bruckner 已提交
1443
    }
M
Max Bruckner 已提交
1444

1445
    output_pointer = ensure(output_buffer, format ? (depth + 2) : 2, hooks);
M
Max Bruckner 已提交
1446
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1447
    {
1448
        return false;
M
Max Bruckner 已提交
1449
    }
M
Max Bruckner 已提交
1450
    if (format)
M
Max Bruckner 已提交
1451
    {
M
Max Bruckner 已提交
1452 1453
        size_t i;
        for (i = 0; i < (depth); i++)
M
Max Bruckner 已提交
1454
        {
M
Max Bruckner 已提交
1455
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1456 1457
        }
    }
M
Max Bruckner 已提交
1458 1459
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1460

1461
    return true;
K
Kevin Branigan 已提交
1462 1463 1464
}

/* Get Array size/item / object item. */
1465
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1466 1467
{
    cJSON *c = array->child;
1468
    size_t i = 0;
M
Max Bruckner 已提交
1469 1470 1471 1472 1473
    while(c)
    {
        i++;
        c = c->next;
    }
1474 1475 1476

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

M
Max Bruckner 已提交
1477
    return (int)i;
M
Max Bruckner 已提交
1478 1479
}

1480
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1481
{
1482
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1483 1484 1485 1486 1487 1488 1489 1490 1491
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1492
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1493
{
1494
    cJSON *c = object ? object->child : NULL;
1495
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1496 1497 1498 1499 1500 1501
    {
        c = c->next;
    }
    return c;
}

1502
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
{
    cJSON *current_element = NULL;

    if ((object == NULL) || (string == NULL))
    {
        return NULL;
    }

    current_element = object->child;
    while ((current_element != NULL) && (strcmp(string, current_element->string) != 0))
    {
        current_element = current_element->next;
    }

    return current_element;
}

1520
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1521 1522 1523
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1524 1525

/* Utility for array list handling. */
M
Max Bruckner 已提交
1526 1527 1528 1529 1530 1531
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1532
/* Utility for handling references. */
1533
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1534
{
1535
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1536 1537
    if (!ref)
    {
1538
        return NULL;
M
Max Bruckner 已提交
1539 1540
    }
    memcpy(ref, item, sizeof(cJSON));
1541
    ref->string = NULL;
M
Max Bruckner 已提交
1542
    ref->type |= cJSON_IsReference;
1543
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1544 1545
    return ref;
}
K
Kevin Branigan 已提交
1546 1547

/* Add item to array/object. */
1548
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1549
{
1550 1551 1552
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1553 1554 1555
    {
        return;
    }
1556 1557 1558 1559

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1560 1561 1562 1563 1564 1565 1566
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1567
        while (child->next)
M
Max Bruckner 已提交
1568
        {
1569
            child = child->next;
M
Max Bruckner 已提交
1570
        }
1571
        suffix_object(child, item);
M
Max Bruckner 已提交
1572 1573 1574
    }
}

1575
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
M
Max Bruckner 已提交
1576
{
1577
    /* call cJSON_AddItemToObjectCS for code reuse */
1578
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1579 1580
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1581 1582
}

1583 1584 1585 1586
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wcast-qual"
1587
/* Add an item to an object with constant string as key */
1588
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1589 1590 1591 1592 1593 1594 1595
{
    if (!item)
    {
        return;
    }
    if (!(item->type & cJSON_StringIsConst) && item->string)
    {
1596
        global_hooks.deallocate(item->string);
1597 1598 1599 1600 1601
    }
    item->string = (char*)string;
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}
1602 1603 1604
#if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif
1605

1606
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1607
{
1608
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1609 1610
}

1611
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1612
{
1613
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1614 1615
}

M
Max Bruckner 已提交
1616
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1627
        return NULL;
1628
    }
1629
    if (c->prev)
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    {
        /* 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 */
1643
    c->prev = c->next = NULL;
1644 1645 1646

    return c;
}
1647
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
M
Max Bruckner 已提交
1648 1649 1650 1651 1652 1653 1654 1655
{
    if (which < 0)
    {
        return NULL;
    }

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

1657
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
1658 1659 1660 1661
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1662
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
1663
{
1664
    size_t i = 0;
1665
    cJSON *c = object->child;
1666
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1667 1668 1669 1670 1671 1672
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1673
        return DetachItemFromArray(object, i);
1674 1675
    }

1676
    return NULL;
1677 1678
}

1679
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1680 1681 1682
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1683 1684

/* Replace array/object items with new ones. */
1685
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
{
    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 已提交
1711
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
{
    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;
    }
1737
    c->next = c->prev = NULL;
1738 1739
    cJSON_Delete(c);
}
1740
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
M
Max Bruckner 已提交
1741 1742 1743 1744 1745 1746 1747 1748
{
    if (which < 0)
    {
        return;
    }

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

1750
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1751
{
1752
    size_t i = 0;
1753
    cJSON *c = object->child;
1754
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1755 1756 1757 1758 1759 1760
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1761 1762 1763
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1764
             global_hooks.deallocate(newitem->string);
1765 1766
        }

1767
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1768
        ReplaceItemInArray(object, i, newitem);
1769 1770
    }
}
K
Kevin Branigan 已提交
1771 1772

/* Create basic types: */
1773
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
M
Max Bruckner 已提交
1774
{
1775
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1776 1777 1778 1779 1780 1781 1782 1783
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

1784
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
M
Max Bruckner 已提交
1785
{
1786
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1787 1788 1789 1790 1791 1792 1793 1794
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

1795
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
M
Max Bruckner 已提交
1796
{
1797
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1798 1799 1800 1801 1802 1803 1804 1805
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

1806
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
M
Max Bruckner 已提交
1807
{
1808
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1809 1810 1811 1812 1813 1814 1815 1816
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

1817
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
M
Max Bruckner 已提交
1818
{
1819
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1820 1821 1822 1823
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837

        /* 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 已提交
1838 1839 1840 1841 1842
    }

    return item;
}

1843
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
M
Max Bruckner 已提交
1844
{
1845
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1846 1847 1848
    if(item)
    {
        item->type = cJSON_String;
1849
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1850 1851 1852
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1853
            return NULL;
M
Max Bruckner 已提交
1854 1855 1856 1857 1858 1859
        }
    }

    return item;
}

1860
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
J
Jiri Zouhar 已提交
1861
{
1862
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1863 1864 1865
    if(item)
    {
        item->type = cJSON_Raw;
1866
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
1867 1868 1869 1870 1871 1872 1873 1874
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
1875 1876
}

1877
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
M
Max Bruckner 已提交
1878
{
1879
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1880 1881 1882 1883 1884 1885 1886 1887
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

1888
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
M
Max Bruckner 已提交
1889
{
1890
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1891 1892 1893 1894 1895 1896 1897
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
1898 1899

/* Create Arrays: */
1900
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
M
Max Bruckner 已提交
1901
{
1902
    size_t i = 0;
1903 1904
    cJSON *n = NULL;
    cJSON *p = NULL;
1905 1906 1907 1908 1909 1910 1911 1912 1913
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1914 1915 1916 1917 1918
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
1919
            return NULL;
M
Max Bruckner 已提交
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1935
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
M
Max Bruckner 已提交
1936
{
1937
    size_t i = 0;
1938 1939
    cJSON *n = NULL;
    cJSON *p = NULL;
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1950
    {
1951
        n = cJSON_CreateNumber((double)numbers[i]);
M
Max Bruckner 已提交
1952 1953 1954
        if(!n)
        {
            cJSON_Delete(a);
1955
            return NULL;
M
Max Bruckner 已提交
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1971
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
1972
{
1973
    size_t i = 0;
1974 1975
    cJSON *n = NULL;
    cJSON *p = NULL;
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
1986 1987 1988 1989 1990
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
1991
            return NULL;
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

2007
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
2008
{
2009
    size_t i = 0;
2010 2011
    cJSON *n = NULL;
    cJSON *p = NULL;
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
2022 2023 2024 2025 2026
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
2027
            return NULL;
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}
2042 2043

/* Duplication */
2044
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
2045
{
M
Max Bruckner 已提交
2046
    cJSON *newitem = NULL;
2047 2048
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2049
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2050 2051 2052 2053

    /* Bail on bad ptr */
    if (!item)
    {
2054
        goto fail;
M
Max Bruckner 已提交
2055 2056
    }
    /* Create new item */
2057
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2058 2059
    if (!newitem)
    {
2060
        goto fail;
M
Max Bruckner 已提交
2061 2062 2063 2064 2065 2066 2067
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2068
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2069 2070
        if (!newitem->valuestring)
        {
2071
            goto fail;
M
Max Bruckner 已提交
2072 2073 2074 2075
        }
    }
    if (item->string)
    {
2076
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2077 2078
        if (!newitem->string)
        {
2079
            goto fail;
M
Max Bruckner 已提交
2080 2081 2082 2083 2084 2085 2086 2087
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2088 2089
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2090
    {
2091
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2092 2093
        if (!newchild)
        {
2094
            goto fail;
M
Max Bruckner 已提交
2095
        }
2096
        if (next != NULL)
M
Max Bruckner 已提交
2097 2098
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2099 2100 2101
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2102 2103 2104 2105
        }
        else
        {
            /* Set newitem->child and move to it */
2106 2107
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2108
        }
2109
        child = child->next;
M
Max Bruckner 已提交
2110 2111 2112
    }

    return newitem;
2113 2114 2115 2116 2117 2118 2119 2120

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

    return NULL;
2121
}
2122

2123
CJSON_PUBLIC(void) cJSON_Minify(char *json)
2124
{
2125
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
    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 已提交
2165
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2166 2167 2168 2169
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2170
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2171
                }
M
Max Bruckner 已提交
2172
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2173
            }
M
Max Bruckner 已提交
2174
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2175 2176 2177 2178
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2179
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2180 2181 2182 2183 2184
        }
    }

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

2187
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
2188 2189 2190 2191 2192 2193 2194 2195 2196
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Invalid;
}

2197
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
2198 2199 2200 2201 2202 2203 2204 2205 2206
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_False;
}

2207
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xff) == cJSON_True;
}


2218
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
2219 2220 2221 2222 2223 2224 2225 2226
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
2227
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
2228 2229 2230 2231 2232 2233 2234 2235 2236
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_NULL;
}

2237
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
2238 2239 2240 2241 2242 2243 2244 2245 2246
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Number;
}

2247
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
2248 2249 2250 2251 2252 2253 2254 2255 2256
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_String;
}

2257
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
2258 2259 2260 2261 2262 2263 2264 2265 2266
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Array;
}

2267
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
2268 2269 2270 2271 2272 2273 2274 2275 2276
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Object;
}

2277
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
2278 2279 2280 2281 2282 2283 2284 2285
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Raw;
}