Handle race condition and mutex issues.
[platform/upstream/iotivity.git] / extlibs / cjson / cJSON.c
1 /*
2   Copyright (c) 2009 Dave Gamble
3
4   Permission is hereby granted, free of charge, to any person obtaining a copy
5   of this software and associated documentation files (the "Software"), to deal
6   in the Software without restriction, including without limitation the rights
7   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8   copies of the Software, and to permit persons to whom the Software is
9   furnished to do so, subject to the following conditions:
10
11   The above copyright notice and this permission notice shall be included in
12   all copies or substantial portions of the Software.
13
14   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20   THE SOFTWARE.
21 */
22
23 /* cJSON */
24 /* JSON parser in C. */
25
26 #include <string.h>
27 #include <stdio.h>
28 #include <math.h>
29 #include <stdlib.h>
30 #include <float.h>
31 #include <limits.h>
32 #include <ctype.h>
33 #include "cJSON.h"
34
35 /* Determine the number of bits that an integer has using the preprocessor */
36 #if INT_MAX == 32767
37     /* 16 bits */
38     #define INTEGER_SIZE 0x0010
39 #elif INT_MAX == 2147483647
40     /* 32 bits */
41     #define INTEGER_SIZE 0x0100
42 #elif INT_MAX == 9223372036854775807
43     /* 64 bits */
44     #define INTEGER_SIZE 0x1000
45 #else
46     #error "Failed to determine the size of an integer"
47 #endif
48
49 static const char *global_ep = NULL;
50
51 const char *cJSON_GetErrorPtr(void)
52 {
53     return global_ep;
54 }
55
56 /* case insensitive strcmp */
57 static int cJSON_strcasecmp(const char *s1, const char *s2)
58 {
59     if (!s1)
60     {
61         return (s1 == s2) ? 0 : 1; /* both NULL? */
62     }
63     if (!s2)
64     {
65         return 1;
66     }
67     for(; tolower(*(const unsigned char *)s1) == tolower(*(const unsigned char *)s2); ++s1, ++s2)
68     {
69         if (*s1 == '\0')
70         {
71             return 0;
72         }
73     }
74
75     return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
76 }
77
78 static void *(*cJSON_malloc)(size_t sz) = malloc;
79 static void (*cJSON_free)(void *ptr) = free;
80
81 static char* cJSON_strdup(const char* str)
82 {
83     size_t len = 0;
84     char *copy = NULL;
85
86     len = strlen(str) + 1;
87     if (!(copy = (char*)cJSON_malloc(len)))
88     {
89         return NULL;
90     }
91     memcpy(copy, str, len);
92
93     return copy;
94 }
95
96 void cJSON_InitHooks(cJSON_Hooks* hooks)
97 {
98     if (!hooks)
99     {
100         /* Reset hooks */
101         cJSON_malloc = malloc;
102         cJSON_free = free;
103         return;
104     }
105
106     cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
107     cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
108 }
109
110 /* Internal constructor. */
111 static cJSON *cJSON_New_Item(void)
112 {
113     cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
114     if (node)
115     {
116         memset(node, '\0', sizeof(cJSON));
117     }
118
119     return node;
120 }
121
122 /* Delete a cJSON structure. */
123 void cJSON_Delete(cJSON *c)
124 {
125     cJSON *next = NULL;
126     while (c)
127     {
128         next = c->next;
129         if (!(c->type & cJSON_IsReference) && c->child)
130         {
131             cJSON_Delete(c->child);
132         }
133         if (!(c->type & cJSON_IsReference) && c->valuestring)
134         {
135             cJSON_free(c->valuestring);
136         }
137         if (!(c->type & cJSON_StringIsConst) && c->string)
138         {
139             cJSON_free(c->string);
140         }
141         cJSON_free(c);
142         c = next;
143     }
144 }
145
146 /* Parse the input text to generate a number, and populate the result into item. */
147 static const char *parse_number(cJSON *item, const char *num)
148 {
149     double n = 0;
150     double sign = 1;
151     double scale = 0;
152     int subscale = 0;
153     int signsubscale = 1;
154
155     /* Has sign? */
156     if (*num == '-')
157     {
158         sign = -1;
159         num++;
160     }
161     /* is zero */
162     if (*num == '0')
163     {
164         num++;
165     }
166     /* Number? */
167     if ((*num >= '1') && (*num <= '9'))
168     {
169         do
170         {
171             n = (n * 10.0) + (*num++ - '0');
172         }
173         while ((*num >= '0') && (*num<='9'));
174     }
175     /* Fractional part? */
176     if ((*num == '.') && (num[1] >= '0') && (num[1] <= '9'))
177     {
178         num++;
179         do
180         {
181             n = (n  *10.0) + (*num++ - '0');
182             scale--;
183         } while ((*num >= '0') && (*num <= '9'));
184     }
185     /* Exponent? */
186     if ((*num == 'e') || (*num == 'E'))
187     {
188         num++;
189         /* With sign? */
190         if (*num == '+')
191         {
192             num++;
193         }
194         else if (*num == '-')
195         {
196             signsubscale = -1;
197             num++;
198         }
199         /* Number? */
200         while ((*num>='0') && (*num<='9'))
201         {
202             subscale = (subscale * 10) + (*num++ - '0');
203         }
204     }
205
206     /* number = +/- number.fraction * 10^+/- exponent */
207     n = sign * n * pow(10.0, (scale + subscale * signsubscale));
208
209     item->valuedouble = n;
210     item->valueint = (int)n;
211     item->type = cJSON_Number;
212
213     return num;
214 }
215
216 /* calculate the next largest power of 2 */
217 static int pow2gt (int x)
218 {
219     --x;
220
221     x |= x >> 1;
222     x |= x >> 2;
223     x |= x >> 4;
224 #if INTEGER_SIZE & 0x1110 /* at least 16 bit */
225     x |= x >> 8;
226 #endif
227 #if INTEGER_SIZE & 0x1100 /* at least 32 bit */
228     x |= x >> 16;
229 #endif
230 #if INT_SIZE & 0x1000 /* 64 bit */
231     x |= x >> 32;
232 #endif
233
234     return x + 1;
235 }
236
237 typedef struct
238 {
239     char *buffer;
240     int length;
241     int offset;
242 } printbuffer;
243
244 /* realloc printbuffer if necessary to have at least "needed" bytes more */
245 static char* ensure(printbuffer *p, int needed)
246 {
247     char *newbuffer = NULL;
248     int newsize = 0;
249     if (!p || !p->buffer)
250     {
251         return NULL;
252     }
253     needed += p->offset;
254     if (needed <= p->length)
255     {
256         return p->buffer + p->offset;
257     }
258
259     newsize = pow2gt(needed);
260     newbuffer = (char*)cJSON_malloc(newsize);
261     if (!newbuffer)
262     {
263         cJSON_free(p->buffer);
264         p->length = 0;
265         p->buffer = NULL;
266
267         return NULL;
268     }
269     if (newbuffer)
270     {
271         memcpy(newbuffer, p->buffer, p->length);
272     }
273     cJSON_free(p->buffer);
274     p->length = newsize;
275     p->buffer = newbuffer;
276
277     return newbuffer + p->offset;
278 }
279
280 /* calculate the new length of the string in a printbuffer */
281 static int update(const printbuffer *p)
282 {
283     char *str = NULL;
284     if (!p || !p->buffer)
285     {
286         return 0;
287     }
288     str = p->buffer + p->offset;
289
290     return p->offset + strlen(str);
291 }
292
293 /* Render the number nicely from the given item into a string. */
294 static char *print_number(const cJSON *item, printbuffer *p)
295 {
296     char *str = NULL;
297     double d = item->valuedouble;
298     /* special case for 0. */
299     if (d == 0)
300     {
301         if (p)
302         {
303             str = ensure(p, 2);
304         }
305         else
306         {
307             str = (char*)cJSON_malloc(2);
308         }
309         if (str)
310         {
311             strcpy(str,"0");
312         }
313     }
314     /* value is an int */
315     else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
316     {
317         if (p)
318         {
319             str = ensure(p, 21);
320         }
321         else
322         {
323             /* 2^64+1 can be represented in 21 chars. */
324             str = (char*)cJSON_malloc(21);
325         }
326         if (str)
327         {
328             sprintf(str, "%d", item->valueint);
329         }
330     }
331     /* value is a floating point number */
332     else
333     {
334         if (p)
335         {
336             /* This is a nice tradeoff. */
337             str = ensure(p, 64);
338         }
339         else
340         {
341             /* This is a nice tradeoff. */
342             str=(char*)cJSON_malloc(64);
343         }
344         if (str)
345         {
346             /* This checks for NaN and Infinity */
347             if ((d * 0) != 0)
348             {
349                 sprintf(str, "null");
350             }
351             else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
352             {
353                 sprintf(str, "%.0f", d);
354             }
355             else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
356             {
357                 sprintf(str, "%e", d);
358             }
359             else
360             {
361                 sprintf(str, "%f", d);
362             }
363         }
364     }
365     return str;
366 }
367
368 /* parse 4 digit hexadecimal number */
369 static unsigned parse_hex4(const char *str)
370 {
371     unsigned h = 0;
372     /* first digit */
373     if ((*str >= '0') && (*str <= '9'))
374     {
375         h += (*str) - '0';
376     }
377     else if ((*str >= 'A') && (*str <= 'F'))
378     {
379         h += 10 + (*str) - 'A';
380     }
381     else if ((*str >= 'a') && (*str <= 'f'))
382     {
383         h += 10 + (*str) - 'a';
384     }
385     else /* invalid */
386     {
387         return 0;
388     }
389
390
391     /* second digit */
392     h = h << 4;
393     str++;
394     if ((*str >= '0') && (*str <= '9'))
395     {
396         h += (*str) - '0';
397     }
398     else if ((*str >= 'A') && (*str <= 'F'))
399     {
400         h += 10 + (*str) - 'A';
401     }
402     else if ((*str >= 'a') && (*str <= 'f'))
403     {
404         h += 10 + (*str) - 'a';
405     }
406     else /* invalid */
407     {
408         return 0;
409     }
410
411     /* third digit */
412     h = h << 4;
413     str++;
414     if ((*str >= '0') && (*str <= '9'))
415     {
416         h += (*str) - '0';
417     }
418     else if ((*str >= 'A') && (*str <= 'F'))
419     {
420         h += 10 + (*str) - 'A';
421     }
422     else if ((*str >= 'a') && (*str <= 'f'))
423     {
424         h += 10 + (*str) - 'a';
425     }
426     else /* invalid */
427     {
428         return 0;
429     }
430
431     /* fourth digit */
432     h = h << 4;
433     str++;
434     if ((*str >= '0') && (*str <= '9'))
435     {
436         h += (*str) - '0';
437     }
438     else if ((*str >= 'A') && (*str <= 'F'))
439     {
440         h += 10 + (*str) - 'A';
441     }
442     else if ((*str >= 'a') && (*str <= 'f'))
443     {
444         h += 10 + (*str) - 'a';
445     }
446     else /* invalid */
447     {
448         return 0;
449     }
450
451     return h;
452 }
453
454 /* first bytes of UTF8 encoding for a given length in bytes */
455 static const unsigned char firstByteMark[7] =
456 {
457     0x00, /* should never happen */
458     0x00, /* 0xxxxxxx */
459     0xC0, /* 110xxxxx */
460     0xE0, /* 1110xxxx */
461     0xF0, /* 11110xxx */
462     0xF8,
463     0xFC
464 };
465
466 /* Parse the input text into an unescaped cstring, and populate item. */
467 static const char *parse_string(cJSON *item, const char *str, const char **ep)
468 {
469     const char *ptr = str + 1;
470     const char *end_ptr =str + 1;
471     char *ptr2 = NULL;
472     char *out = NULL;
473     int len = 0;
474     unsigned uc = 0;
475     unsigned uc2 = 0;
476
477     /* not a string! */
478     if (*str != '\"')
479     {
480         *ep = str;
481         return NULL;
482     }
483
484     while ((*end_ptr != '\"') && *end_ptr && ++len)
485     {
486         if (*end_ptr++ == '\\')
487         {
488             if (*end_ptr == '\0')
489             {
490                 /* prevent buffer overflow when last input character is a backslash */
491                 return NULL;
492             }
493             /* Skip escaped quotes. */
494             end_ptr++;
495         }
496     }
497
498     /* This is at most how long we need for the string, roughly. */
499     out = (char*)cJSON_malloc(len + 1);
500     if (!out)
501     {
502         return NULL;
503     }
504     item->valuestring = out; /* assign here so out will be deleted during cJSON_Delete() later */
505     item->type = cJSON_String;
506
507     ptr = str + 1;
508     ptr2 = out;
509     /* loop through the string literal */
510     while (ptr < end_ptr)
511     {
512         if (*ptr != '\\')
513         {
514             *ptr2++ = *ptr++;
515         }
516         /* escape sequence */
517         else
518         {
519             ptr++;
520             switch (*ptr)
521             {
522                 case 'b':
523                     *ptr2++ = '\b';
524                     break;
525                 case 'f':
526                     *ptr2++ = '\f';
527                     break;
528                 case 'n':
529                     *ptr2++ = '\n';
530                     break;
531                 case 'r':
532                     *ptr2++ = '\r';
533                     break;
534                 case 't':
535                     *ptr2++ = '\t';
536                     break;
537                 case '\"':
538                 case '\\':
539                 case '/':
540                     *ptr2++ = *ptr;
541                     break;
542                 case 'u':
543                     /* transcode utf16 to utf8. See RFC2781 and RFC3629. */
544                     uc = parse_hex4(ptr + 1); /* get the unicode char. */
545                     ptr += 4;
546                     if (ptr >= end_ptr)
547                     {
548                         /* invalid */
549                         *ep = str;
550                         return NULL;
551                     }
552                     /* check for invalid. */
553                     if (((uc >= 0xDC00) && (uc <= 0xDFFF)) || (uc == 0))
554                     {
555                         *ep = str;
556                         return NULL;
557                     }
558
559                     /* UTF16 surrogate pairs. */
560                     if ((uc >= 0xD800) && (uc<=0xDBFF))
561                     {
562                         if ((ptr + 6) > end_ptr)
563                         {
564                             /* invalid */
565                             *ep = str;
566                             return NULL;
567                         }
568                         if ((ptr[1] != '\\') || (ptr[2] != 'u'))
569                         {
570                             /* missing second-half of surrogate. */
571                             *ep = str;
572                             return NULL;
573                         }
574                         uc2 = parse_hex4(ptr + 3);
575                         ptr += 6; /* \uXXXX */
576                         if ((uc2 < 0xDC00) || (uc2 > 0xDFFF))
577                         {
578                             /* invalid second-half of surrogate. */
579                             *ep = str;
580                             return NULL;
581                         }
582                         /* calculate unicode codepoint from the surrogate pair */
583                         uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF));
584                     }
585
586                     /* encode as UTF8
587                      * takes at maximum 4 bytes to encode:
588                      * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
589                     len = 4;
590                     if (uc < 0x80)
591                     {
592                         /* normal ascii, encoding 0xxxxxxx */
593                         len = 1;
594                     }
595                     else if (uc < 0x800)
596                     {
597                         /* two bytes, encoding 110xxxxx 10xxxxxx */
598                         len = 2;
599                     }
600                     else if (uc < 0x10000)
601                     {
602                         /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
603                         len = 3;
604                     }
605                     ptr2 += len;
606
607                     switch (len) {
608                         case 4:
609                             /* 10xxxxxx */
610                             *--ptr2 = ((uc | 0x80) & 0xBF);
611                             uc >>= 6;
612                         case 3:
613                             /* 10xxxxxx */
614                             *--ptr2 = ((uc | 0x80) & 0xBF);
615                             uc >>= 6;
616                         case 2:
617                             /* 10xxxxxx */
618                             *--ptr2 = ((uc | 0x80) & 0xBF);
619                             uc >>= 6;
620                         case 1:
621                             /* depending on the length in bytes this determines the
622                              * encoding ofthe first UTF8 byte */
623                             *--ptr2 = (uc | firstByteMark[len]);
624                     }
625                     ptr2 += len;
626                     break;
627                 default:
628                     *ep = str;
629                     return NULL;
630             }
631             ptr++;
632         }
633     }
634     *ptr2 = '\0';
635     if (*ptr == '\"')
636     {
637         ptr++;
638     }
639
640     return ptr;
641 }
642
643 /* Render the cstring provided to an escaped version that can be printed. */
644 static char *print_string_ptr(const char *str, printbuffer *p)
645 {
646     const char *ptr = NULL;
647     char *ptr2 = NULL;
648     char *out = NULL;
649     int len = 0;
650     int flag = 0;
651     unsigned char token = '\0';
652
653     /* empty string */
654     if (!str)
655     {
656         if (p)
657         {
658             out = ensure(p, 3);
659         }
660         else
661         {
662             out = (char*)cJSON_malloc(3);
663         }
664         if (!out)
665         {
666             return NULL;
667         }
668         strcpy(out, "\"\"");
669
670         return out;
671     }
672
673     /* set "flag" to 1 if something needs to be escaped */
674     for (ptr = str; *ptr; ptr++)
675     {
676         flag |= (((*ptr > 0) && (*ptr < 32)) /* unprintable characters */
677                 || (*ptr == '\"') /* double quote */
678                 || (*ptr == '\\')) /* backslash */
679             ? 1
680             : 0;
681     }
682     /* no characters have to be escaped */
683     if (!flag)
684     {
685         len = ptr - str;
686         if (p)
687         {
688             out = ensure(p, len + 3);
689         }
690         else
691         {
692             out = (char*)cJSON_malloc(len + 3);
693         }
694         if (!out)
695         {
696             return NULL;
697         }
698
699         ptr2 = out;
700         *ptr2++ = '\"';
701         strcpy(ptr2, str);
702         ptr2[len] = '\"';
703         ptr2[len + 1] = '\0';
704
705         return out;
706     }
707
708     ptr = str;
709     /* calculate additional space that is needed for escaping */
710     while ((token = *ptr) && ++len)
711     {
712         if (strchr("\"\\\b\f\n\r\t", token))
713         {
714             len++; /* +1 for the backslash */
715         }
716         else if (token < 32)
717         {
718             len += 5; /* +5 for \uXXXX */
719         }
720         ptr++;
721     }
722
723     if (p)
724     {
725         out = ensure(p, len + 3);
726     }
727     else
728     {
729         out = (char*)cJSON_malloc(len + 3);
730     }
731     if (!out)
732     {
733         return NULL;
734     }
735
736     ptr2 = out;
737     ptr = str;
738     *ptr2++ = '\"';
739     /* copy the string */
740     while (*ptr)
741     {
742         if (((unsigned char)*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
743         {
744             /* normal character, copy */
745             *ptr2++ = *ptr++;
746         }
747         else
748         {
749             /* character needs to be escaped */
750             *ptr2++ = '\\';
751             switch (token = *ptr++)
752             {
753                 case '\\':
754                     *ptr2++ = '\\';
755                     break;
756                 case '\"':
757                     *ptr2++ = '\"';
758                     break;
759                 case '\b':
760                     *ptr2++ = 'b';
761                     break;
762                 case '\f':
763                     *ptr2++ = 'f';
764                     break;
765                 case '\n':
766                     *ptr2++ = 'n';
767                     break;
768                 case '\r':
769                     *ptr2++ = 'r';
770                     break;
771                 case '\t':
772                     *ptr2++ = 't';
773                     break;
774                 default:
775                     /* escape and print as unicode codepoint */
776                     sprintf(ptr2, "u%04x", token);
777                     ptr2 += 5;
778                     break;
779             }
780         }
781     }
782     *ptr2++ = '\"';
783     *ptr2++ = '\0';
784
785     return out;
786 }
787
788 /* Invoke print_string_ptr (which is useful) on an item. */
789 static char *print_string(const cJSON *item, printbuffer *p)
790 {
791     return print_string_ptr(item->valuestring, p);
792 }
793
794 /* Predeclare these prototypes. */
795 static const char *parse_value(cJSON *item, const char *value, const char **ep);
796 static char *print_value(const cJSON *item, int depth, int fmt, printbuffer *p);
797 static const char *parse_array(cJSON *item, const char *value, const char **ep);
798 static char *print_array(const cJSON *item, int depth, int fmt, printbuffer *p);
799 static const char *parse_object(cJSON *item, const char *value, const char **ep);
800 static char *print_object(const cJSON *item, int depth, int fmt, printbuffer *p);
801
802 /* Utility to jump whitespace and cr/lf */
803 static const char *skip(const char *in)
804 {
805     while (in && *in && ((unsigned char)*in<=32))
806     {
807         in++;
808     }
809
810     return in;
811 }
812
813 /* Parse an object - create a new root, and populate. */
814 cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, int require_null_terminated)
815 {
816     const char *end = NULL;
817     /* use global error pointer if no specific one was given */
818     const char **ep = return_parse_end ? return_parse_end : &global_ep;
819     cJSON *c = cJSON_New_Item();
820     *ep = NULL;
821     if (!c) /* memory fail */
822     {
823         return NULL;
824     }
825
826     end = parse_value(c, skip(value), ep);
827     if (!end)
828     {
829         /* parse failure. ep is set. */
830         cJSON_Delete(c);
831         return NULL;
832     }
833
834     /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
835     if (require_null_terminated)
836     {
837         end = skip(end);
838         if (*end)
839         {
840             cJSON_Delete(c);
841             *ep = end;
842             return NULL;
843         }
844     }
845     if (return_parse_end)
846     {
847         *return_parse_end = end;
848     }
849
850     return c;
851 }
852
853 /* Default options for cJSON_Parse */
854 cJSON *cJSON_Parse(const char *value)
855 {
856     return cJSON_ParseWithOpts(value, 0, 0);
857 }
858
859 /* Render a cJSON item/entity/structure to text. */
860 char *cJSON_Print(const cJSON *item)
861 {
862     return print_value(item, 0, 1, 0);
863 }
864
865 char *cJSON_PrintUnformatted(const cJSON *item)
866 {
867     return print_value(item, 0, 0, 0);
868 }
869
870 char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, int fmt)
871 {
872     printbuffer p;
873     p.buffer = (char*)cJSON_malloc(prebuffer);
874     if (!p.buffer)
875     {
876         return NULL;
877     }
878     p.length = prebuffer;
879     p.offset = 0;
880
881     return print_value(item, 0, fmt, &p);
882 }
883
884
885 /* Parser core - when encountering text, process appropriately. */
886 static const char *parse_value(cJSON *item, const char *value, const char **ep)
887 {
888     if (!value)
889     {
890         /* Fail on null. */
891         return NULL;
892     }
893
894     /* parse the different types of values */
895     if (!strncmp(value, "null", 4))
896     {
897         item->type = cJSON_NULL;
898         return value + 4;
899     }
900     if (!strncmp(value, "false", 5))
901     {
902         item->type = cJSON_False;
903         return value + 5;
904     }
905     if (!strncmp(value, "true", 4))
906     {
907         item->type = cJSON_True;
908         item->valueint = 1;
909         return value + 4;
910     }
911     if (*value == '\"')
912     {
913         return parse_string(item, value, ep);
914     }
915     if ((*value == '-') || ((*value >= '0') && (*value <= '9')))
916     {
917         return parse_number(item, value);
918     }
919     if (*value == '[')
920     {
921         return parse_array(item, value, ep);
922     }
923     if (*value == '{')
924     {
925         return parse_object(item, value, ep);
926     }
927
928     /* failure. */
929     *ep = value;
930     return NULL;
931 }
932
933 /* Render a value to text. */
934 static char *print_value(const cJSON *item, int depth, int fmt, printbuffer *p)
935 {
936     char *out = NULL;
937
938     if (!item)
939     {
940         return NULL;
941     }
942     if (p)
943     {
944         switch ((item->type) & 0xFF)
945         {
946             case cJSON_NULL:
947                 out = ensure(p, 5);
948                 if (out)
949                 {
950                     strcpy(out, "null");
951                 }
952                 break;
953             case cJSON_False:
954                 out = ensure(p, 6);
955                 if (out)
956                 {
957                     strcpy(out, "false");
958                 }
959                 break;
960             case cJSON_True:
961                 out = ensure(p, 5);
962                 if (out)
963                 {
964                     strcpy(out, "true");
965                 }
966                 break;
967             case cJSON_Number:
968                 out = print_number(item, p);
969                 break;
970             case cJSON_String:
971                 out = print_string(item, p);
972                 break;
973             case cJSON_Array:
974                 out = print_array(item, depth, fmt, p);
975                 break;
976             case cJSON_Object:
977                 out = print_object(item, depth, fmt, p);
978                 break;
979         }
980     }
981     else
982     {
983         switch ((item->type) & 0xFF)
984         {
985             case cJSON_NULL:
986                 out = cJSON_strdup("null");
987                 break;
988             case cJSON_False:
989                 out = cJSON_strdup("false");
990                 break;
991             case cJSON_True:
992                 out = cJSON_strdup("true");
993                 break;
994             case cJSON_Number:
995                 out = print_number(item, 0);
996                 break;
997             case cJSON_String:
998                 out = print_string(item, 0);
999                 break;
1000             case cJSON_Array:
1001                 out = print_array(item, depth, fmt, 0);
1002                 break;
1003             case cJSON_Object:
1004                 out = print_object(item, depth, fmt, 0);
1005                 break;
1006         }
1007     }
1008
1009     return out;
1010 }
1011
1012 /* Build an array from input text. */
1013 static const char *parse_array(cJSON *item,const char *value,const char **ep)
1014 {
1015     cJSON *child = NULL;
1016     if (*value != '[')
1017     {
1018         /* not an array! */
1019         *ep = value;
1020         return NULL;
1021     }
1022
1023     item->type = cJSON_Array;
1024     value = skip(value + 1);
1025     if (*value == ']')
1026     {
1027         /* empty array. */
1028         return value + 1;
1029     }
1030
1031     item->child = child = cJSON_New_Item();
1032     if (!item->child)
1033     {
1034         /* memory fail */
1035         return NULL;
1036     }
1037     /* skip any spacing, get the value. */
1038     value = skip(parse_value(child, skip(value), ep));
1039     if (!value)
1040     {
1041         return NULL;
1042     }
1043
1044     /* loop through the comma separated array elements */
1045     while (*value == ',')
1046     {
1047         cJSON *new_item = NULL;
1048         if (!(new_item = cJSON_New_Item()))
1049         {
1050             /* memory fail */
1051             return NULL;
1052         }
1053         /* add new item to end of the linked list */
1054         child->next = new_item;
1055         new_item->prev = child;
1056         child = new_item;
1057
1058         /* go to the next comma */
1059         value = skip(parse_value(child, skip(value + 1), ep));
1060         if (!value)
1061         {
1062             /* memory fail */
1063             return NULL;
1064         }
1065     }
1066
1067     if (*value == ']')
1068     {
1069         /* end of array */
1070         return value + 1;
1071     }
1072
1073     /* malformed. */
1074     *ep = value;
1075
1076     return NULL;
1077 }
1078
1079 /* Render an array to text */
1080 static char *print_array(const cJSON *item, int depth, int fmt, printbuffer *p)
1081 {
1082     char **entries;
1083     char *out = NULL;
1084     char *ptr = NULL;
1085     char *ret = NULL;
1086     int len = 5;
1087     cJSON *child = item->child;
1088     int numentries = 0;
1089     int i = 0;
1090     int fail = 0;
1091     size_t tmplen = 0;
1092
1093     /* How many entries in the array? */
1094     while (child)
1095     {
1096         numentries++;
1097         child = child->next;
1098     }
1099
1100     /* Explicitly handle numentries == 0 */
1101     if (!numentries)
1102     {
1103         if (p)
1104         {
1105             out = ensure(p, 3);
1106         }
1107         else
1108         {
1109             out = (char*)cJSON_malloc(3);
1110         }
1111         if (out)
1112         {
1113             strcpy(out,"[]");
1114         }
1115
1116         return out;
1117     }
1118
1119     if (p)
1120     {
1121         /* Compose the output array. */
1122         /* opening square bracket */
1123         i = p->offset;
1124         ptr = ensure(p, 1);
1125         if (!ptr)
1126         {
1127             return NULL;
1128         }
1129         *ptr = '[';
1130         p->offset++;
1131
1132         child = item->child;
1133         while (child && !fail)
1134         {
1135             print_value(child, depth + 1, fmt, p);
1136             p->offset = update(p);
1137             if (child->next)
1138             {
1139                 len = fmt ? 2 : 1;
1140                 ptr = ensure(p, len + 1);
1141                 if (!ptr)
1142                 {
1143                     return NULL;
1144                 }
1145                 *ptr++ = ',';
1146                 if(fmt)
1147                 {
1148                     *ptr++ = ' ';
1149                 }
1150                 *ptr = '\0';
1151                 p->offset += len;
1152             }
1153             child = child->next;
1154         }
1155         ptr = ensure(p, 2);
1156         if (!ptr)
1157         {
1158             return NULL;
1159         }
1160         *ptr++ = ']';
1161         *ptr = '\0';
1162         out = (p->buffer) + i;
1163     }
1164     else
1165     {
1166         /* Allocate an array to hold the pointers to all printed values */
1167         entries = (char**)cJSON_malloc(numentries * sizeof(char*));
1168         if (!entries)
1169         {
1170             return NULL;
1171         }
1172         memset(entries, '\0', numentries * sizeof(char*));
1173
1174         /* Retrieve all the results: */
1175         child = item->child;
1176         while (child && !fail)
1177         {
1178             ret = print_value(child, depth + 1, fmt, 0);
1179             entries[i++] = ret;
1180             if (ret)
1181             {
1182                 len += strlen(ret) + 2 + (fmt ? 1 : 0);
1183             }
1184             else
1185             {
1186                 fail = 1;
1187             }
1188             child = child->next;
1189         }
1190
1191         /* If we didn't fail, try to malloc the output string */
1192         if (!fail)
1193         {
1194             out = (char*)cJSON_malloc(len);
1195         }
1196         /* If that fails, we fail. */
1197         if (!out)
1198         {
1199             fail = 1;
1200         }
1201
1202         /* Handle failure. */
1203         if (fail)
1204         {
1205             /* free all the entries in the array */
1206             for (i = 0; i < numentries; i++)
1207             {
1208                 if (entries[i])
1209                 {
1210                     cJSON_free(entries[i]);
1211                 }
1212             }
1213             cJSON_free(entries);
1214             return NULL;
1215         }
1216
1217         /* Compose the output array. */
1218         *out='[';
1219         ptr = out + 1;
1220         *ptr = '\0';
1221         for (i = 0; i < numentries; i++)
1222         {
1223             tmplen = strlen(entries[i]);
1224             memcpy(ptr, entries[i], tmplen);
1225             ptr += tmplen;
1226             if (i != (numentries - 1))
1227             {
1228                 *ptr++ = ',';
1229                 if(fmt)
1230                 {
1231                     *ptr++ = ' ';
1232                 }
1233                 *ptr = '\0';
1234             }
1235             cJSON_free(entries[i]);
1236         }
1237         cJSON_free(entries);
1238         *ptr++ = ']';
1239         *ptr++ = '\0';
1240     }
1241
1242     return out;
1243 }
1244
1245 /* Build an object from the text. */
1246 static const char *parse_object(cJSON *item, const char *value, const char **ep)
1247 {
1248     cJSON *child = NULL;
1249     if (*value != '{')
1250     {
1251         /* not an object! */
1252         *ep = value;
1253         return NULL;
1254     }
1255
1256     item->type = cJSON_Object;
1257     value = skip(value + 1);
1258     if (*value == '}')
1259     {
1260         /* empty object. */
1261         return value + 1;
1262     }
1263
1264     child = cJSON_New_Item();
1265     item->child = child;
1266     if (!item->child)
1267     {
1268         return NULL;
1269     }
1270     /* parse first key */
1271     value = skip(parse_string(child, skip(value), ep));
1272     if (!value)
1273     {
1274         return NULL;
1275     }
1276     /* use string as key, not value */
1277     child->string = child->valuestring;
1278     child->valuestring = NULL;
1279
1280     if (*value != ':')
1281     {
1282         /* invalid object. */
1283         *ep = value;
1284         return NULL;
1285     }
1286     /* skip any spacing, get the value. */
1287     value = skip(parse_value(child, skip(value + 1), ep));
1288     if (!value)
1289     {
1290         return NULL;
1291     }
1292
1293     while (*value == ',')
1294     {
1295         cJSON *new_item = NULL;
1296         if (!(new_item = cJSON_New_Item()))
1297         {
1298             /* memory fail */
1299             return NULL;
1300         }
1301         /* add to linked list */
1302         child->next = new_item;
1303         new_item->prev = child;
1304
1305         child = new_item;
1306         value = skip(parse_string(child, skip(value + 1), ep));
1307         if (!value)
1308         {
1309             return NULL;
1310         }
1311
1312         /* use string as key, not value */
1313         child->string = child->valuestring;
1314         child->valuestring = NULL;
1315
1316         if (*value != ':')
1317         {
1318             /* invalid object. */
1319             *ep = value;
1320             return NULL;
1321         }
1322         /* skip any spacing, get the value. */
1323         value = skip(parse_value(child, skip(value + 1), ep));
1324         if (!value)
1325         {
1326             return NULL;
1327         }
1328     }
1329     /* end of object */
1330     if (*value == '}')
1331     {
1332         return value + 1;
1333     }
1334
1335     /* malformed */
1336     *ep = value;
1337     return NULL;
1338 }
1339
1340 /* Render an object to text. */
1341 static char *print_object(const cJSON *item, int depth, int fmt, printbuffer *p)
1342 {
1343     char **entries = NULL;
1344     char **names = NULL;
1345     char *out = NULL;
1346     char *ptr = NULL;
1347     char *ret = NULL;
1348     char *str = NULL;
1349     int len = 7;
1350     int i = 0;
1351     int j = 0;
1352     cJSON *child = item->child;
1353     int numentries = 0;
1354     int fail = 0;
1355     size_t tmplen = 0;
1356
1357     /* Count the number of entries. */
1358     while (child)
1359     {
1360         numentries++;
1361         child = child->next;
1362     }
1363
1364     /* Explicitly handle empty object case */
1365     if (!numentries)
1366     {
1367         if (p)
1368         {
1369             out = ensure(p, fmt ? depth + 4 : 3);
1370         }
1371         else
1372         {
1373             out = (char*)cJSON_malloc(fmt ? depth + 4 : 3);
1374         }
1375         if (!out)
1376         {
1377             return NULL;
1378         }
1379         ptr = out;
1380         *ptr++ = '{';
1381         if (fmt) {
1382             *ptr++ = '\n';
1383             for (i = 0; i < depth; i++)
1384             {
1385                 *ptr++ = '\t';
1386             }
1387         }
1388         *ptr++ = '}';
1389         *ptr++ = '\0';
1390
1391         return out;
1392     }
1393
1394     if (p)
1395     {
1396         /* Compose the output: */
1397         i = p->offset;
1398         len = fmt ? 2 : 1; /* fmt: {\n */
1399         ptr = ensure(p, len + 1);
1400         if (!ptr)
1401         {
1402             return NULL;
1403         }
1404
1405         *ptr++ = '{';
1406         if (fmt)
1407         {
1408             *ptr++ = '\n';
1409         }
1410         *ptr = '\0';
1411         p->offset += len;
1412
1413         child = item->child;
1414         depth++;
1415         while (child)
1416         {
1417             if (fmt)
1418             {
1419                 ptr = ensure(p, depth);
1420                 if (!ptr)
1421                 {
1422                     return NULL;
1423                 }
1424                 for (j = 0; j < depth; j++)
1425                 {
1426                     *ptr++ = '\t';
1427                 }
1428                 p->offset += depth;
1429             }
1430
1431             /* print key */
1432             print_string_ptr(child->string, p);
1433             p->offset = update(p);
1434
1435             len = fmt ? 2 : 1;
1436             ptr = ensure(p, len);
1437             if (!ptr)
1438             {
1439                 return NULL;
1440             }
1441             *ptr++ = ':';
1442             if (fmt)
1443             {
1444                 *ptr++ = '\t';
1445             }
1446             p->offset+=len;
1447
1448             /* print value */
1449             print_value(child, depth, fmt, p);
1450             p->offset = update(p);
1451
1452             /* print comma if not last */
1453             len = (fmt ? 1 : 0) + (child->next ? 1 : 0);
1454             ptr = ensure(p, len + 1);
1455             if (!ptr)
1456             {
1457                 return NULL;
1458             }
1459             if (child->next)
1460             {
1461                 *ptr++ = ',';
1462             }
1463
1464             if (fmt)
1465             {
1466                 *ptr++ = '\n';
1467             }
1468             *ptr = '\0';
1469             p->offset += len;
1470
1471             child = child->next;
1472         }
1473
1474         ptr = ensure(p, fmt ? (depth + 1) : 2);
1475         if (!ptr)
1476         {
1477             return NULL;
1478         }
1479         if (fmt)
1480         {
1481             for (i = 0; i < (depth - 1); i++)
1482             {
1483                 *ptr++ = '\t';
1484             }
1485         }
1486         *ptr++ = '}';
1487         *ptr = '\0';
1488         out = (p->buffer) + i;
1489     }
1490     else
1491     {
1492         /* Allocate space for the names and the objects */
1493         entries = (char**)cJSON_malloc(numentries * sizeof(char*));
1494         if (!entries)
1495         {
1496             return NULL;
1497         }
1498         names = (char**)cJSON_malloc(numentries * sizeof(char*));
1499         if (!names)
1500         {
1501             cJSON_free(entries);
1502             return NULL;
1503         }
1504         memset(entries, '\0', sizeof(char*) * numentries);
1505         memset(names, '\0', sizeof(char*) * numentries);
1506
1507         /* Collect all the results into our arrays: */
1508         child = item->child;
1509         depth++;
1510         if (fmt)
1511         {
1512             len += depth;
1513         }
1514         while (child && !fail)
1515         {
1516             names[i] = str = print_string_ptr(child->string, 0); /* print key */
1517             entries[i++] = ret = print_value(child, depth, fmt, 0);
1518             if (str && ret)
1519             {
1520                 len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0);
1521             }
1522             else
1523             {
1524                 fail = 1;
1525             }
1526             child = child->next;
1527         }
1528
1529         /* Try to allocate the output string */
1530         if (!fail)
1531         {
1532             out = (char*)cJSON_malloc(len);
1533         }
1534         if (!out)
1535         {
1536             fail = 1;
1537         }
1538
1539         /* Handle failure */
1540         if (fail)
1541         {
1542             /* free all the printed keys and values */
1543             for (i = 0; i < numentries; i++)
1544             {
1545                 if (names[i])
1546                 {
1547                     cJSON_free(names[i]);
1548                 }
1549                 if (entries[i])
1550                 {
1551                     cJSON_free(entries[i]);
1552                 }
1553             }
1554             cJSON_free(names);
1555             cJSON_free(entries);
1556             return NULL;
1557         }
1558
1559         /* Compose the output: */
1560         *out = '{';
1561         ptr = out + 1;
1562         if (fmt)
1563         {
1564             *ptr++ = '\n';
1565         }
1566         *ptr = '\0';
1567         for (i = 0; i < numentries; i++)
1568         {
1569             if (fmt)
1570             {
1571                 for (j = 0; j < depth; j++)
1572                 {
1573                     *ptr++='\t';
1574                 }
1575             }
1576             tmplen = strlen(names[i]);
1577             memcpy(ptr, names[i], tmplen);
1578             ptr += tmplen;
1579             *ptr++ = ':';
1580             if (fmt)
1581             {
1582                 *ptr++ = '\t';
1583             }
1584             strcpy(ptr, entries[i]);
1585             ptr += strlen(entries[i]);
1586             if (i != (numentries - 1))
1587             {
1588                 *ptr++ = ',';
1589             }
1590             if (fmt)
1591             {
1592                 *ptr++ = '\n';
1593             }
1594             *ptr = '\0';
1595             cJSON_free(names[i]);
1596             cJSON_free(entries[i]);
1597         }
1598
1599         cJSON_free(names);
1600         cJSON_free(entries);
1601         if (fmt)
1602         {
1603             for (i = 0; i < (depth - 1); i++)
1604             {
1605                 *ptr++ = '\t';
1606             }
1607         }
1608         *ptr++ = '}';
1609         *ptr++ = '\0';
1610     }
1611
1612     return out;
1613 }
1614
1615 /* Get Array size/item / object item. */
1616 int    cJSON_GetArraySize(const cJSON *array)
1617 {
1618     cJSON *c = array->child;
1619     int i = 0;
1620     while(c)
1621     {
1622         i++;
1623         c = c->next;
1624     }
1625     return i;
1626 }
1627
1628 cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
1629 {
1630     cJSON *c = array ? array->child : NULL;
1631     while (c && item > 0)
1632     {
1633         item--;
1634         c = c->next;
1635     }
1636
1637     return c;
1638 }
1639
1640 cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
1641 {
1642     cJSON *c = object ? object->child : NULL;
1643     while (c && cJSON_strcasecmp(c->string, string))
1644     {
1645         c = c->next;
1646     }
1647     return c;
1648 }
1649
1650 int cJSON_HasObjectItem(const cJSON *object,const char *string)
1651 {
1652     return cJSON_GetObjectItem(object, string) ? 1 : 0;
1653 }
1654
1655 /* Utility for array list handling. */
1656 static void suffix_object(cJSON *prev, cJSON *item)
1657 {
1658     prev->next = item;
1659     item->prev = prev;
1660 }
1661
1662 /* Utility for handling references. */
1663 static cJSON *create_reference(const cJSON *item)
1664 {
1665     cJSON *ref = cJSON_New_Item();
1666     if (!ref)
1667     {
1668         return NULL;
1669     }
1670     memcpy(ref, item, sizeof(cJSON));
1671     ref->string = NULL;
1672     ref->type |= cJSON_IsReference;
1673     ref->next = ref->prev = NULL;
1674     return ref;
1675 }
1676
1677 /* Add item to array/object. */
1678 void   cJSON_AddItemToArray(cJSON *array, cJSON *item)
1679 {
1680     cJSON *c = array->child;
1681     if (!item)
1682     {
1683         return;
1684     }
1685     if (!c)
1686     {
1687         /* list is empty, start new one */
1688         array->child = item;
1689     }
1690     else
1691     {
1692         /* append to the end */
1693         while (c->next)
1694         {
1695             c = c->next;
1696         }
1697         suffix_object(c, item);
1698     }
1699 }
1700
1701 void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
1702 {
1703     if (!item)
1704     {
1705         return;
1706     }
1707
1708     /* free old key and set new one */
1709     if (item->string)
1710     {
1711         cJSON_free(item->string);
1712     }
1713     item->string = cJSON_strdup(string);
1714
1715     cJSON_AddItemToArray(object,item);
1716 }
1717
1718 /* Add an item to an object with constant string as key */
1719 void   cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1720 {
1721     if (!item)
1722     {
1723         return;
1724     }
1725     if (!(item->type & cJSON_StringIsConst) && item->string)
1726     {
1727         cJSON_free(item->string);
1728     }
1729     item->string = (char*)string;
1730     item->type |= cJSON_StringIsConst;
1731     cJSON_AddItemToArray(object, item);
1732 }
1733
1734 void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1735 {
1736     cJSON_AddItemToArray(array, create_reference(item));
1737 }
1738
1739 void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1740 {
1741     cJSON_AddItemToObject(object, string, create_reference(item));
1742 }
1743
1744 cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
1745 {
1746     cJSON *c = array->child;
1747     while (c && (which > 0))
1748     {
1749         c = c->next;
1750         which--;
1751     }
1752     if (!c)
1753     {
1754         /* item doesn't exist */
1755         return NULL;
1756     }
1757     if (c->prev)
1758     {
1759         /* not the first element */
1760         c->prev->next = c->next;
1761     }
1762     if (c->next)
1763     {
1764         c->next->prev = c->prev;
1765     }
1766     if (c==array->child)
1767     {
1768         array->child = c->next;
1769     }
1770     /* make sure the detached item doesn't point anywhere anymore */
1771     c->prev = c->next = NULL;
1772
1773     return c;
1774 }
1775
1776 void cJSON_DeleteItemFromArray(cJSON *array, int which)
1777 {
1778     cJSON_Delete(cJSON_DetachItemFromArray(array, which));
1779 }
1780
1781 cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
1782 {
1783     int i = 0;
1784     cJSON *c = object->child;
1785     while (c && cJSON_strcasecmp(c->string,string))
1786     {
1787         i++;
1788         c = c->next;
1789     }
1790     if (c)
1791     {
1792         return cJSON_DetachItemFromArray(object, i);
1793     }
1794
1795     return NULL;
1796 }
1797
1798 void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1799 {
1800     cJSON_Delete(cJSON_DetachItemFromObject(object, string));
1801 }
1802
1803 /* Replace array/object items with new ones. */
1804 void cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1805 {
1806     cJSON *c = array->child;
1807     while (c && (which > 0))
1808     {
1809         c = c->next;
1810         which--;
1811     }
1812     if (!c)
1813     {
1814         cJSON_AddItemToArray(array, newitem);
1815         return;
1816     }
1817     newitem->next = c;
1818     newitem->prev = c->prev;
1819     c->prev = newitem;
1820     if (c == array->child)
1821     {
1822         array->child = newitem;
1823     }
1824     else
1825     {
1826         newitem->prev->next = newitem;
1827     }
1828 }
1829
1830 void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
1831 {
1832     cJSON *c = array->child;
1833     while (c && (which > 0))
1834     {
1835         c = c->next;
1836         which--;
1837     }
1838     if (!c)
1839     {
1840         return;
1841     }
1842     newitem->next = c->next;
1843     newitem->prev = c->prev;
1844     if (newitem->next)
1845     {
1846         newitem->next->prev = newitem;
1847     }
1848     if (c == array->child)
1849     {
1850         array->child = newitem;
1851     }
1852     else
1853     {
1854         newitem->prev->next = newitem;
1855     }
1856     c->next = c->prev = NULL;
1857     cJSON_Delete(c);
1858 }
1859
1860 void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1861 {
1862     int i = 0;
1863     cJSON *c = object->child;
1864     while(c && cJSON_strcasecmp(c->string, string))
1865     {
1866         i++;
1867         c = c->next;
1868     }
1869     if(c)
1870     {
1871         /* free the old string if not const */
1872         if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
1873         {
1874              cJSON_free(newitem->string);
1875         }
1876
1877         newitem->string = cJSON_strdup(string);
1878         cJSON_ReplaceItemInArray(object, i, newitem);
1879     }
1880 }
1881
1882 /* Create basic types: */
1883 cJSON *cJSON_CreateNull(void)
1884 {
1885     cJSON *item = cJSON_New_Item();
1886     if(item)
1887     {
1888         item->type = cJSON_NULL;
1889     }
1890
1891     return item;
1892 }
1893
1894 cJSON *cJSON_CreateTrue(void)
1895 {
1896     cJSON *item = cJSON_New_Item();
1897     if(item)
1898     {
1899         item->type = cJSON_True;
1900     }
1901
1902     return item;
1903 }
1904
1905 cJSON *cJSON_CreateFalse(void)
1906 {
1907     cJSON *item = cJSON_New_Item();
1908     if(item)
1909     {
1910         item->type = cJSON_False;
1911     }
1912
1913     return item;
1914 }
1915
1916 cJSON *cJSON_CreateBool(int b)
1917 {
1918     cJSON *item = cJSON_New_Item();
1919     if(item)
1920     {
1921         item->type = b ? cJSON_True : cJSON_False;
1922     }
1923
1924     return item;
1925 }
1926
1927 cJSON *cJSON_CreateNumber(double num)
1928 {
1929     cJSON *item = cJSON_New_Item();
1930     if(item)
1931     {
1932         item->type = cJSON_Number;
1933         item->valuedouble = num;
1934         item->valueint = (int)num;
1935     }
1936
1937     return item;
1938 }
1939
1940 cJSON *cJSON_CreateString(const char *string)
1941 {
1942     cJSON *item = cJSON_New_Item();
1943     if(item)
1944     {
1945         item->type = cJSON_String;
1946         item->valuestring = cJSON_strdup(string);
1947         if(!item->valuestring)
1948         {
1949             cJSON_Delete(item);
1950             return NULL;
1951         }
1952     }
1953
1954     return item;
1955 }
1956
1957 cJSON *cJSON_CreateArray(void)
1958 {
1959     cJSON *item = cJSON_New_Item();
1960     if(item)
1961     {
1962         item->type=cJSON_Array;
1963     }
1964
1965     return item;
1966 }
1967
1968 cJSON *cJSON_CreateObject(void)
1969 {
1970     cJSON *item = cJSON_New_Item();
1971     if (item)
1972     {
1973         item->type = cJSON_Object;
1974     }
1975
1976     return item;
1977 }
1978
1979 /* Create Arrays: */
1980 cJSON *cJSON_CreateIntArray(const int *numbers, int count)
1981 {
1982     int i = 0;
1983     cJSON *n = NULL;
1984     cJSON *p = NULL;
1985     cJSON *a = cJSON_CreateArray();
1986     for(i = 0; a && (i < count); i++)
1987     {
1988         n = cJSON_CreateNumber(numbers[i]);
1989         if (!n)
1990         {
1991             cJSON_Delete(a);
1992             return NULL;
1993         }
1994         if(!i)
1995         {
1996             a->child = n;
1997         }
1998         else
1999         {
2000             suffix_object(p, n);
2001         }
2002         p = n;
2003     }
2004
2005     return a;
2006 }
2007
2008 cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
2009 {
2010     int i = 0;
2011     cJSON *n = NULL;
2012     cJSON *p = NULL;
2013     cJSON *a = cJSON_CreateArray();
2014     for(i = 0; a && (i < count); i++)
2015     {
2016         n = cJSON_CreateNumber(numbers[i]);
2017         if(!n)
2018         {
2019             cJSON_Delete(a);
2020             return NULL;
2021         }
2022         if(!i)
2023         {
2024             a->child = n;
2025         }
2026         else
2027         {
2028             suffix_object(p, n);
2029         }
2030         p = n;
2031     }
2032
2033     return a;
2034 }
2035
2036 cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
2037 {
2038     int i = 0;
2039     cJSON *n = NULL;
2040     cJSON *p = NULL;
2041     cJSON *a = cJSON_CreateArray();
2042     for(i = 0;a && (i < count); i++)
2043     {
2044         n = cJSON_CreateNumber(numbers[i]);
2045         if(!n)
2046         {
2047             cJSON_Delete(a);
2048             return NULL;
2049         }
2050         if(!i)
2051         {
2052             a->child = n;
2053         }
2054         else
2055         {
2056             suffix_object(p, n);
2057         }
2058         p = n;
2059     }
2060
2061     return a;
2062 }
2063
2064 cJSON *cJSON_CreateStringArray(const char **strings, int count)
2065 {
2066     int i = 0;
2067     cJSON *n = NULL;
2068     cJSON *p = NULL;
2069     cJSON *a = cJSON_CreateArray();
2070     for (i = 0; a && (i < count); i++)
2071     {
2072         n = cJSON_CreateString(strings[i]);
2073         if(!n)
2074         {
2075             cJSON_Delete(a);
2076             return NULL;
2077         }
2078         if(!i)
2079         {
2080             a->child = n;
2081         }
2082         else
2083         {
2084             suffix_object(p,n);
2085         }
2086         p = n;
2087     }
2088
2089     return a;
2090 }
2091
2092 /* Duplication */
2093 cJSON *cJSON_Duplicate(const cJSON *item, int recurse)
2094 {
2095     cJSON *newitem = NULL;
2096     cJSON *cptr = NULL;
2097     cJSON *nptr = NULL;
2098     cJSON *newchild = NULL;
2099
2100     /* Bail on bad ptr */
2101     if (!item)
2102     {
2103         return NULL;
2104     }
2105     /* Create new item */
2106     newitem = cJSON_New_Item();
2107     if (!newitem)
2108     {
2109         return NULL;
2110     }
2111     /* Copy over all vars */
2112     newitem->type = item->type & (~cJSON_IsReference);
2113     newitem->valueint = item->valueint;
2114     newitem->valuedouble = item->valuedouble;
2115     if (item->valuestring)
2116     {
2117         newitem->valuestring = cJSON_strdup(item->valuestring);
2118         if (!newitem->valuestring)
2119         {
2120             cJSON_Delete(newitem);
2121             return NULL;
2122         }
2123     }
2124     if (item->string)
2125     {
2126         newitem->string = cJSON_strdup(item->string);
2127         if (!newitem->string)
2128         {
2129             cJSON_Delete(newitem);
2130             return NULL;
2131         }
2132     }
2133     /* If non-recursive, then we're done! */
2134     if (!recurse)
2135     {
2136         return newitem;
2137     }
2138     /* Walk the ->next chain for the child. */
2139     cptr = item->child;
2140     while (cptr)
2141     {
2142         newchild = cJSON_Duplicate(cptr, 1); /* Duplicate (with recurse) each item in the ->next chain */
2143         if (!newchild)
2144         {
2145             cJSON_Delete(newitem);
2146             return NULL;
2147         }
2148         if (nptr)
2149         {
2150             /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2151             nptr->next = newchild;
2152             newchild->prev = nptr;
2153             nptr = newchild;
2154         }
2155         else
2156         {
2157             /* Set newitem->child and move to it */
2158             newitem->child = newchild; nptr = newchild;
2159         }
2160         cptr = cptr->next;
2161     }
2162
2163     return newitem;
2164 }
2165
2166 void cJSON_Minify(char *json)
2167 {
2168     char *into = json;
2169     while (*json)
2170     {
2171         if (*json == ' ')
2172         {
2173             json++;
2174         }
2175         else if (*json == '\t')
2176         {
2177             /* Whitespace characters. */
2178             json++;
2179         }
2180         else if (*json == '\r')
2181         {
2182             json++;
2183         }
2184         else if (*json=='\n')
2185         {
2186             json++;
2187         }
2188         else if ((*json == '/') && (json[1] == '/'))
2189         {
2190             /* double-slash comments, to end of line. */
2191             while (*json && (*json != '\n'))
2192             {
2193                 json++;
2194             }
2195         }
2196         else if ((*json == '/') && (json[1] == '*'))
2197         {
2198             /* multiline comments. */
2199             while (*json && !((*json == '*') && (json[1] == '/')))
2200             {
2201                 json++;
2202             }
2203             json += 2;
2204         }
2205         else if (*json == '\"')
2206         {
2207             /* string literals, which are \" sensitive. */
2208             *into++ = *json++;
2209             while (*json && (*json != '\"'))
2210             {
2211                 if (*json == '\\')
2212                 {
2213                     *into++=*json++;
2214                 }
2215                 *into++ = *json++;
2216             }
2217             *into++ = *json++;
2218         }
2219         else
2220         {
2221             /* All other characters. */
2222             *into++ = *json++;
2223         }
2224     }
2225
2226     /* and null-terminate. */
2227     *into = '\0';
2228 }