cJSON.c 52.0 KB
Newer Older
K
Kevin Branigan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
  Copyright (c) 2009 Dave Gamble

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

/* cJSON */
/* JSON parser in C. */

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"

M
Max Bruckner 已提交
35
/* define our own boolean type */
M
Max Bruckner 已提交
36 37 38
typedef int cjbool;
#define true ((cjbool)1)
#define false ((cjbool)0)
M
Max Bruckner 已提交
39

40
static const unsigned char *global_ep = NULL;
K
Kevin Branigan 已提交
41

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

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

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

    return version;
}

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

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

82 83 84 85 86 87 88 89
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 已提交
90

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

96 97 98 99 100
    if (str == NULL)
    {
        return NULL;
    }

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

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

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

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

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

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

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

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

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

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

184
    if (input == NULL)
185 186 187 188
    {
        return NULL;
    }

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

195
    item->valuedouble = number;
M
Max Bruckner 已提交
196

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

M
Max Bruckner 已提交
211 212
    item->type = cJSON_Number;

213
    return after_end;
K
Kevin Branigan 已提交
214 215
}

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

    return object->valuedouble = number;
}

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

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

249
    if ((p == NULL) || (p->buffer == NULL))
250
    {
251
        return NULL;
252 253
    }

254 255 256 257 258 259
    if (needed > INT_MAX)
    {
        /* sizes bigger than INT_MAX are currently not supported */
        return NULL;
    }

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

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

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    /* 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;
        }
    }

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

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

    return newbuffer + p->offset;
312 313
}

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

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

/* Render the number nicely from the given item into a string. */
328
static unsigned char *print_number(const cJSON * const item, printbuffer * const output_buffer, const internal_hooks * const hooks)
329
{
M
Max Bruckner 已提交
330
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
331
    double d = item->valuedouble;
M
Max Bruckner 已提交
332

M
Max Bruckner 已提交
333
    if (output_buffer == NULL)
M
Max Bruckner 已提交
334 335 336 337
    {
        return NULL;
    }

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

M
Max Bruckner 已提交
375
    return output_pointer;
K
Kevin Branigan 已提交
376 377
}

M
Max Bruckner 已提交
378
/* parse 4 digit hexadecimal number */
379
static unsigned parse_hex4(const unsigned char * const input)
380
{
M
Max Bruckner 已提交
381
    unsigned int h = 0;
382
    size_t i = 0;
M
Max Bruckner 已提交
383

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

404 405 406 407 408
        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
M
Max Bruckner 已提交
409 410 411
    }

    return h;
412 413
}

414 415
/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
416
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 已提交
417
{
418 419 420 421 422 423 424 425 426 427 428 429 430
    /* first bytes of UTF8 encoding for a given length in bytes */
    static const unsigned char firstByteMark[5] =
    {
        0x00, /* should never happen */
        0x00, /* 0xxxxxxx */
        0xC0, /* 110xxxxx */
        0xE0, /* 1110xxxx */
        0xF0 /* 11110xxx */
    };

    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
431 432
    unsigned char utf8_length = 0;
    unsigned char sequence_length = 0;
433 434 435 436 437 438 439 440 441

    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);
    if ((input_end - first_sequence) < 6)
    {
        /* input ends unexpectedly */
        *error_pointer = first_sequence;
        goto fail;
    }
M
Max Bruckner 已提交
442

443 444
    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)) || (first_code == 0))
M
Max Bruckner 已提交
445
    {
446
        *error_pointer = first_sequence;
447
        goto fail;
M
Max Bruckner 已提交
448
    }
M
Max Bruckner 已提交
449

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

        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 已提交
489
    }
M
Max Bruckner 已提交
490

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    /* encode as UTF-8
     * takes at maximum 4 bytes to encode:
     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
    if (codepoint < 0x80)
    {
        /* normal ascii, encoding 0xxxxxxx */
        utf8_length = 1;
    }
    else if (codepoint < 0x800)
    {
        /* two bytes, encoding 110xxxxx 10xxxxxx */
        utf8_length = 2;
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
    }
    else
M
Max Bruckner 已提交
515
    {
516 517
        /* invalid unicode codepoint */
        *error_pointer = first_sequence;
518
        goto fail;
M
Max Bruckner 已提交
519 520
    }

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    /* encode as utf8 */
    switch (utf8_length)
    {
        case 4:
            /* 10xxxxxx */
            (*output_pointer)[3] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 3:
            /* 10xxxxxx */
            (*output_pointer)[2] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 2:
            (*output_pointer)[1] = (unsigned char)((codepoint | 0x80) & 0xBF);
            codepoint >>= 6;
        case 1:
            /* depending on the length in bytes this determines the
               encoding of the first UTF8 byte */
            (*output_pointer)[0] = (unsigned char)((codepoint | firstByteMark[utf8_length]) & 0xFF);
            break;
        default:
            *error_pointer = first_sequence;
            goto fail;
    }
    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
553
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)
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
{
    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;
593
        output = (unsigned char*)hooks->allocate(allocation_length + sizeof('\0'));
594 595 596 597 598 599 600
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
M
Max Bruckner 已提交
601
    /* loop through the string literal */
602
    while (input_pointer < input_end)
M
Max Bruckner 已提交
603
    {
604
        if (*input_pointer != '\\')
M
Max Bruckner 已提交
605
        {
606
            *output_pointer++ = *input_pointer++;
M
Max Bruckner 已提交
607 608 609 610
        }
        /* escape sequence */
        else
        {
611
            unsigned char sequence_length = 2;
612
            switch (input_pointer[1])
M
Max Bruckner 已提交
613 614
            {
                case 'b':
615
                    *output_pointer++ = '\b';
M
Max Bruckner 已提交
616 617
                    break;
                case 'f':
618
                    *output_pointer++ = '\f';
M
Max Bruckner 已提交
619 620
                    break;
                case 'n':
621
                    *output_pointer++ = '\n';
M
Max Bruckner 已提交
622 623
                    break;
                case 'r':
624
                    *output_pointer++ = '\r';
M
Max Bruckner 已提交
625 626
                    break;
                case 't':
627
                    *output_pointer++ = '\t';
M
Max Bruckner 已提交
628
                    break;
629 630 631
                case '\"':
                case '\\':
                case '/':
632
                    *output_pointer++ = input_pointer[1];
633
                    break;
634 635

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

M
Max Bruckner 已提交
645
                default:
646
                    *error_pointer = input_pointer;
647
                    goto fail;
M
Max Bruckner 已提交
648
            }
649
            input_pointer += sequence_length;
M
Max Bruckner 已提交
650 651
        }
    }
652 653 654

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

656
    item->type = cJSON_String;
657
    item->valuestring = (char*)output;
658

659
    return input_end + 1;
660 661

fail:
662
    if (output != NULL)
663
    {
664
        hooks->deallocate(output);
665 666 667
    }

    return NULL;
K
Kevin Branigan 已提交
668 669 670
}

/* Render the cstring provided to an escaped version that can be printed. */
671
static unsigned char *print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
672
{
673 674 675
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
676 677 678
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;
M
Max Bruckner 已提交
679

680
    if (output_buffer == NULL)
M
Max Bruckner 已提交
681 682 683 684
    {
        return NULL;
    }

M
Max Bruckner 已提交
685
    /* empty string */
686
    if (input == NULL)
M
Max Bruckner 已提交
687
    {
688
        output = ensure(output_buffer, sizeof("\"\""), hooks);
689
        if (output == NULL)
M
Max Bruckner 已提交
690
        {
691
            return NULL;
M
Max Bruckner 已提交
692
        }
693
        strcpy((char*)output, "\"\"");
M
Max Bruckner 已提交
694

695
        return output;
M
Max Bruckner 已提交
696 697 698
    }

    /* set "flag" to 1 if something needs to be escaped */
699
    for (input_pointer = input; *input_pointer; input_pointer++)
M
Max Bruckner 已提交
700
    {
M
Max Bruckner 已提交
701
        if (strchr("\"\\\b\f\n\r\t", *input_pointer))
M
Max Bruckner 已提交
702
        {
M
Max Bruckner 已提交
703 704
            /* one character escape sequence */
            escape_characters++;
M
Max Bruckner 已提交
705
        }
M
Max Bruckner 已提交
706
        else if (*input_pointer < 32)
M
Max Bruckner 已提交
707
        {
M
Max Bruckner 已提交
708 709
            /* UTF-16 escape sequence uXXXX */
            escape_characters += 5;
M
Max Bruckner 已提交
710 711
        }
    }
M
Max Bruckner 已提交
712
    output_length = (size_t)(input_pointer - input) + escape_characters;
M
Max Bruckner 已提交
713

714
    output = ensure(output_buffer, output_length + sizeof("\"\""), hooks);
715
    if (output == NULL)
M
Max Bruckner 已提交
716
    {
717
        return NULL;
M
Max Bruckner 已提交
718 719
    }

M
Max Bruckner 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732
    /* no characters have to be escaped */
    if (escape_characters == 0)
    {
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

        return output;
    }

    output[0] = '\"';
    output_pointer = output + 1;
M
Max Bruckner 已提交
733
    /* copy the string */
M
Max Bruckner 已提交
734
    for (input_pointer = input; *input_pointer != '\0'; input_pointer++, output_pointer++)
M
Max Bruckner 已提交
735
    {
736
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
M
Max Bruckner 已提交
737 738
        {
            /* normal character, copy */
M
Max Bruckner 已提交
739
            *output_pointer = *input_pointer;
M
Max Bruckner 已提交
740 741 742 743
        }
        else
        {
            /* character needs to be escaped */
744
            *output_pointer++ = '\\';
M
Max Bruckner 已提交
745
            switch (*input_pointer)
M
Max Bruckner 已提交
746 747
            {
                case '\\':
M
Max Bruckner 已提交
748
                    *output_pointer = '\\';
M
Max Bruckner 已提交
749 750
                    break;
                case '\"':
M
Max Bruckner 已提交
751
                    *output_pointer = '\"';
M
Max Bruckner 已提交
752 753
                    break;
                case '\b':
M
Max Bruckner 已提交
754
                    *output_pointer = 'b';
M
Max Bruckner 已提交
755 756
                    break;
                case '\f':
M
Max Bruckner 已提交
757
                    *output_pointer = 'f';
M
Max Bruckner 已提交
758 759
                    break;
                case '\n':
M
Max Bruckner 已提交
760
                    *output_pointer = 'n';
M
Max Bruckner 已提交
761 762
                    break;
                case '\r':
M
Max Bruckner 已提交
763
                    *output_pointer = 'r';
M
Max Bruckner 已提交
764 765
                    break;
                case '\t':
M
Max Bruckner 已提交
766
                    *output_pointer = 't';
M
Max Bruckner 已提交
767 768 769
                    break;
                default:
                    /* escape and print as unicode codepoint */
M
Max Bruckner 已提交
770 771
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
M
Max Bruckner 已提交
772 773 774 775
                    break;
            }
        }
    }
M
Max Bruckner 已提交
776 777
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';
M
Max Bruckner 已提交
778

779
    return output;
K
Kevin Branigan 已提交
780
}
M
Max Bruckner 已提交
781

M
Max Bruckner 已提交
782
/* Invoke print_string_ptr (which is useful) on an item. */
783
static unsigned char *print_string(const cJSON * const item, printbuffer * const p, const internal_hooks * const hooks)
M
Max Bruckner 已提交
784
{
785
    return print_string_ptr((unsigned char*)item->valuestring, p, hooks);
M
Max Bruckner 已提交
786
}
K
Kevin Branigan 已提交
787 788

/* Predeclare these prototypes. */
789 790 791 792 793 794
static const unsigned char *parse_value(cJSON * const item, const unsigned char * const input, const unsigned char ** const ep, const internal_hooks * const hooks);
static unsigned char *print_value(const cJSON * const item, const size_t depth, const cjbool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
static const unsigned char *parse_array(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
static unsigned char *print_array(const cJSON * const item, const size_t depth, const cjbool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
static const unsigned char *parse_object(cJSON * const item, const unsigned char *input, const unsigned char ** const ep, const internal_hooks * const hooks);
static unsigned char *print_object(const cJSON * const item, const size_t depth, const cjbool format, printbuffer * const output_buffer, const internal_hooks * const hooks);
K
Kevin Branigan 已提交
795 796

/* Utility to jump whitespace and cr/lf */
M
Max Bruckner 已提交
797
static const unsigned char *skip_whitespace(const unsigned char *in)
M
Max Bruckner 已提交
798
{
799
    while (in && *in && (*in <= 32))
M
Max Bruckner 已提交
800 801 802 803 804 805
    {
        in++;
    }

    return in;
}
K
Kevin Branigan 已提交
806 807

/* Parse an object - create a new root, and populate. */
M
Max Bruckner 已提交
808
cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cjbool require_null_terminated)
K
Kevin Branigan 已提交
809
{
810
    const unsigned char *end = NULL;
M
Max Bruckner 已提交
811
    /* use global error pointer if no specific one was given */
812
    const unsigned char **ep = return_parse_end ? (const unsigned char**)return_parse_end : &global_ep;
813
    cJSON *c = cJSON_New_Item(&global_hooks);
814
    *ep = NULL;
M
Max Bruckner 已提交
815 816
    if (!c) /* memory fail */
    {
817
        return NULL;
M
Max Bruckner 已提交
818 819
    }

820
    end = parse_value(c, skip_whitespace((const unsigned char*)value), ep, &global_hooks);
M
Max Bruckner 已提交
821 822 823 824
    if (!end)
    {
        /* parse failure. ep is set. */
        cJSON_Delete(c);
825
        return NULL;
M
Max Bruckner 已提交
826 827 828 829 830
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
M
Max Bruckner 已提交
831
        end = skip_whitespace(end);
M
Max Bruckner 已提交
832 833 834 835
        if (*end)
        {
            cJSON_Delete(c);
            *ep = end;
836
            return NULL;
M
Max Bruckner 已提交
837 838 839 840
        }
    }
    if (return_parse_end)
    {
841
        *return_parse_end = (const char*)end;
M
Max Bruckner 已提交
842 843 844
    }

    return c;
K
Kevin Branigan 已提交
845
}
M
Max Bruckner 已提交
846

847
/* Default options for cJSON_Parse */
M
Max Bruckner 已提交
848 849 850 851
cJSON *cJSON_Parse(const char *value)
{
    return cJSON_ParseWithOpts(value, 0, 0);
}
K
Kevin Branigan 已提交
852

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

855
static unsigned char *print(const cJSON * const item, cjbool format, const internal_hooks * const hooks)
M
Max Bruckner 已提交
856 857 858 859 860 861 862
{
    printbuffer buffer[1];
    unsigned char *printed = NULL;

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

    /* create buffer */
863
    buffer->buffer = (unsigned char*) hooks->allocate(256);
M
Max Bruckner 已提交
864 865 866 867 868 869
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
870
    if (print_value(item, 0, format, buffer, hooks) == NULL)
M
Max Bruckner 已提交
871 872 873
    {
        goto fail;
    }
874
    update_offset(buffer);
M
Max Bruckner 已提交
875 876

    /* copy the buffer over to a new one */
877
    printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
M
Max Bruckner 已提交
878 879 880 881 882 883 884 885
    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 */
886
    hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
887 888 889 890 891 892

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
893
        hooks->deallocate(buffer->buffer);
M
Max Bruckner 已提交
894 895 896 897
    }

    if (printed != NULL)
    {
898
        hooks->deallocate(printed);
M
Max Bruckner 已提交
899 900 901 902 903
    }

    return NULL;
}

K
Kevin Branigan 已提交
904
/* Render a cJSON item/entity/structure to text. */
905
char *cJSON_Print(const cJSON *item)
M
Max Bruckner 已提交
906
{
907
    return (char*)print(item, true, &global_hooks);
M
Max Bruckner 已提交
908 909
}

910
char *cJSON_PrintUnformatted(const cJSON *item)
911
{
912
    return (char*)print(item, false, &global_hooks);
913
}
914

M
Max Bruckner 已提交
915
char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, cjbool fmt)
916
{
M
Max Bruckner 已提交
917
    printbuffer p;
M
Max Bruckner 已提交
918 919 920

    if (prebuffer < 0)
    {
M
Max Bruckner 已提交
921
        return NULL;
M
Max Bruckner 已提交
922 923
    }

924
    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
925 926
    if (!p.buffer)
    {
927
        return NULL;
928
    }
M
Max Bruckner 已提交
929 930

    p.length = (size_t)prebuffer;
M
Max Bruckner 已提交
931
    p.offset = 0;
932
    p.noalloc = false;
M
Max Bruckner 已提交
933

934
    return (char*)print_value(item, 0, fmt, &p, &global_hooks);
935 936
}

937
int cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cjbool fmt)
938 939
{
    printbuffer p;
M
Max Bruckner 已提交
940 941 942 943 944 945

    if (len < 0)
    {
        return false;
    }

946
    p.buffer = (unsigned char*)buf;
M
Max Bruckner 已提交
947
    p.length = (size_t)len;
948
    p.offset = 0;
949
    p.noalloc = true;
950
    return print_value(item, 0, fmt, &p, &global_hooks) != NULL;
951
}
K
Kevin Branigan 已提交
952 953

/* Parser core - when encountering text, process appropriately. */
954
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 已提交
955
{
956
    if (input == NULL)
M
Max Bruckner 已提交
957
    {
958
        return NULL; /* no input */
M
Max Bruckner 已提交
959 960 961
    }

    /* parse the different types of values */
962 963
    /* null */
    if (!strncmp((const char*)input, "null", 4))
M
Max Bruckner 已提交
964 965
    {
        item->type = cJSON_NULL;
966
        return input + 4;
M
Max Bruckner 已提交
967
    }
968 969
    /* false */
    if (!strncmp((const char*)input, "false", 5))
M
Max Bruckner 已提交
970 971
    {
        item->type = cJSON_False;
972
        return input + 5;
M
Max Bruckner 已提交
973
    }
974 975
    /* true */
    if (!strncmp((const char*)input, "true", 4))
M
Max Bruckner 已提交
976 977 978
    {
        item->type = cJSON_True;
        item->valueint = 1;
979
        return input + 4;
M
Max Bruckner 已提交
980
    }
981 982
    /* string */
    if (*input == '\"')
M
Max Bruckner 已提交
983
    {
984
        return parse_string(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
985
    }
986 987
    /* number */
    if ((*input == '-') || ((*input >= '0') && (*input <= '9')))
M
Max Bruckner 已提交
988
    {
989
        return parse_number(item, input);
M
Max Bruckner 已提交
990
    }
991 992
    /* array */
    if (*input == '[')
M
Max Bruckner 已提交
993
    {
994
        return parse_array(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
995
    }
996 997
    /* object */
    if (*input == '{')
M
Max Bruckner 已提交
998
    {
999
        return parse_object(item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1000 1001
    }

M
Max Bruckner 已提交
1002
    /* failure. */
1003
    *error_pointer = input;
1004
    return NULL;
K
Kevin Branigan 已提交
1005 1006 1007
}

/* Render a value to text. */
1008
static unsigned char *print_value(const cJSON * const item, const size_t depth, const cjbool format,  printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1009
{
M
Max Bruckner 已提交
1010
    unsigned char *output = NULL;
M
Max Bruckner 已提交
1011

M
Max Bruckner 已提交
1012
    if ((item == NULL) || (output_buffer == NULL))
M
Max Bruckner 已提交
1013 1014 1015 1016 1017
    {
        return NULL;
    }

    switch ((item->type) & 0xFF)
M
Max Bruckner 已提交
1018
    {
M
Max Bruckner 已提交
1019
        case cJSON_NULL:
1020
            output = ensure(output_buffer, 5, hooks);
M
Max Bruckner 已提交
1021
            if (output != NULL)
M
Max Bruckner 已提交
1022
            {
M
Max Bruckner 已提交
1023
                strcpy((char*)output, "null");
M
Max Bruckner 已提交
1024 1025 1026
            }
            break;
        case cJSON_False:
1027
            output = ensure(output_buffer, 6, hooks);
M
Max Bruckner 已提交
1028
            if (output != NULL)
M
Max Bruckner 已提交
1029
            {
M
Max Bruckner 已提交
1030
                strcpy((char*)output, "false");
M
Max Bruckner 已提交
1031 1032 1033
            }
            break;
        case cJSON_True:
1034
            output = ensure(output_buffer, 5, hooks);
M
Max Bruckner 已提交
1035
            if (output != NULL)
M
Max Bruckner 已提交
1036
            {
M
Max Bruckner 已提交
1037
                strcpy((char*)output, "true");
M
Max Bruckner 已提交
1038 1039 1040
            }
            break;
        case cJSON_Number:
1041
            output = print_number(item, output_buffer, hooks);
M
Max Bruckner 已提交
1042 1043
            break;
        case cJSON_Raw:
M
Max Bruckner 已提交
1044
        {
M
Max Bruckner 已提交
1045 1046
            size_t raw_length = 0;
            if (item->valuestring == NULL)
1047
            {
M
Max Bruckner 已提交
1048
                if (!output_buffer->noalloc)
J
Jiri Zouhar 已提交
1049
                {
1050
                    hooks->deallocate(output_buffer->buffer);
J
Jiri Zouhar 已提交
1051
                }
M
Max Bruckner 已提交
1052
                output = NULL;
1053
                break;
M
Max Bruckner 已提交
1054 1055 1056
            }

            raw_length = strlen(item->valuestring) + sizeof('\0');
1057
            output = ensure(output_buffer, raw_length, hooks);
M
Max Bruckner 已提交
1058
            if (output != NULL)
M
Max Bruckner 已提交
1059
            {
M
Max Bruckner 已提交
1060
                memcpy(output, item->valuestring, raw_length);
M
Max Bruckner 已提交
1061 1062
            }
            break;
M
Max Bruckner 已提交
1063
        }
M
Max Bruckner 已提交
1064
        case cJSON_String:
1065
            output = print_string(item, output_buffer, hooks);
M
Max Bruckner 已提交
1066 1067
            break;
        case cJSON_Array:
1068
            output = print_array(item, depth, format, output_buffer, hooks);
M
Max Bruckner 已提交
1069 1070
            break;
        case cJSON_Object:
1071
            output = print_object(item, depth, format, output_buffer, hooks);
M
Max Bruckner 已提交
1072 1073
            break;
        default:
M
Max Bruckner 已提交
1074
            output = NULL;
M
Max Bruckner 已提交
1075
            break;
M
Max Bruckner 已提交
1076 1077
    }

M
Max Bruckner 已提交
1078
    return output;
K
Kevin Branigan 已提交
1079 1080 1081
}

/* Build an array from input text. */
1082
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 已提交
1083
{
1084
    cJSON *head = NULL; /* head of the linked list */
1085 1086
    cJSON *current_item = NULL;

1087
    if (*input != '[')
M
Max Bruckner 已提交
1088
    {
1089
        /* not an array */
1090
        *error_pointer = input;
1091
        goto fail;
M
Max Bruckner 已提交
1092
    }
K
Kevin Branigan 已提交
1093

M
Max Bruckner 已提交
1094
    input = skip_whitespace(input + 1);
1095
    if (*input == ']')
M
Max Bruckner 已提交
1096
    {
1097
        /* empty array */
1098
        goto success;
M
Max Bruckner 已提交
1099
    }
K
Kevin Branigan 已提交
1100

1101
    /* step back to character in front of the first element */
1102
    input--;
M
Max Bruckner 已提交
1103
    /* loop through the comma separated array elements */
1104
    do
M
Max Bruckner 已提交
1105
    {
1106
        /* allocate next item */
1107
        cJSON *new_item = cJSON_New_Item(hooks);
1108
        if (new_item == NULL)
M
Max Bruckner 已提交
1109
        {
1110
            goto fail; /* allocation failure */
M
Max Bruckner 已提交
1111
        }
1112 1113 1114

        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1115
        {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
            /* 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 已提交
1128
        input = skip_whitespace(input + 1);
1129
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1130
        input = skip_whitespace(input);
1131
        if (input == NULL)
1132 1133
        {
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1134 1135
        }
    }
1136
    while (*input == ',');
M
Max Bruckner 已提交
1137

1138
    if (*input != ']')
M
Max Bruckner 已提交
1139
    {
1140 1141
        *error_pointer = input;
        goto fail; /* expected end of array */
M
Max Bruckner 已提交
1142 1143
    }

1144 1145
success:
    item->type = cJSON_Array;
1146
    item->child = head;
1147

1148
    return input + 1;
K
Kevin Branigan 已提交
1149

1150
fail:
1151
    if (head != NULL)
1152
    {
1153
        cJSON_Delete(head);
1154 1155
    }

1156
    return NULL;
K
Kevin Branigan 已提交
1157 1158 1159
}

/* Render an array to text */
1160
static unsigned char *print_array(const cJSON * const item, const size_t depth, const cjbool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
K
Kevin Branigan 已提交
1161
{
M
Max Bruckner 已提交
1162 1163
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1164
    size_t length = 0;
M
Max Bruckner 已提交
1165
    cJSON *current_element = item->child;
M
Max Bruckner 已提交
1166
    size_t output_offset = 0;
M
Max Bruckner 已提交
1167

M
Max Bruckner 已提交
1168
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1169 1170 1171
    {
        return NULL;
    }
K
Kevin Branigan 已提交
1172

M
Max Bruckner 已提交
1173 1174
    /* Compose the output array. */
    /* opening square bracket */
M
Max Bruckner 已提交
1175
    output_offset = output_buffer->offset;
1176
    output_pointer = ensure(output_buffer, 1, hooks);
M
Max Bruckner 已提交
1177
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1178
    {
M
Max Bruckner 已提交
1179 1180
        return NULL;
    }
M
Max Bruckner 已提交
1181

M
Max Bruckner 已提交
1182 1183
    *output_pointer = '[';
    output_buffer->offset++;
M
Max Bruckner 已提交
1184

M
Max Bruckner 已提交
1185
    current_element = item->child;
M
Max Bruckner 已提交
1186
    while (current_element != NULL)
M
Max Bruckner 已提交
1187
    {
1188
        if (print_value(current_element, depth + 1, format, output_buffer, hooks) == NULL)
M
Max Bruckner 已提交
1189
        {
1190
            return NULL;
M
Max Bruckner 已提交
1191
        }
1192
        update_offset(output_buffer);
M
Max Bruckner 已提交
1193
        if (current_element->next)
M
Max Bruckner 已提交
1194
        {
M
Max Bruckner 已提交
1195
            length = format ? 2 : 1;
1196
            output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1197
            if (output_pointer == NULL)
1198 1199 1200
            {
                return NULL;
            }
M
Max Bruckner 已提交
1201 1202
            *output_pointer++ = ',';
            if(format)
M
Max Bruckner 已提交
1203
            {
M
Max Bruckner 已提交
1204
                *output_pointer++ = ' ';
M
Max Bruckner 已提交
1205
            }
M
Max Bruckner 已提交
1206 1207
            *output_pointer = '\0';
            output_buffer->offset += length;
M
Max Bruckner 已提交
1208
        }
M
Max Bruckner 已提交
1209
        current_element = current_element->next;
M
Max Bruckner 已提交
1210
    }
M
Max Bruckner 已提交
1211

1212
    output_pointer = ensure(output_buffer, 2, hooks);
M
Max Bruckner 已提交
1213
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1214
    {
M
Max Bruckner 已提交
1215
        return NULL;
M
Max Bruckner 已提交
1216
    }
M
Max Bruckner 已提交
1217 1218
    *output_pointer++ = ']';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1219
    output = output_buffer->buffer + output_offset;
M
Max Bruckner 已提交
1220

M
Max Bruckner 已提交
1221
    return output;
K
Kevin Branigan 已提交
1222 1223 1224
}

/* Build an object from the text. */
1225
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 已提交
1226
{
1227
    cJSON *head = NULL; /* linked list head */
1228 1229
    cJSON *current_item = NULL;

1230
    if (*input != '{')
M
Max Bruckner 已提交
1231
    {
1232 1233
        *error_pointer = input;
        goto fail; /* not an object */
M
Max Bruckner 已提交
1234 1235
    }

M
Max Bruckner 已提交
1236
    input = skip_whitespace(input + 1);
1237
    if (*input == '}')
M
Max Bruckner 已提交
1238
    {
1239
        goto success; /* empty object */
M
Max Bruckner 已提交
1240 1241
    }

1242
    /* step back to character in front of the first element */
1243
    input--;
1244 1245
    /* loop through the comma separated array elements */
    do
M
Max Bruckner 已提交
1246
    {
1247
        /* allocate next item */
1248
        cJSON *new_item = cJSON_New_Item(hooks);
1249 1250 1251 1252
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }
M
Max Bruckner 已提交
1253

1254 1255
        /* attach next item to list */
        if (head == NULL)
M
Max Bruckner 已提交
1256
        {
1257 1258 1259 1260 1261 1262 1263 1264 1265
            /* 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 已提交
1266 1267
        }

1268
        /* parse the name of the child */
M
Max Bruckner 已提交
1269
        input = skip_whitespace(input + 1);
1270
        input = parse_string(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1271
        input = skip_whitespace(input);
1272
        if (input == NULL)
M
Max Bruckner 已提交
1273
        {
1274
            goto fail; /* faile to parse name */
M
Max Bruckner 已提交
1275 1276
        }

1277 1278 1279
        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;
M
Max Bruckner 已提交
1280

1281
        if (*input != ':')
M
Max Bruckner 已提交
1282
        {
1283 1284
            *error_pointer = input;
            goto fail; /* invalid object */
M
Max Bruckner 已提交
1285
        }
1286 1287

        /* parse the value */
M
Max Bruckner 已提交
1288
        input = skip_whitespace(input + 1);
1289
        input = parse_value(current_item, input, error_pointer, hooks);
M
Max Bruckner 已提交
1290
        input = skip_whitespace(input);
1291
        if (input == NULL)
M
Max Bruckner 已提交
1292
        {
1293
            goto fail; /* failed to parse value */
M
Max Bruckner 已提交
1294 1295
        }
    }
1296
    while (*input == ',');
1297

1298
    if (*input != '}')
M
Max Bruckner 已提交
1299
    {
1300 1301
        *error_pointer = input;
        goto fail; /* expected end of object */
M
Max Bruckner 已提交
1302 1303
    }

1304 1305
success:
    item->type = cJSON_Object;
1306
    item->child = head;
1307

1308
    return input + 1;
1309 1310

fail:
1311
    if (head != NULL)
1312
    {
1313
        cJSON_Delete(head);
1314 1315
    }

1316
    return NULL;
K
Kevin Branigan 已提交
1317 1318 1319
}

/* Render an object to text. */
1320
static unsigned char *print_object(const cJSON * const item, const size_t depth, const cjbool format, printbuffer * const output_buffer, const internal_hooks * const hooks)
1321
{
M
Max Bruckner 已提交
1322 1323
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
M
Max Bruckner 已提交
1324 1325
    size_t length = 0;
    size_t output_offset = 0;
M
Max Bruckner 已提交
1326
    cJSON *current_item = item->child;
M
Max Bruckner 已提交
1327

M
Max Bruckner 已提交
1328
    if (output_buffer == NULL)
M
Max Bruckner 已提交
1329 1330 1331
    {
        return NULL;
    }
M
Max Bruckner 已提交
1332

M
Max Bruckner 已提交
1333
    /* Compose the output: */
M
Max Bruckner 已提交
1334
    output_offset = output_buffer->offset;
M
Max Bruckner 已提交
1335
    length = format ? 2 : 1; /* fmt: {\n */
1336
    output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1337
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1338
    {
M
Max Bruckner 已提交
1339 1340
        return NULL;
    }
M
Max Bruckner 已提交
1341

M
Max Bruckner 已提交
1342 1343
    *output_pointer++ = '{';
    if (format)
M
Max Bruckner 已提交
1344
    {
M
Max Bruckner 已提交
1345
        *output_pointer++ = '\n';
M
Max Bruckner 已提交
1346
    }
M
Max Bruckner 已提交
1347
    output_buffer->offset += length;
M
Max Bruckner 已提交
1348

M
Max Bruckner 已提交
1349 1350
    current_item = item->child;
    while (current_item)
M
Max Bruckner 已提交
1351
    {
M
Max Bruckner 已提交
1352
        if (format)
M
Max Bruckner 已提交
1353
        {
M
Max Bruckner 已提交
1354
            size_t i;
1355
            output_pointer = ensure(output_buffer, depth + 1, hooks);
M
Max Bruckner 已提交
1356
            if (output_pointer == NULL)
M
Max Bruckner 已提交
1357
            {
1358
                return NULL;
M
Max Bruckner 已提交
1359
            }
M
Max Bruckner 已提交
1360
            for (i = 0; i < depth + 1; i++)
M
Max Bruckner 已提交
1361
            {
M
Max Bruckner 已提交
1362
                *output_pointer++ = '\t';
M
Max Bruckner 已提交
1363
            }
M
Max Bruckner 已提交
1364
            output_buffer->offset += depth + 1;
M
Max Bruckner 已提交
1365 1366
        }

M
Max Bruckner 已提交
1367
        /* print key */
1368
        if (print_string_ptr((unsigned char*)current_item->string, output_buffer, hooks) == NULL)
M
Max Bruckner 已提交
1369
        {
1370
            return NULL;
M
Max Bruckner 已提交
1371
        }
M
Max Bruckner 已提交
1372
        update_offset(output_buffer);
M
Max Bruckner 已提交
1373

M
Max Bruckner 已提交
1374
        length = format ? 2 : 1;
1375
        output_pointer = ensure(output_buffer, length, hooks);
M
Max Bruckner 已提交
1376
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1377
        {
1378
            return NULL;
M
Max Bruckner 已提交
1379
        }
M
Max Bruckner 已提交
1380 1381
        *output_pointer++ = ':';
        if (format)
M
Max Bruckner 已提交
1382
        {
M
Max Bruckner 已提交
1383
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1384
        }
M
Max Bruckner 已提交
1385
        output_buffer->offset += length;
M
Max Bruckner 已提交
1386

M
Max Bruckner 已提交
1387
        /* print value */
1388
        if (!print_value(current_item, depth + 1, format, output_buffer, hooks))
M
Max Bruckner 已提交
1389
        {
M
Max Bruckner 已提交
1390
            return NULL;
M
Max Bruckner 已提交
1391
        }
M
Max Bruckner 已提交
1392
        update_offset(output_buffer);
M
Max Bruckner 已提交
1393

M
Max Bruckner 已提交
1394
        /* print comma if not last */
M
Max Bruckner 已提交
1395
        length = (size_t) (format ? 1 : 0) + (current_item->next ? 1 : 0);
1396
        output_pointer = ensure(output_buffer, length + 1, hooks);
M
Max Bruckner 已提交
1397
        if (output_pointer == NULL)
M
Max Bruckner 已提交
1398
        {
1399
            return NULL;
M
Max Bruckner 已提交
1400
        }
M
Max Bruckner 已提交
1401
        if (current_item->next)
M
Max Bruckner 已提交
1402
        {
M
Max Bruckner 已提交
1403
            *output_pointer++ = ',';
M
Max Bruckner 已提交
1404
        }
M
Max Bruckner 已提交
1405

M
Max Bruckner 已提交
1406
        if (format)
M
Max Bruckner 已提交
1407
        {
M
Max Bruckner 已提交
1408
            *output_pointer++ = '\n';
M
Max Bruckner 已提交
1409
        }
M
Max Bruckner 已提交
1410 1411
        *output_pointer = '\0';
        output_buffer->offset += length;
M
Max Bruckner 已提交
1412

M
Max Bruckner 已提交
1413
        current_item = current_item->next;
M
Max Bruckner 已提交
1414 1415
    }

1416
    output_pointer = ensure(output_buffer, format ? (depth + 2) : 2, hooks);
M
Max Bruckner 已提交
1417
    if (output_pointer == NULL)
M
Max Bruckner 已提交
1418 1419 1420
    {
        return NULL;
    }
M
Max Bruckner 已提交
1421
    if (format)
M
Max Bruckner 已提交
1422
    {
M
Max Bruckner 已提交
1423 1424
        size_t i;
        for (i = 0; i < (depth); i++)
M
Max Bruckner 已提交
1425
        {
M
Max Bruckner 已提交
1426
            *output_pointer++ = '\t';
M
Max Bruckner 已提交
1427 1428
        }
    }
M
Max Bruckner 已提交
1429 1430
    *output_pointer++ = '}';
    *output_pointer = '\0';
M
Max Bruckner 已提交
1431
    output = (output_buffer->buffer) + output_offset;
M
Max Bruckner 已提交
1432

M
Max Bruckner 已提交
1433
    return output;
K
Kevin Branigan 已提交
1434 1435 1436
}

/* Get Array size/item / object item. */
M
Max Bruckner 已提交
1437
int cJSON_GetArraySize(const cJSON *array)
M
Max Bruckner 已提交
1438 1439
{
    cJSON *c = array->child;
1440
    size_t i = 0;
M
Max Bruckner 已提交
1441 1442 1443 1444 1445
    while(c)
    {
        i++;
        c = c->next;
    }
1446 1447 1448

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

M
Max Bruckner 已提交
1449
    return (int)i;
M
Max Bruckner 已提交
1450 1451
}

1452
cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
M
Max Bruckner 已提交
1453
{
1454
    cJSON *c = array ? array->child : NULL;
M
Max Bruckner 已提交
1455 1456 1457 1458 1459 1460 1461 1462 1463
    while (c && item > 0)
    {
        item--;
        c = c->next;
    }

    return c;
}

1464
cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1465
{
1466
    cJSON *c = object ? object->child : NULL;
1467
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
M
Max Bruckner 已提交
1468 1469 1470 1471 1472 1473
    {
        c = c->next;
    }
    return c;
}

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
cJSON *cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
{
    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;
}

1492
cjbool cJSON_HasObjectItem(const cJSON *object, const char *string)
M
Max Bruckner 已提交
1493 1494 1495
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
K
Kevin Branigan 已提交
1496 1497

/* Utility for array list handling. */
M
Max Bruckner 已提交
1498 1499 1500 1501 1502 1503
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

K
Kevin Branigan 已提交
1504
/* Utility for handling references. */
1505
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
M
Max Bruckner 已提交
1506
{
1507
    cJSON *ref = cJSON_New_Item(hooks);
M
Max Bruckner 已提交
1508 1509
    if (!ref)
    {
1510
        return NULL;
M
Max Bruckner 已提交
1511 1512
    }
    memcpy(ref, item, sizeof(cJSON));
1513
    ref->string = NULL;
M
Max Bruckner 已提交
1514
    ref->type |= cJSON_IsReference;
1515
    ref->next = ref->prev = NULL;
M
Max Bruckner 已提交
1516 1517
    return ref;
}
K
Kevin Branigan 已提交
1518 1519

/* Add item to array/object. */
1520
void cJSON_AddItemToArray(cJSON *array, cJSON *item)
M
Max Bruckner 已提交
1521
{
1522 1523 1524
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
M
Max Bruckner 已提交
1525 1526 1527
    {
        return;
    }
1528 1529 1530 1531

    child = array->child;

    if (child == NULL)
M
Max Bruckner 已提交
1532 1533 1534 1535 1536 1537 1538
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
1539
        while (child->next)
M
Max Bruckner 已提交
1540
        {
1541
            child = child->next;
M
Max Bruckner 已提交
1542
        }
1543
        suffix_object(child, item);
M
Max Bruckner 已提交
1544 1545 1546
    }
}

M
Max Bruckner 已提交
1547 1548
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
1549
    /* call cJSON_AddItemToObjectCS for code reuse */
1550
    cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
1551 1552
    /* remove cJSON_StringIsConst flag */
    item->type &= ~cJSON_StringIsConst;
M
Max Bruckner 已提交
1553 1554
}

1555 1556 1557 1558 1559 1560 1561 1562 1563
/* 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)
    {
1564
        global_hooks.deallocate(item->string);
1565
    }
1566 1567
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
1568
    item->string = (char*)string;
1569
#pragma GCC diagnostic pop
1570 1571 1572 1573
    item->type |= cJSON_StringIsConst;
    cJSON_AddItemToArray(object, item);
}

1574 1575
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
1576
    cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
1577 1578
}

1579 1580
void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
1581
    cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
1582 1583
}

M
Max Bruckner 已提交
1584
static cJSON *DetachItemFromArray(cJSON *array, size_t which)
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
1595
        return NULL;
1596
    }
1597
    if (c->prev)
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    {
        /* 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 */
1611
    c->prev = c->next = NULL;
1612 1613 1614

    return c;
}
M
Max Bruckner 已提交
1615 1616 1617 1618 1619 1620 1621 1622 1623
cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
    if (which < 0)
    {
        return NULL;
    }

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

1625 1626 1627 1628 1629
void cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

1630 1631
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
1632
    size_t i = 0;
1633
    cJSON *c = object->child;
1634
    while (c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1635 1636 1637 1638 1639 1640
    {
        i++;
        c = c->next;
    }
    if (c)
    {
M
Max Bruckner 已提交
1641
        return DetachItemFromArray(object, i);
1642 1643
    }

1644
    return NULL;
1645 1646
}

1647 1648 1649 1650
void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
K
Kevin Branigan 已提交
1651 1652

/* Replace array/object items with new ones. */
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
void cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        cJSON_AddItemToArray(array, newitem);
        return;
    }
    newitem->next = c;
    newitem->prev = c->prev;
    c->prev = newitem;
    if (c == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
}

M
Max Bruckner 已提交
1679
static void ReplaceItemInArray(cJSON *array, size_t which, cJSON *newitem)
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
{
    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;
    }
1705
    c->next = c->prev = NULL;
1706 1707
    cJSON_Delete(c);
}
M
Max Bruckner 已提交
1708 1709 1710 1711 1712 1713 1714 1715 1716
void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    if (which < 0)
    {
        return;
    }

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

1718 1719
void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
1720
    size_t i = 0;
1721
    cJSON *c = object->child;
1722
    while(c && cJSON_strcasecmp((unsigned char*)c->string, (const unsigned char*)string))
1723 1724 1725 1726 1727 1728
    {
        i++;
        c = c->next;
    }
    if(c)
    {
1729 1730 1731
        /* free the old string if not const */
        if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
        {
1732
             global_hooks.deallocate(newitem->string);
1733 1734
        }

1735
        newitem->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1736
        ReplaceItemInArray(object, i, newitem);
1737 1738
    }
}
K
Kevin Branigan 已提交
1739 1740

/* Create basic types: */
M
Max Bruckner 已提交
1741 1742
cJSON *cJSON_CreateNull(void)
{
1743
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1744 1745 1746 1747 1748 1749 1750 1751
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

M
Max Bruckner 已提交
1752 1753
cJSON *cJSON_CreateTrue(void)
{
1754
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1755 1756 1757 1758 1759 1760 1761 1762
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

M
Max Bruckner 已提交
1763 1764
cJSON *cJSON_CreateFalse(void)
{
1765
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1766 1767 1768 1769 1770 1771 1772 1773
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1774
cJSON *cJSON_CreateBool(cjbool b)
M
Max Bruckner 已提交
1775
{
1776
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1777 1778 1779 1780 1781 1782 1783 1784
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

M
Max Bruckner 已提交
1785 1786
cJSON *cJSON_CreateNumber(double num)
{
1787
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1788 1789 1790 1791
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

        /* 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 已提交
1806 1807 1808 1809 1810
    }

    return item;
}

M
Max Bruckner 已提交
1811 1812
cJSON *cJSON_CreateString(const char *string)
{
1813
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1814 1815 1816
    if(item)
    {
        item->type = cJSON_String;
1817
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
M
Max Bruckner 已提交
1818 1819 1820
        if(!item->valuestring)
        {
            cJSON_Delete(item);
1821
            return NULL;
M
Max Bruckner 已提交
1822 1823 1824 1825 1826 1827
        }
    }

    return item;
}

J
Jiri Zouhar 已提交
1828 1829
extern cJSON *cJSON_CreateRaw(const char *raw)
{
1830
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1831 1832 1833
    if(item)
    {
        item->type = cJSON_Raw;
1834
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
M
Max Bruckner 已提交
1835 1836 1837 1838 1839 1840 1841 1842
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
J
Jiri Zouhar 已提交
1843 1844
}

M
Max Bruckner 已提交
1845 1846
cJSON *cJSON_CreateArray(void)
{
1847
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1848 1849 1850 1851 1852 1853 1854 1855
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

M
Max Bruckner 已提交
1856 1857
cJSON *cJSON_CreateObject(void)
{
1858
    cJSON *item = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
1859 1860 1861 1862 1863 1864 1865
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}
K
Kevin Branigan 已提交
1866 1867

/* Create Arrays: */
M
Max Bruckner 已提交
1868 1869
cJSON *cJSON_CreateIntArray(const int *numbers, int count)
{
1870
    size_t i = 0;
1871 1872
    cJSON *n = NULL;
    cJSON *p = NULL;
1873 1874 1875 1876 1877 1878 1879 1880 1881
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
M
Max Bruckner 已提交
1882 1883 1884 1885 1886
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
1887
            return NULL;
M
Max Bruckner 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

M
Max Bruckner 已提交
1903 1904
cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
{
1905
    size_t i = 0;
1906 1907
    cJSON *n = NULL;
    cJSON *p = NULL;
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}

1939 1940
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
{
1941
    size_t i = 0;
1942 1943
    cJSON *n = NULL;
    cJSON *p = NULL;
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
1954 1955 1956 1957 1958
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
1959
            return NULL;
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

1975 1976
cJSON *cJSON_CreateStringArray(const char **strings, int count)
{
1977
    size_t i = 0;
1978 1979
    cJSON *n = NULL;
    cJSON *p = NULL;
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
    cJSON *a = NULL;

    if (count < 0)
    {
        return NULL;
    }

    a = cJSON_CreateArray();

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

    return a;
}
2010 2011

/* Duplication */
M
Max Bruckner 已提交
2012
cJSON *cJSON_Duplicate(const cJSON *item, cjbool recurse)
2013
{
M
Max Bruckner 已提交
2014
    cJSON *newitem = NULL;
2015 2016
    cJSON *child = NULL;
    cJSON *next = NULL;
M
Max Bruckner 已提交
2017
    cJSON *newchild = NULL;
M
Max Bruckner 已提交
2018 2019 2020 2021

    /* Bail on bad ptr */
    if (!item)
    {
2022
        goto fail;
M
Max Bruckner 已提交
2023 2024
    }
    /* Create new item */
2025
    newitem = cJSON_New_Item(&global_hooks);
M
Max Bruckner 已提交
2026 2027
    if (!newitem)
    {
2028
        goto fail;
M
Max Bruckner 已提交
2029 2030 2031 2032 2033 2034 2035
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
2036
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
M
Max Bruckner 已提交
2037 2038
        if (!newitem->valuestring)
        {
2039
            goto fail;
M
Max Bruckner 已提交
2040 2041 2042 2043
        }
    }
    if (item->string)
    {
2044
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
M
Max Bruckner 已提交
2045 2046
        if (!newitem->string)
        {
2047
            goto fail;
M
Max Bruckner 已提交
2048 2049 2050 2051 2052 2053 2054 2055
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
2056 2057
    child = item->child;
    while (child != NULL)
M
Max Bruckner 已提交
2058
    {
2059
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
M
Max Bruckner 已提交
2060 2061
        if (!newchild)
        {
2062
            goto fail;
M
Max Bruckner 已提交
2063
        }
2064
        if (next != NULL)
M
Max Bruckner 已提交
2065 2066
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2067 2068 2069
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
M
Max Bruckner 已提交
2070 2071 2072 2073
        }
        else
        {
            /* Set newitem->child and move to it */
2074 2075
            newitem->child = newchild;
            next = newchild;
M
Max Bruckner 已提交
2076
        }
2077
        child = child->next;
M
Max Bruckner 已提交
2078 2079 2080
    }

    return newitem;
2081 2082 2083 2084 2085 2086 2087 2088

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

    return NULL;
2089
}
2090 2091 2092

void cJSON_Minify(char *json)
{
2093
    unsigned char *into = (unsigned char*)json;
M
Max Bruckner 已提交
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
    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 已提交
2133
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2134 2135 2136 2137
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
M
Max Bruckner 已提交
2138
                    *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2139
                }
M
Max Bruckner 已提交
2140
                *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2141
            }
M
Max Bruckner 已提交
2142
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2143 2144 2145 2146
        }
        else
        {
            /* All other characters. */
M
Max Bruckner 已提交
2147
            *into++ = (unsigned char)*json++;
M
Max Bruckner 已提交
2148 2149 2150 2151 2152
        }
    }

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