Merge branch 'master' of https://github.com/json-c/json-c
[platform/upstream/json-c.git] / json_object.c
1 /*
2  * $Id: json_object.c,v 1.17 2006/07/25 03:24:50 mclark Exp $
3  *
4  * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5  * Michael Clark <michael@metaparadigm.com>
6  * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the MIT license. See COPYING for details.
10  *
11  */
12
13 #include "config.h"
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <stddef.h>
18 #include <string.h>
19
20 #include "debug.h"
21 #include "printbuf.h"
22 #include "linkhash.h"
23 #include "arraylist.h"
24 #include "json_inttypes.h"
25 #include "json_object.h"
26 #include "json_object_private.h"
27 #include "json_util.h"
28
29 #if !defined(HAVE_STRDUP) && defined(_MSC_VER)
30   /* MSC has the version as _strdup */
31 # define strdup _strdup
32 #elif !defined(HAVE_STRDUP)
33 # error You do not have strdup on your system.
34 #endif /* HAVE_STRDUP */
35
36 #if !defined(HAVE_STRNDUP)
37   char* strndup(const char* str, size_t n);
38 #endif /* !HAVE_STRNDUP */
39
40 // Don't define this.  It's not thread-safe.
41 /* #define REFCOUNT_DEBUG 1 */
42
43 const char *json_number_chars = "0123456789.+-eE";
44 const char *json_hex_chars = "0123456789abcdefABCDEF";
45
46 static void json_object_generic_delete(struct json_object* jso);
47 static struct json_object* json_object_new(enum json_type o_type);
48
49 static json_object_to_json_string_fn json_object_object_to_json_string;
50 static json_object_to_json_string_fn json_object_boolean_to_json_string;
51 static json_object_to_json_string_fn json_object_int_to_json_string;
52 static json_object_to_json_string_fn json_object_double_to_json_string;
53 static json_object_to_json_string_fn json_object_string_to_json_string;
54 static json_object_to_json_string_fn json_object_array_to_json_string;
55
56
57 /* ref count debugging */
58
59 #ifdef REFCOUNT_DEBUG
60
61 static struct lh_table *json_object_table;
62
63 static void json_object_init(void) __attribute__ ((constructor));
64 static void json_object_init(void) {
65   MC_DEBUG("json_object_init: creating object table\n");
66   json_object_table = lh_kptr_table_new(128, "json_object_table", NULL);
67 }
68
69 static void json_object_fini(void) __attribute__ ((destructor));
70 static void json_object_fini(void) {
71   struct lh_entry *ent;
72   if(MC_GET_DEBUG()) {
73     if (json_object_table->count) {
74       MC_DEBUG("json_object_fini: %d referenced objects at exit\n",
75                json_object_table->count);
76       lh_foreach(json_object_table, ent) {
77         struct json_object* obj = (struct json_object*)ent->v;
78         MC_DEBUG("\t%s:%p\n", json_type_to_name(obj->o_type), obj);
79       }
80     }
81   }
82   MC_DEBUG("json_object_fini: freeing object table\n");
83   lh_table_free(json_object_table);
84 }
85 #endif /* REFCOUNT_DEBUG */
86
87
88 /* string escaping */
89
90 static int json_escape_str(struct printbuf *pb, char *str, int len)
91 {
92   int pos = 0, start_offset = 0;
93   unsigned char c;
94   while (len--) {
95     c = str[pos];
96     switch(c) {
97     case '\b':
98     case '\n':
99     case '\r':
100     case '\t':
101     case '"':
102     case '\\':
103     case '/':
104       if(pos - start_offset > 0)
105         printbuf_memappend(pb, str + start_offset, pos - start_offset);
106       if(c == '\b') printbuf_memappend(pb, "\\b", 2);
107       else if(c == '\n') printbuf_memappend(pb, "\\n", 2);
108       else if(c == '\r') printbuf_memappend(pb, "\\r", 2);
109       else if(c == '\t') printbuf_memappend(pb, "\\t", 2);
110       else if(c == '"') printbuf_memappend(pb, "\\\"", 2);
111       else if(c == '\\') printbuf_memappend(pb, "\\\\", 2);
112       else if(c == '/') printbuf_memappend(pb, "\\/", 2);
113       start_offset = ++pos;
114       break;
115     default:
116       if(c < ' ') {
117         if(pos - start_offset > 0)
118           printbuf_memappend(pb, str + start_offset, pos - start_offset);
119         sprintbuf(pb, "\\u00%c%c",
120                   json_hex_chars[c >> 4],
121                   json_hex_chars[c & 0xf]);
122         start_offset = ++pos;
123       } else pos++;
124     }
125   }
126   if(pos - start_offset > 0)
127     printbuf_memappend(pb, str + start_offset, pos - start_offset);
128   return 0;
129 }
130
131
132 /* reference counting */
133
134 extern struct json_object* json_object_get(struct json_object *jso)
135 {
136   if(jso) {
137     jso->_ref_count++;
138   }
139   return jso;
140 }
141
142 int json_object_put(struct json_object *jso)
143 {
144         if(jso)
145         {
146                 jso->_ref_count--;
147                 if(!jso->_ref_count)
148                 {
149                         if (jso->_user_delete)
150                                 jso->_user_delete(jso, jso->_userdata);
151                         jso->_delete(jso);
152                         return 1;
153                 }
154         }
155         return 0;
156 }
157
158
159 /* generic object construction and destruction parts */
160
161 static void json_object_generic_delete(struct json_object* jso)
162 {
163 #ifdef REFCOUNT_DEBUG
164   MC_DEBUG("json_object_delete_%s: %p\n",
165            json_type_to_name(jso->o_type), jso);
166   lh_table_delete(json_object_table, jso);
167 #endif /* REFCOUNT_DEBUG */
168   printbuf_free(jso->_pb);
169   free(jso);
170 }
171
172 static struct json_object* json_object_new(enum json_type o_type)
173 {
174   struct json_object *jso;
175
176   jso = (struct json_object*)calloc(sizeof(struct json_object), 1);
177   if(!jso) return NULL;
178   jso->o_type = o_type;
179   jso->_ref_count = 1;
180   jso->_delete = &json_object_generic_delete;
181 #ifdef REFCOUNT_DEBUG
182   lh_table_insert(json_object_table, jso, jso);
183   MC_DEBUG("json_object_new_%s: %p\n", json_type_to_name(jso->o_type), jso);
184 #endif /* REFCOUNT_DEBUG */
185   return jso;
186 }
187
188
189 /* type checking functions */
190
191 int json_object_is_type(struct json_object *jso, enum json_type type)
192 {
193   if (!jso)
194     return (type == json_type_null);
195   return (jso->o_type == type);
196 }
197
198 enum json_type json_object_get_type(struct json_object *jso)
199 {
200   if (!jso)
201     return json_type_null;
202   return jso->o_type;
203 }
204
205 /* set a custom conversion to string */
206
207 void json_object_set_serializer(json_object *jso,
208         json_object_to_json_string_fn to_string_func,
209         void *userdata,
210         json_object_delete_fn *user_delete)
211 {
212         // First, clean up any previously existing user info
213         if (jso->_user_delete)
214         {
215                 jso->_user_delete(jso, jso->_userdata);
216         }
217         jso->_userdata = NULL;
218         jso->_user_delete = NULL;
219
220         if (to_string_func == NULL)
221         {
222                 // Reset to the standard serialization function
223                 switch(jso->o_type)
224                 {
225                 case json_type_null:
226                         jso->_to_json_string = NULL;
227                         break;
228                 case json_type_boolean:
229                         jso->_to_json_string = &json_object_boolean_to_json_string;
230                         break;
231                 case json_type_double:
232                         jso->_to_json_string = &json_object_double_to_json_string;
233                         break;
234                 case json_type_int:
235                         jso->_to_json_string = &json_object_int_to_json_string;
236                         break;
237                 case json_type_object:
238                         jso->_to_json_string = &json_object_object_to_json_string;
239                         break;
240                 case json_type_array:
241                         jso->_to_json_string = &json_object_array_to_json_string;
242                         break;
243                 case json_type_string:
244                         jso->_to_json_string = &json_object_string_to_json_string;
245                         break;
246                 }
247                 return;
248         }
249
250         jso->_to_json_string = to_string_func;
251         jso->_userdata = userdata;
252         jso->_user_delete = user_delete;
253 }
254
255
256 /* extended conversion to string */
257
258 const char* json_object_to_json_string_ext(struct json_object *jso, int flags)
259 {
260         if (!jso)
261                 return "null";
262
263         if ((!jso->_pb) && !(jso->_pb = printbuf_new()))
264                 return NULL;
265
266         printbuf_reset(jso->_pb);
267
268         if(jso->_to_json_string(jso, jso->_pb, 0, flags) < 0)
269                 return NULL;
270
271         return jso->_pb->buf;
272 }
273
274 /* backwards-compatible conversion to string */
275
276 const char* json_object_to_json_string(struct json_object *jso)
277 {
278         return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
279 }
280
281 static void indent(struct printbuf *pb, int level, int flags)
282 {
283         if (flags & JSON_C_TO_STRING_PRETTY)
284         {
285                 printbuf_memset(pb, -1, ' ', level * 2);
286         }
287 }
288
289 /* json_object_object */
290
291 static int json_object_object_to_json_string(struct json_object* jso,
292                                              struct printbuf *pb,
293                                              int level,
294                                                  int flags)
295 {
296         int had_children = 0;
297         struct json_object_iter iter;
298
299         sprintbuf(pb, "{" /*}*/);
300         if (flags & JSON_C_TO_STRING_PRETTY)
301                 sprintbuf(pb, "\n");
302         json_object_object_foreachC(jso, iter)
303         {
304                 if (had_children)
305                 {
306                         sprintbuf(pb, ",");
307                         if (flags & JSON_C_TO_STRING_PRETTY)
308                                 sprintbuf(pb, "\n");
309                 }
310                 had_children = 1;
311                 if (flags & JSON_C_TO_STRING_SPACED)
312                         sprintbuf(pb, " ");
313                 indent(pb, level+1, flags);
314                 sprintbuf(pb, "\"");
315                 json_escape_str(pb, iter.key, strlen(iter.key));
316                 if (flags & JSON_C_TO_STRING_SPACED)
317                         sprintbuf(pb, "\": ");
318                 else
319                         sprintbuf(pb, "\":");
320                 if(iter.val == NULL)
321                         sprintbuf(pb, "null");
322                 else
323                         iter.val->_to_json_string(iter.val, pb, level+1,flags);
324         }
325         if (flags & JSON_C_TO_STRING_PRETTY)
326         {
327                 if (had_children)
328                         sprintbuf(pb, "\n");
329                 indent(pb,level,flags);
330         }
331         if (flags & JSON_C_TO_STRING_SPACED)
332                 return sprintbuf(pb, /*{*/ " }");
333         else
334                 return sprintbuf(pb, /*{*/ "}");
335 }
336
337
338 static void json_object_lh_entry_free(struct lh_entry *ent)
339 {
340   free(ent->k);
341   json_object_put((struct json_object*)ent->v);
342 }
343
344 static void json_object_object_delete(struct json_object* jso)
345 {
346   lh_table_free(jso->o.c_object);
347   json_object_generic_delete(jso);
348 }
349
350 struct json_object* json_object_new_object(void)
351 {
352   struct json_object *jso = json_object_new(json_type_object);
353   if(!jso) return NULL;
354   jso->_delete = &json_object_object_delete;
355   jso->_to_json_string = &json_object_object_to_json_string;
356   jso->o.c_object = lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES,
357                                         NULL, &json_object_lh_entry_free);
358   return jso;
359 }
360
361 struct lh_table* json_object_get_object(struct json_object *jso)
362 {
363   if(!jso) return NULL;
364   switch(jso->o_type) {
365   case json_type_object:
366     return jso->o.c_object;
367   default:
368     return NULL;
369   }
370 }
371
372 void json_object_object_add(struct json_object* jso, const char *key,
373                             struct json_object *val)
374 {
375         // We lookup the entry and replace the value, rather than just deleting
376         // and re-adding it, so the existing key remains valid.
377         json_object *existing_value = NULL;
378         struct lh_entry *existing_entry;
379         existing_entry = lh_table_lookup_entry(jso->o.c_object, (void*)key);
380         if (!existing_entry)
381         {
382                 lh_table_insert(jso->o.c_object, strdup(key), val);
383                 return;
384         }
385         existing_value = (void *)existing_entry->v;
386         if (existing_value)
387                 json_object_put(existing_value);
388         existing_entry->v = val;
389 }
390
391 struct json_object* json_object_object_get(struct json_object* jso, const char *key)
392 {
393         struct json_object *result = NULL;
394         json_object_object_get_ex(jso, key, &result);
395         return result;
396 }
397
398 json_bool json_object_object_get_ex(struct json_object* jso, const char *key, struct json_object **value)
399 {
400         if (value != NULL)
401                 *value = NULL;
402
403         if (NULL == jso)
404                 return FALSE;
405
406         switch(jso->o_type)
407         {
408         case json_type_object:
409                 return lh_table_lookup_ex(jso->o.c_object, (void*)key, (void**)value);
410         default:
411                 if (value != NULL)
412                         *value = NULL;
413                 return FALSE;
414         }
415 }
416
417 void json_object_object_del(struct json_object* jso, const char *key)
418 {
419         lh_table_delete(jso->o.c_object, key);
420 }
421
422
423 /* json_object_boolean */
424
425 static int json_object_boolean_to_json_string(struct json_object* jso,
426                                               struct printbuf *pb,
427                                               int level,
428                                                   int flags)
429 {
430   if(jso->o.c_boolean) return sprintbuf(pb, "true");
431   else return sprintbuf(pb, "false");
432 }
433
434 struct json_object* json_object_new_boolean(json_bool b)
435 {
436   struct json_object *jso = json_object_new(json_type_boolean);
437   if(!jso) return NULL;
438   jso->_to_json_string = &json_object_boolean_to_json_string;
439   jso->o.c_boolean = b;
440   return jso;
441 }
442
443 json_bool json_object_get_boolean(struct json_object *jso)
444 {
445   if(!jso) return FALSE;
446   switch(jso->o_type) {
447   case json_type_boolean:
448     return jso->o.c_boolean;
449   case json_type_int:
450     return (jso->o.c_int64 != 0);
451   case json_type_double:
452     return (jso->o.c_double != 0);
453   case json_type_string:
454     return (jso->o.c_string.len != 0);
455   default:
456     return FALSE;
457   }
458 }
459
460
461 /* json_object_int */
462
463 static int json_object_int_to_json_string(struct json_object* jso,
464                                           struct printbuf *pb,
465                                           int level,
466                                           int flags)
467 {
468   return sprintbuf(pb, "%"PRId64, jso->o.c_int64);
469 }
470
471 struct json_object* json_object_new_int(int32_t i)
472 {
473   struct json_object *jso = json_object_new(json_type_int);
474   if(!jso) return NULL;
475   jso->_to_json_string = &json_object_int_to_json_string;
476   jso->o.c_int64 = i;
477   return jso;
478 }
479
480 int32_t json_object_get_int(struct json_object *jso)
481 {
482   int64_t cint64;
483   enum json_type o_type;
484
485   if(!jso) return 0;
486
487   o_type = jso->o_type;
488   cint64 = jso->o.c_int64;
489
490   if (o_type == json_type_string)
491   {
492         /*
493          * Parse strings into 64-bit numbers, then use the
494          * 64-to-32-bit number handling below.
495          */
496         if (json_parse_int64(jso->o.c_string.str, &cint64) != 0)
497                 return 0; /* whoops, it didn't work. */
498         o_type = json_type_int;
499   }
500
501   switch(o_type) {
502   case json_type_int:
503         /* Make sure we return the correct values for out of range numbers. */
504         if (cint64 <= INT32_MIN)
505                 return INT32_MIN;
506         else if (cint64 >= INT32_MAX)
507                 return INT32_MAX;
508         else
509                 return (int32_t)cint64;
510   case json_type_double:
511     return (int32_t)jso->o.c_double;
512   case json_type_boolean:
513     return jso->o.c_boolean;
514   default:
515     return 0;
516   }
517 }
518
519 struct json_object* json_object_new_int64(int64_t i)
520 {
521   struct json_object *jso = json_object_new(json_type_int);
522   if(!jso) return NULL;
523   jso->_to_json_string = &json_object_int_to_json_string;
524   jso->o.c_int64 = i;
525   return jso;
526 }
527
528 int64_t json_object_get_int64(struct json_object *jso)
529 {
530    int64_t cint;
531
532   if(!jso) return 0;
533   switch(jso->o_type) {
534   case json_type_int:
535     return jso->o.c_int64;
536   case json_type_double:
537     return (int64_t)jso->o.c_double;
538   case json_type_boolean:
539     return jso->o.c_boolean;
540   case json_type_string:
541         if (json_parse_int64(jso->o.c_string.str, &cint) == 0) return cint;
542   default:
543     return 0;
544   }
545 }
546
547
548 /* json_object_double */
549
550 static int json_object_double_to_json_string(struct json_object* jso,
551                                              struct printbuf *pb,
552                                              int level,
553                                                  int flags)
554 {
555   return sprintbuf(pb, "%f", jso->o.c_double);
556 }
557
558 struct json_object* json_object_new_double(double d)
559 {
560   struct json_object *jso = json_object_new(json_type_double);
561   if(!jso) return NULL;
562   jso->_to_json_string = &json_object_double_to_json_string;
563   jso->o.c_double = d;
564   return jso;
565 }
566
567 double json_object_get_double(struct json_object *jso)
568 {
569   double cdouble;
570
571   if(!jso) return 0.0;
572   switch(jso->o_type) {
573   case json_type_double:
574     return jso->o.c_double;
575   case json_type_int:
576     return jso->o.c_int64;
577   case json_type_boolean:
578     return jso->o.c_boolean;
579   case json_type_string:
580     if(sscanf(jso->o.c_string.str, "%lf", &cdouble) == 1) return cdouble;
581   default:
582     return 0.0;
583   }
584 }
585
586
587 /* json_object_string */
588
589 static int json_object_string_to_json_string(struct json_object* jso,
590                                              struct printbuf *pb,
591                                              int level,
592                                                  int flags)
593 {
594   sprintbuf(pb, "\"");
595   json_escape_str(pb, jso->o.c_string.str, jso->o.c_string.len);
596   sprintbuf(pb, "\"");
597   return 0;
598 }
599
600 static void json_object_string_delete(struct json_object* jso)
601 {
602   free(jso->o.c_string.str);
603   json_object_generic_delete(jso);
604 }
605
606 struct json_object* json_object_new_string(const char *s)
607 {
608   struct json_object *jso = json_object_new(json_type_string);
609   if(!jso) return NULL;
610   jso->_delete = &json_object_string_delete;
611   jso->_to_json_string = &json_object_string_to_json_string;
612   jso->o.c_string.str = strdup(s);
613   jso->o.c_string.len = strlen(s);
614   return jso;
615 }
616
617 struct json_object* json_object_new_string_len(const char *s, int len)
618 {
619   struct json_object *jso = json_object_new(json_type_string);
620   if(!jso) return NULL;
621   jso->_delete = &json_object_string_delete;
622   jso->_to_json_string = &json_object_string_to_json_string;
623   jso->o.c_string.str = (char*)malloc(len + 1);
624   memcpy(jso->o.c_string.str, (void *)s, len);
625   jso->o.c_string.str[len] = '\0';
626   jso->o.c_string.len = len;
627   return jso;
628 }
629
630 const char* json_object_get_string(struct json_object *jso)
631 {
632   if(!jso) return NULL;
633   switch(jso->o_type) {
634   case json_type_string:
635     return jso->o.c_string.str;
636   default:
637     return json_object_to_json_string(jso);
638   }
639 }
640
641 int json_object_get_string_len(struct json_object *jso)  {
642   if(!jso) return 0;
643   switch(jso->o_type) {
644   case json_type_string:
645     return jso->o.c_string.len;
646   default:
647     return 0;
648   }
649 }
650
651
652 /* json_object_array */
653
654 static int json_object_array_to_json_string(struct json_object* jso,
655                                             struct printbuf *pb,
656                                             int level,
657                                             int flags)
658 {
659         int had_children = 0;
660         int ii;
661         sprintbuf(pb, "[");
662         if (flags & JSON_C_TO_STRING_PRETTY)
663                 sprintbuf(pb, "\n");
664         for(ii=0; ii < json_object_array_length(jso); ii++)
665         {
666                 struct json_object *val;
667                 if (had_children)
668                 {
669                         sprintbuf(pb, ",");
670                         if (flags & JSON_C_TO_STRING_PRETTY)
671                                 sprintbuf(pb, "\n");
672                 }
673                 had_children = 1;
674                 if (flags & JSON_C_TO_STRING_SPACED)
675                         sprintbuf(pb, " ");
676                 indent(pb, level + 1, flags);
677                 val = json_object_array_get_idx(jso, ii);
678                 if(val == NULL)
679                         sprintbuf(pb, "null");
680                 else
681                         val->_to_json_string(val, pb, level+1, flags);
682         }
683         if (flags & JSON_C_TO_STRING_PRETTY)
684         {
685                 if (had_children)
686                         sprintbuf(pb, "\n");
687                 indent(pb,level,flags);
688         }
689
690         if (flags & JSON_C_TO_STRING_SPACED)
691                 return sprintbuf(pb, " ]");
692         else
693                 return sprintbuf(pb, "]");
694 }
695
696 static void json_object_array_entry_free(void *data)
697 {
698   json_object_put((struct json_object*)data);
699 }
700
701 static void json_object_array_delete(struct json_object* jso)
702 {
703   array_list_free(jso->o.c_array);
704   json_object_generic_delete(jso);
705 }
706
707 struct json_object* json_object_new_array(void)
708 {
709   struct json_object *jso = json_object_new(json_type_array);
710   if(!jso) return NULL;
711   jso->_delete = &json_object_array_delete;
712   jso->_to_json_string = &json_object_array_to_json_string;
713   jso->o.c_array = array_list_new(&json_object_array_entry_free);
714   return jso;
715 }
716
717 struct array_list* json_object_get_array(struct json_object *jso)
718 {
719   if(!jso) return NULL;
720   switch(jso->o_type) {
721   case json_type_array:
722     return jso->o.c_array;
723   default:
724     return NULL;
725   }
726 }
727
728 void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *, const void *))
729 {
730   array_list_sort(jso->o.c_array, sort_fn);
731 }
732
733 int json_object_array_length(struct json_object *jso)
734 {
735   return array_list_length(jso->o.c_array);
736 }
737
738 int json_object_array_add(struct json_object *jso,struct json_object *val)
739 {
740   return array_list_add(jso->o.c_array, val);
741 }
742
743 int json_object_array_put_idx(struct json_object *jso, int idx,
744                               struct json_object *val)
745 {
746   return array_list_put_idx(jso->o.c_array, idx, val);
747 }
748
749 struct json_object* json_object_array_get_idx(struct json_object *jso,
750                                               int idx)
751 {
752   return (struct json_object*)array_list_get_idx(jso->o.c_array, idx);
753 }
754