Bump to 0.17
[platform/upstream/json-c.git] / json_object.h
1 /*
2  * $Id: json_object.h,v 1.12 2006/01/30 23:07:57 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 /**
14  * @file
15  * @brief Core json-c API.  Start here, or with json_tokener.h
16  */
17 #ifndef _json_object_h_
18 #define _json_object_h_
19
20 #ifdef __GNUC__
21 #define JSON_C_CONST_FUNCTION(func) func __attribute__((const))
22 #else
23 #define JSON_C_CONST_FUNCTION(func) func
24 #endif
25
26 #include "json_inttypes.h"
27 #include "json_types.h"
28 #include "printbuf.h"
29
30 #include <stddef.h>
31
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35
36 #define JSON_OBJECT_DEF_HASH_ENTRIES 16
37
38 /**
39  * A flag for the json_object_to_json_string_ext() and
40  * json_object_to_file_ext() functions which causes the output
41  * to have no extra whitespace or formatting applied.
42  */
43 #define JSON_C_TO_STRING_PLAIN 0
44 /**
45  * A flag for the json_object_to_json_string_ext() and
46  * json_object_to_file_ext() functions which causes the output to have
47  * minimal whitespace inserted to make things slightly more readable.
48  */
49 #define JSON_C_TO_STRING_SPACED (1 << 0)
50 /**
51  * A flag for the json_object_to_json_string_ext() and
52  * json_object_to_file_ext() functions which causes
53  * the output to be formatted.
54  *
55  * See the "Two Space Tab" option at https://jsonformatter.curiousconcept.com/
56  * for an example of the format.
57  */
58 #define JSON_C_TO_STRING_PRETTY (1 << 1)
59 /**
60  * A flag for the json_object_to_json_string_ext() and
61  * json_object_to_file_ext() functions which causes
62  * the output to be formatted.
63  *
64  * Instead of a "Two Space Tab" this gives a single tab character.
65  */
66 #define JSON_C_TO_STRING_PRETTY_TAB (1 << 3)
67 /**
68  * A flag to drop trailing zero for float values
69  */
70 #define JSON_C_TO_STRING_NOZERO (1 << 2)
71
72 /**
73  * Don't escape forward slashes.
74  */
75 #define JSON_C_TO_STRING_NOSLASHESCAPE (1 << 4)
76
77 /**
78  * A flag for the json_object_to_json_string_ext() and
79  * json_object_to_file_ext() functions which causes
80  * the output to be formatted.
81  *
82  * Use color for printing json.
83  */
84 #define JSON_C_TO_STRING_COLOR (1 << 5)
85
86 /**
87  * A flag for the json_object_object_add_ex function which
88  * causes the value to be added without a check if it already exists.
89  * Note: it is the responsibility of the caller to ensure that no
90  * key is added multiple times. If this is done, results are
91  * unpredictable. While this option is somewhat dangerous, it
92  * permits potentially large performance savings in code that
93  * knows for sure the key values are unique (e.g. because the
94  * code adds a well-known set of constant key values).
95  */
96 #define JSON_C_OBJECT_ADD_KEY_IS_NEW (1 << 1)
97 /**
98  * A flag for the json_object_object_add_ex function which
99  * flags the key as being constant memory. This means that
100  * the key will NOT be copied via strdup(), resulting in a
101  * potentially huge performance win (malloc, strdup and
102  * free are usually performance hogs). It is acceptable to
103  * use this flag for keys in non-constant memory blocks if
104  * the caller ensure that the memory holding the key lives
105  * longer than the corresponding json object. However, this
106  * is somewhat dangerous and should only be done if really
107  * justified.
108  * The general use-case for this flag is cases where the
109  * key is given as a real constant value in the function
110  * call, e.g. as in
111  *   json_object_object_add_ex(obj, "ip", json,
112  *       JSON_C_OBJECT_ADD_CONSTANT_KEY);
113  */
114 #define JSON_C_OBJECT_ADD_CONSTANT_KEY (1 << 2)
115 /**
116  * This flag is an alias to JSON_C_OBJECT_ADD_CONSTANT_KEY.
117  * Historically, this flag was used first and the new name
118  * JSON_C_OBJECT_ADD_CONSTANT_KEY was introduced for version
119  * 0.16.00 in order to have regular naming.
120  * Use of this flag is now legacy.
121  */
122 #define JSON_C_OBJECT_KEY_IS_CONSTANT  JSON_C_OBJECT_ADD_CONSTANT_KEY
123
124 /**
125  * Set the global value of an option, which will apply to all
126  * current and future threads that have not set a thread-local value.
127  *
128  * @see json_c_set_serialization_double_format
129  */
130 #define JSON_C_OPTION_GLOBAL (0)
131 /**
132  * Set a thread-local value of an option, overriding the global value.
133  * This will fail if json-c is not compiled with threading enabled, and
134  * with the __thread specifier (or equivalent) available.
135  *
136  * @see json_c_set_serialization_double_format
137  */
138 #define JSON_C_OPTION_THREAD (1)
139
140 /* reference counting functions */
141
142 /**
143  * Increment the reference count of json_object, thereby taking ownership of it.
144  *
145  * Cases where you might need to increase the refcount include:
146  * - Using an object field or array index (retrieved through
147  *    `json_object_object_get()` or `json_object_array_get_idx()`)
148  *    beyond the lifetime of the parent object.
149  * - Detaching an object field or array index from its parent object
150  *    (using `json_object_object_del()` or `json_object_array_del_idx()`)
151  * - Sharing a json_object with multiple (not necessarily parallel) threads
152  *    of execution that all expect to free it (with `json_object_put()`) when
153  *    they're done.
154  *
155  * @param obj the json_object instance
156  * @see json_object_put()
157  * @see json_object_object_get()
158  * @see json_object_array_get_idx()
159  */
160 JSON_EXPORT struct json_object *json_object_get(struct json_object *obj);
161
162 /**
163  * Decrement the reference count of json_object and free if it reaches zero.
164  *
165  * You must have ownership of obj prior to doing this or you will cause an
166  * imbalance in the reference count, leading to a classic use-after-free bug.
167  * In particular, you normally do not need to call `json_object_put()` on the
168  * json_object returned by `json_object_object_get()` or `json_object_array_get_idx()`.
169  *
170  * Just like after calling `free()` on a block of memory, you must not use
171  * `obj` after calling `json_object_put()` on it or any object that it
172  * is a member of (unless you know you've called `json_object_get(obj)` to
173  * explicitly increment the refcount).
174  *
175  * NULL may be passed, which which case this is a no-op.
176  *
177  * @param obj the json_object instance
178  * @returns 1 if the object was freed.
179  * @see json_object_get()
180  */
181 JSON_EXPORT int json_object_put(struct json_object *obj);
182
183 /**
184  * Check if the json_object is of a given type
185  * @param obj the json_object instance
186  * @param type one of:
187      json_type_null (i.e. obj == NULL),
188      json_type_boolean,
189      json_type_double,
190      json_type_int,
191      json_type_object,
192      json_type_array,
193      json_type_string
194  */
195 JSON_EXPORT int json_object_is_type(const struct json_object *obj, enum json_type type);
196
197 /**
198  * Get the type of the json_object.  See also json_type_to_name() to turn this
199  * into a string suitable, for instance, for logging.
200  *
201  * @param obj the json_object instance
202  * @returns type being one of:
203      json_type_null (i.e. obj == NULL),
204      json_type_boolean,
205      json_type_double,
206      json_type_int,
207      json_type_object,
208      json_type_array,
209      json_type_string
210  */
211 JSON_EXPORT enum json_type json_object_get_type(const struct json_object *obj);
212
213 /** Stringify object to json format.
214  * Equivalent to json_object_to_json_string_ext(obj, JSON_C_TO_STRING_SPACED)
215  * The pointer you get is an internal of your json object. You don't
216  * have to free it, later use of json_object_put() should be sufficient.
217  * If you can not ensure there's no concurrent access to *obj use
218  * strdup().
219  * @param obj the json_object instance
220  * @returns a string in JSON format
221  */
222 JSON_EXPORT const char *json_object_to_json_string(struct json_object *obj);
223
224 /** Stringify object to json format
225  * @see json_object_to_json_string() for details on how to free string.
226  * @param obj the json_object instance
227  * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
228  * @returns a string in JSON format
229  */
230 JSON_EXPORT const char *json_object_to_json_string_ext(struct json_object *obj, int flags);
231
232 /** Stringify object to json format
233  * @see json_object_to_json_string() for details on how to free string.
234  * @param obj the json_object instance
235  * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
236  * @param length a pointer where, if not NULL, the length (without null) is stored
237  * @returns a string in JSON format and the length if not NULL
238  */
239 JSON_EXPORT const char *json_object_to_json_string_length(struct json_object *obj, int flags,
240                                                           size_t *length);
241
242 /**
243  * Returns the userdata set by json_object_set_userdata() or
244  * json_object_set_serializer()
245  *
246  * @param jso the object to return the userdata for
247  */
248 JSON_EXPORT void *json_object_get_userdata(json_object *jso);
249
250 /**
251  * Set an opaque userdata value for an object
252  *
253  * The userdata can be retrieved using json_object_get_userdata().
254  *
255  * If custom userdata is already set on this object, any existing user_delete
256  * function is called before the new one is set.
257  *
258  * The user_delete parameter is optional and may be passed as NULL, even if
259  * the userdata parameter is non-NULL.  It will be called just before the
260  * json_object is deleted, after it's reference count goes to zero
261  * (see json_object_put()).
262  * If this is not provided, it is up to the caller to free the userdata at
263  * an appropriate time. (i.e. after the json_object is deleted)
264  *
265  * Note: Objects created by parsing strings may have custom serializers set
266  * which expect the userdata to contain specific data (due to use of
267  * json_object_new_double_s()). In this case, json_object_set_serialiser() with
268  * NULL as to_string_func should be used instead to set the userdata and reset
269  * the serializer to its default value.
270  *
271  * @param jso the object to set the userdata for
272  * @param userdata an optional opaque cookie
273  * @param user_delete an optional function from freeing userdata
274  */
275 JSON_EXPORT void json_object_set_userdata(json_object *jso, void *userdata,
276                                           json_object_delete_fn *user_delete);
277
278 /**
279  * Set a custom serialization function to be used when this particular object
280  * is converted to a string by json_object_to_json_string.
281  *
282  * If custom userdata is already set on this object, any existing user_delete
283  * function is called before the new one is set.
284  *
285  * If to_string_func is NULL the default behaviour is reset (but the userdata
286  * and user_delete fields are still set).
287  *
288  * The userdata parameter is optional and may be passed as NULL. It can be used
289  * to provide additional data for to_string_func to use. This parameter may
290  * be NULL even if user_delete is non-NULL.
291  *
292  * The user_delete parameter is optional and may be passed as NULL, even if
293  * the userdata parameter is non-NULL.  It will be called just before the
294  * json_object is deleted, after it's reference count goes to zero
295  * (see json_object_put()).
296  * If this is not provided, it is up to the caller to free the userdata at
297  * an appropriate time. (i.e. after the json_object is deleted)
298  *
299  * Note that the userdata is the same as set by json_object_set_userdata(), so
300  * care must be taken not to overwrite the value when both a custom serializer
301  * and json_object_set_userdata() are used.
302  *
303  * @param jso the object to customize
304  * @param to_string_func the custom serialization function
305  * @param userdata an optional opaque cookie
306  * @param user_delete an optional function from freeing userdata
307  */
308 JSON_EXPORT void json_object_set_serializer(json_object *jso,
309                                             json_object_to_json_string_fn *to_string_func,
310                                             void *userdata, json_object_delete_fn *user_delete);
311
312 #ifdef __clang__
313 /*
314  * Clang doesn't pay attention to the parameters defined in the
315  * function typedefs used here, so turn off spurious doc warnings.
316  * {
317  */
318 #pragma clang diagnostic push
319 #pragma clang diagnostic ignored "-Wdocumentation"
320 #endif
321
322 /**
323  * Simply call free on the userdata pointer.
324  * Can be used with json_object_set_serializer().
325  *
326  * @param jso unused
327  * @param userdata the pointer that is passed to free().
328  */
329 JSON_EXPORT json_object_delete_fn json_object_free_userdata;
330
331 /**
332  * Copy the jso->_userdata string over to pb as-is.
333  * Can be used with json_object_set_serializer().
334  *
335  * @param jso The object whose _userdata is used.
336  * @param pb The destination buffer.
337  * @param level Ignored.
338  * @param flags Ignored.
339  */
340 JSON_EXPORT json_object_to_json_string_fn json_object_userdata_to_json_string;
341
342 #ifdef __clang__
343 /* } */
344 #pragma clang diagnostic pop
345 #endif
346
347 /* object type methods */
348
349 /** Create a new empty object with a reference count of 1.  The caller of
350  * this object initially has sole ownership.  Remember, when using
351  * json_object_object_add or json_object_array_put_idx, ownership will
352  * transfer to the object/array.  Call json_object_get if you want to maintain
353  * shared ownership or also add this object as a child of multiple objects or
354  * arrays.  Any ownerships you acquired but did not transfer must be released
355  * through json_object_put.
356  *
357  * @returns a json_object of type json_type_object
358  */
359 JSON_EXPORT struct json_object *json_object_new_object(void);
360
361 /** Get the hashtable of a json_object of type json_type_object
362  * @param obj the json_object instance
363  * @returns a linkhash
364  */
365 JSON_EXPORT struct lh_table *json_object_get_object(const struct json_object *obj);
366
367 /** Get the size of an object in terms of the number of fields it has.
368  * @param obj the json_object whose length to return
369  */
370 JSON_EXPORT int json_object_object_length(const struct json_object *obj);
371
372 /** Get the sizeof (struct json_object).
373  * @returns a size_t with the sizeof (struct json_object)
374  */
375 JSON_C_CONST_FUNCTION(JSON_EXPORT size_t json_c_object_sizeof(void));
376
377 /** Add an object field to a json_object of type json_type_object
378  *
379  * The reference count of `val` will *not* be incremented, in effect
380  * transferring ownership that object to `obj`, and thus `val` will be
381  * freed when `obj` is.  (i.e. through `json_object_put(obj)`)
382  *
383  * If you want to retain a reference to the added object, independent
384  * of the lifetime of obj, you must increment the refcount with
385  * `json_object_get(val)` (and later release it with json_object_put()).
386  *
387  * Since ownership transfers to `obj`, you must make sure
388  * that you do in fact have ownership over `val`.  For instance,
389  * json_object_new_object() will give you ownership until you transfer it,
390  * whereas json_object_object_get() does not.
391  *
392  * Any previous object stored under `key` in `obj` will have its refcount
393  * decremented, and be freed normally if that drops to zero.
394  *
395  * @param obj the json_object instance
396  * @param key the object field name (a private copy will be duplicated)
397  * @param val a json_object or NULL member to associate with the given field
398  *
399  * @return On success, <code>0</code> is returned.
400  *      On error, a negative value is returned.
401  */
402 JSON_EXPORT int json_object_object_add(struct json_object *obj, const char *key,
403                                        struct json_object *val);
404
405 /** Add an object field to a json_object of type json_type_object
406  *
407  * The semantics are identical to json_object_object_add, except that an
408  * additional flag fields gives you more control over some detail aspects
409  * of processing. See the description of JSON_C_OBJECT_ADD_* flags for more
410  * details.
411  *
412  * @param obj the json_object instance
413  * @param key the object field name (a private copy will be duplicated)
414  * @param val a json_object or NULL member to associate with the given field
415  * @param opts process-modifying options. To specify multiple options, use
416  *             (OPT1|OPT2)
417  */
418 JSON_EXPORT int json_object_object_add_ex(struct json_object *obj, const char *const key,
419                                           struct json_object *const val, const unsigned opts);
420
421 /** Get the json_object associate with a given object field.
422  * Deprecated/discouraged: used json_object_object_get_ex instead.
423  *
424  * This returns NULL if the field is found but its value is null, or if
425  *  the field is not found, or if obj is not a json_type_object.  If you
426  *  need to distinguish between these cases, use json_object_object_get_ex().
427  *
428  * *No* reference counts will be changed.  There is no need to manually adjust
429  * reference counts through the json_object_put/json_object_get methods unless
430  * you need to have the child (value) reference maintain a different lifetime
431  * than the owning parent (obj). Ownership of the returned value is retained
432  * by obj (do not do json_object_put unless you have done a json_object_get).
433  * If you delete the value from obj (json_object_object_del) and wish to access
434  * the returned reference afterwards, make sure you have first gotten shared
435  * ownership through json_object_get (& don't forget to do a json_object_put
436  * or transfer ownership to prevent a memory leak).
437  *
438  * @param obj the json_object instance
439  * @param key the object field name
440  * @returns the json_object associated with the given field name
441  */
442 JSON_EXPORT struct json_object *json_object_object_get(const struct json_object *obj,
443                                                        const char *key);
444
445 /** Get the json_object associated with a given object field.
446  *
447  * This returns true if the key is found, false in all other cases (including
448  * if obj isn't a json_type_object).
449  *
450  * *No* reference counts will be changed.  There is no need to manually adjust
451  * reference counts through the json_object_put/json_object_get methods unless
452  * you need to have the child (value) reference maintain a different lifetime
453  * than the owning parent (obj).  Ownership of value is retained by obj.
454  *
455  * @param obj the json_object instance
456  * @param key the object field name
457  * @param value a pointer where to store a reference to the json_object
458  *              associated with the given field name.
459  *
460  *              It is safe to pass a NULL value.
461  * @returns whether or not the key exists
462  */
463 JSON_EXPORT json_bool json_object_object_get_ex(const struct json_object *obj, const char *key,
464                                                 struct json_object **value);
465
466 /** Delete the given json_object field
467  *
468  * The reference count will be decremented for the deleted object.  If there
469  * are no more owners of the value represented by this key, then the value is
470  * freed.  Otherwise, the reference to the value will remain in memory.
471  *
472  * @param obj the json_object instance
473  * @param key the object field name
474  */
475 JSON_EXPORT void json_object_object_del(struct json_object *obj, const char *key);
476
477 /**
478  * Iterate through all keys and values of an object.
479  *
480  * Adding keys to the object while iterating is NOT allowed.
481  *
482  * Deleting an existing key, or replacing an existing key with a
483  * new value IS allowed.
484  *
485  * @param obj the json_object instance
486  * @param key the local name for the char* key variable defined in the body
487  * @param val the local name for the json_object* object variable defined in
488  *            the body
489  */
490 #if defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
491
492 #define json_object_object_foreach(obj, key, val)                                \
493         char *key = NULL;                                                        \
494         struct json_object *val __attribute__((__unused__)) = NULL;              \
495         for (struct lh_entry *entry##key = lh_table_head(json_object_get_object(obj)),    \
496                              *entry_next##key = NULL;                            \
497              ({                                                                  \
498                      if (entry##key)                                             \
499                      {                                                           \
500                              key = (char *)lh_entry_k(entry##key);               \
501                              val = (struct json_object *)lh_entry_v(entry##key); \
502                              entry_next##key = lh_entry_next(entry##key);        \
503                      };                                                          \
504                      entry##key;                                                 \
505              });                                                                 \
506              entry##key = entry_next##key)
507
508 #else /* ANSI C or MSC */
509
510 #define json_object_object_foreach(obj, key, val)                              \
511         char *key = NULL;                                                      \
512         struct json_object *val = NULL;                                        \
513         struct lh_entry *entry##key;                                           \
514         struct lh_entry *entry_next##key = NULL;                               \
515         for (entry##key = lh_table_head(json_object_get_object(obj));          \
516              (entry##key ? (key = (char *)lh_entry_k(entry##key),              \
517                            val = (struct json_object *)lh_entry_v(entry##key), \
518                            entry_next##key = lh_entry_next(entry##key), entry##key)     \
519                          : 0);                                                 \
520              entry##key = entry_next##key)
521
522 #endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) */
523
524 /** Iterate through all keys and values of an object (ANSI C Safe)
525  * @param obj the json_object instance
526  * @param iter the object iterator, use type json_object_iter
527  */
528 #define json_object_object_foreachC(obj, iter)                                                  \
529         for (iter.entry = lh_table_head(json_object_get_object(obj));                                    \
530              (iter.entry ? (iter.key = (char *)lh_entry_k(iter.entry),                          \
531                            iter.val = (struct json_object *)lh_entry_v(iter.entry), iter.entry) \
532                          : 0);                                                                  \
533              iter.entry = lh_entry_next(iter.entry))
534
535 /* Array type methods */
536
537 /** Create a new empty json_object of type json_type_array
538  * with 32 slots allocated.
539  * If you know the array size you'll need ahead of time, use
540  * json_object_new_array_ext() instead.
541  * @see json_object_new_array_ext()
542  * @see json_object_array_shrink()
543  * @returns a json_object of type json_type_array
544  */
545 JSON_EXPORT struct json_object *json_object_new_array(void);
546
547 /** Create a new empty json_object of type json_type_array
548  * with the desired number of slots allocated.
549  * @see json_object_array_shrink()
550  * @param initial_size the number of slots to allocate
551  * @returns a json_object of type json_type_array
552  */
553 JSON_EXPORT struct json_object *json_object_new_array_ext(int initial_size);
554
555 /** Get the arraylist of a json_object of type json_type_array
556  * @param obj the json_object instance
557  * @returns an arraylist
558  */
559 JSON_EXPORT struct array_list *json_object_get_array(const struct json_object *obj);
560
561 /** Get the length of a json_object of type json_type_array
562  * @param obj the json_object instance
563  * @returns an int
564  */
565 JSON_EXPORT size_t json_object_array_length(const struct json_object *obj);
566
567 /** Sorts the elements of jso of type json_type_array
568 *
569 * Pointers to the json_object pointers will be passed as the two arguments
570 * to sort_fn
571 *
572 * @param jso the json_object instance
573 * @param sort_fn a sorting function
574 */
575 JSON_EXPORT void json_object_array_sort(struct json_object *jso,
576                                         int (*sort_fn)(const void *, const void *));
577
578 /** Binary search a sorted array for a specified key object.
579  *
580  * It depends on your compare function what's sufficient as a key.
581  * Usually you create some dummy object with the parameter compared in
582  * it, to identify the right item you're actually looking for.
583  *
584  * @see json_object_array_sort() for hints on the compare function.
585  *
586  * @param key a dummy json_object with the right key
587  * @param jso the array object we're searching
588  * @param sort_fn the sort/compare function
589  *
590  * @return the wanted json_object instance
591  */
592 JSON_EXPORT struct json_object *
593 json_object_array_bsearch(const struct json_object *key, const struct json_object *jso,
594                           int (*sort_fn)(const void *, const void *));
595
596 /** Add an element to the end of a json_object of type json_type_array
597  *
598  * The reference count will *not* be incremented. This is to make adding
599  * fields to objects in code more compact. If you want to retain a reference
600  * to an added object you must wrap the passed object with json_object_get
601  *
602  * @param obj the json_object instance
603  * @param val the json_object to be added
604  */
605 JSON_EXPORT int json_object_array_add(struct json_object *obj, struct json_object *val);
606
607 /** Insert or replace an element at a specified index in an array (a json_object of type json_type_array)
608  *
609  * The reference count will *not* be incremented. This is to make adding
610  * fields to objects in code more compact. If you want to retain a reference
611  * to an added object you must wrap the passed object with json_object_get
612  *
613  * The reference count of a replaced object will be decremented.
614  *
615  * The array size will be automatically be expanded to the size of the
616  * index if the index is larger than the current size.
617  *
618  * @param obj the json_object instance
619  * @param idx the index to insert the element at
620  * @param val the json_object to be added
621  */
622 JSON_EXPORT int json_object_array_put_idx(struct json_object *obj, size_t idx,
623                                           struct json_object *val);
624
625 /** Insert an element at a specified index in an array (a json_object of type json_type_array)
626  *
627  * The reference count will *not* be incremented. This is to make adding
628  * fields to objects in code more compact. If you want to retain a reference
629  * to an added object you must wrap the passed object with json_object_get
630  *
631  * The array size will be automatically be expanded to the size of the
632  * index if the index is larger than the current size.
633  * If the index is within the existing array limits, then the element will be
634  * inserted and all elements will be shifted. This is the only difference between
635  * this function and json_object_array_put_idx().
636  *
637  * @param obj the json_object instance
638  * @param idx the index to insert the element at
639  * @param val the json_object to be added
640  */
641 JSON_EXPORT int json_object_array_insert_idx(struct json_object *obj, size_t idx,
642                                              struct json_object *val);
643
644 /** Get the element at specified index of array `obj` (which must be a json_object of type json_type_array)
645  *
646  * *No* reference counts will be changed, and ownership of the returned
647  * object remains with `obj`.  See json_object_object_get() for additional
648  * implications of this behavior.
649  *
650  * Calling this with anything other than a json_type_array will trigger
651  * an assert.
652  *
653  * @param obj the json_object instance
654  * @param idx the index to get the element at
655  * @returns the json_object at the specified index (or NULL)
656  */
657 JSON_EXPORT struct json_object *json_object_array_get_idx(const struct json_object *obj,
658                                                           size_t idx);
659
660 /** Delete an elements from a specified index in an array (a json_object of type json_type_array)
661  *
662  * The reference count will be decremented for each of the deleted objects.  If there
663  * are no more owners of an element that is being deleted, then the value is
664  * freed.  Otherwise, the reference to the value will remain in memory.
665  *
666  * @param obj the json_object instance
667  * @param idx the index to start deleting elements at
668  * @param count the number of elements to delete
669  * @returns 0 if the elements were successfully deleted
670  */
671 JSON_EXPORT int json_object_array_del_idx(struct json_object *obj, size_t idx, size_t count);
672
673 /**
674  * Shrink the internal memory allocation of the array to just
675  * enough to fit the number of elements in it, plus empty_slots.
676  *
677  * @param jso the json_object instance, must be json_type_array
678  * @param empty_slots the number of empty slots to leave allocated
679  */
680 JSON_EXPORT int json_object_array_shrink(struct json_object *jso, int empty_slots);
681
682 /* json_bool type methods */
683
684 /** Create a new empty json_object of type json_type_boolean
685  * @param b a json_bool 1 or 0
686  * @returns a json_object of type json_type_boolean
687  */
688 JSON_EXPORT struct json_object *json_object_new_boolean(json_bool b);
689
690 /** Get the json_bool value of a json_object
691  *
692  * The type is coerced to a json_bool if the passed object is not a json_bool.
693  * integer and double objects will return 0 if there value is zero
694  * or 1 otherwise. If the passed object is a string it will return
695  * 1 if it has a non zero length. 
696  * If any other object type is passed 0 will be returned, even non-empty
697  *  json_type_array and json_type_object objects.
698  *
699  * @param obj the json_object instance
700  * @returns a json_bool
701  */
702 JSON_EXPORT json_bool json_object_get_boolean(const struct json_object *obj);
703
704 /** Set the json_bool value of a json_object
705  *
706  * The type of obj is checked to be a json_type_boolean and 0 is returned
707  * if it is not without any further actions. If type of obj is json_type_boolean
708  * the object value is changed to new_value
709  *
710  * @param obj the json_object instance
711  * @param new_value the value to be set
712  * @returns 1 if value is set correctly, 0 otherwise
713  */
714 JSON_EXPORT int json_object_set_boolean(struct json_object *obj, json_bool new_value);
715
716 /* int type methods */
717
718 /** Create a new empty json_object of type json_type_int
719  * Note that values are stored as 64-bit values internally.
720  * To ensure the full range is maintained, use json_object_new_int64 instead.
721  * @param i the integer
722  * @returns a json_object of type json_type_int
723  */
724 JSON_EXPORT struct json_object *json_object_new_int(int32_t i);
725
726 /** Create a new empty json_object of type json_type_int
727  * @param i the integer
728  * @returns a json_object of type json_type_int
729  */
730 JSON_EXPORT struct json_object *json_object_new_int64(int64_t i);
731
732 /** Create a new empty json_object of type json_type_uint
733  * @param i the integer
734  * @returns a json_object of type json_type_uint
735  */
736 JSON_EXPORT struct json_object *json_object_new_uint64(uint64_t i);
737
738 /** Get the int value of a json_object
739  *
740  * The type is coerced to a int if the passed object is not a int.
741  * double objects will return their integer conversion. Strings will be
742  * parsed as an integer. If no conversion exists then 0 is returned
743  * and errno is set to EINVAL. null is equivalent to 0 (no error values set)
744  *
745  * Note that integers are stored internally as 64-bit values.
746  * If the value of too big or too small to fit into 32-bit, INT32_MAX or
747  * INT32_MIN are returned, respectively.
748  *
749  * @param obj the json_object instance
750  * @returns an int
751  */
752 JSON_EXPORT int32_t json_object_get_int(const struct json_object *obj);
753
754 /** Set the int value of a json_object
755  *
756  * The type of obj is checked to be a json_type_int and 0 is returned
757  * if it is not without any further actions. If type of obj is json_type_int
758  * the object value is changed to new_value
759  *
760  * @param obj the json_object instance
761  * @param new_value the value to be set
762  * @returns 1 if value is set correctly, 0 otherwise
763  */
764 JSON_EXPORT int json_object_set_int(struct json_object *obj, int new_value);
765
766 /** Increment a json_type_int object by the given amount, which may be negative.
767  *
768  * If the type of obj is not json_type_int then 0 is returned with no further
769  * action taken.
770  * If the addition would result in a overflow, the object value
771  * is set to INT64_MAX.
772  * If the addition would result in a underflow, the object value
773  * is set to INT64_MIN.
774  * Neither overflow nor underflow affect the return value.
775  *
776  * @param obj the json_object instance
777  * @param val the value to add
778  * @returns 1 if the increment succeeded, 0 otherwise
779  */
780 JSON_EXPORT int json_object_int_inc(struct json_object *obj, int64_t val);
781
782 /** Get the int value of a json_object
783  *
784  * The type is coerced to a int64 if the passed object is not a int64.
785  * double objects will return their int64 conversion. Strings will be
786  * parsed as an int64. If no conversion exists then 0 is returned.
787  *
788  * NOTE: Set errno to 0 directly before a call to this function to determine
789  * whether or not conversion was successful (it does not clear the value for
790  * you).
791  *
792  * @param obj the json_object instance
793  * @returns an int64
794  */
795 JSON_EXPORT int64_t json_object_get_int64(const struct json_object *obj);
796
797 /** Get the uint value of a json_object
798  *
799  * The type is coerced to a uint64 if the passed object is not a uint64.
800  * double objects will return their uint64 conversion. Strings will be
801  * parsed as an uint64. If no conversion exists then 0 is returned.
802  *
803  * NOTE: Set errno to 0 directly before a call to this function to determine
804  * whether or not conversion was successful (it does not clear the value for
805  * you).
806  *
807  * @param obj the json_object instance
808  * @returns an uint64
809  */
810 JSON_EXPORT uint64_t json_object_get_uint64(const struct json_object *obj);
811
812 /** Set the int64_t value of a json_object
813  *
814  * The type of obj is checked to be a json_type_int and 0 is returned
815  * if it is not without any further actions. If type of obj is json_type_int
816  * the object value is changed to new_value
817  *
818  * @param obj the json_object instance
819  * @param new_value the value to be set
820  * @returns 1 if value is set correctly, 0 otherwise
821  */
822 JSON_EXPORT int json_object_set_int64(struct json_object *obj, int64_t new_value);
823
824 /** Set the uint64_t value of a json_object
825  *
826  * The type of obj is checked to be a json_type_uint and 0 is returned
827  * if it is not without any further actions. If type of obj is json_type_uint
828  * the object value is changed to new_value
829  *
830  * @param obj the json_object instance
831  * @param new_value the value to be set
832  * @returns 1 if value is set correctly, 0 otherwise
833  */
834 JSON_EXPORT int json_object_set_uint64(struct json_object *obj, uint64_t new_value);
835
836 /* double type methods */
837
838 /** Create a new empty json_object of type json_type_double
839  *
840  * @see json_object_double_to_json_string() for how to set a custom format string.
841  *
842  * @param d the double
843  * @returns a json_object of type json_type_double
844  */
845 JSON_EXPORT struct json_object *json_object_new_double(double d);
846
847 /**
848  * Create a new json_object of type json_type_double, using
849  * the exact serialized representation of the value.
850  *
851  * This allows for numbers that would otherwise get displayed
852  * inefficiently (e.g. 12.3 => "12.300000000000001") to be
853  * serialized with the more convenient form.
854  *
855  * Notes:
856  *
857  * This is used by json_tokener_parse_ex() to allow for
858  * an exact re-serialization of a parsed object.
859  *
860  * The userdata field is used to store the string representation, so it
861  * can't be used for other data if this function is used.
862  *
863  * A roughly equivalent sequence of calls, with the difference being that
864  *  the serialization function won't be reset by json_object_set_double(), is:
865  * @code
866  *   jso = json_object_new_double(d);
867  *   json_object_set_serializer(jso, json_object_userdata_to_json_string,
868  *       strdup(ds), json_object_free_userdata);
869  * @endcode
870  *
871  * @param d the numeric value of the double.
872  * @param ds the string representation of the double.  This will be copied.
873  */
874 JSON_EXPORT struct json_object *json_object_new_double_s(double d, const char *ds);
875
876 /**
877  * Set a global or thread-local json-c option, depending on whether
878  *  JSON_C_OPTION_GLOBAL or JSON_C_OPTION_THREAD is passed.
879  * Thread-local options default to undefined, and inherit from the global
880  *  value, even if the global value is changed after the thread is created.
881  * Attempting to set thread-local options when threading is not compiled in
882  *  will result in an error.  Be sure to check the return value.
883  *
884  * double_format is a "%g" printf format, such as "%.20g"
885  *
886  * @return -1 on errors, 0 on success.
887  */
888 JSON_EXPORT int json_c_set_serialization_double_format(const char *double_format,
889                                                        int global_or_thread);
890
891 /** Serialize a json_object of type json_type_double to a string.
892  *
893  * This function isn't meant to be called directly. Instead, you can set a
894  * custom format string for the serialization of this double using the
895  * following call (where "%.17g" actually is the default):
896  *
897  * @code
898  *   jso = json_object_new_double(d);
899  *   json_object_set_serializer(jso, json_object_double_to_json_string,
900  *       "%.17g", NULL);
901  * @endcode
902  *
903  * @see printf(3) man page for format strings
904  *
905  * @param jso The json_type_double object that is serialized.
906  * @param pb The destination buffer.
907  * @param level Ignored.
908  * @param flags Ignored.
909  */
910 JSON_EXPORT int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb,
911                                                   int level, int flags);
912
913 /** Get the double floating point value of a json_object
914  *
915  * The type is coerced to a double if the passed object is not a double.
916  * integer objects will return their double conversion. Strings will be
917  * parsed as a double. If no conversion exists then 0.0 is returned and
918  * errno is set to EINVAL. null is equivalent to 0 (no error values set)
919  *
920  * If the value is too big to fit in a double, then the value is set to
921  * the closest infinity with errno set to ERANGE. If strings cannot be
922  * converted to their double value, then EINVAL is set & NaN is returned.
923  *
924  * Arrays of length 0 are interpreted as 0 (with no error flags set).
925  * Arrays of length 1 are effectively cast to the equivalent object and
926  * converted using the above rules.  All other arrays set the error to
927  * EINVAL & return NaN.
928  *
929  * NOTE: Set errno to 0 directly before a call to this function to
930  * determine whether or not conversion was successful (it does not clear
931  * the value for you).
932  *
933  * @param obj the json_object instance
934  * @returns a double floating point number
935  */
936 JSON_EXPORT double json_object_get_double(const struct json_object *obj);
937
938 /** Set the double value of a json_object
939  *
940  * The type of obj is checked to be a json_type_double and 0 is returned
941  * if it is not without any further actions. If type of obj is json_type_double
942  * the object value is changed to new_value
943  *
944  * If the object was created with json_object_new_double_s(), the serialization
945  * function is reset to the default and the cached serialized value is cleared.
946  *
947  * @param obj the json_object instance
948  * @param new_value the value to be set
949  * @returns 1 if value is set correctly, 0 otherwise
950  */
951 JSON_EXPORT int json_object_set_double(struct json_object *obj, double new_value);
952
953 /* string type methods */
954
955 /** Create a new empty json_object of type json_type_string
956  *
957  * A copy of the string is made and the memory is managed by the json_object
958  *
959  * @param s the string
960  * @returns a json_object of type json_type_string
961  * @see json_object_new_string_len()
962  */
963 JSON_EXPORT struct json_object *json_object_new_string(const char *s);
964
965 /** Create a new empty json_object of type json_type_string and allocate
966  * len characters for the new string.
967  *
968  * A copy of the string is made and the memory is managed by the json_object
969  *
970  * @param s the string
971  * @param len max length of the new string
972  * @returns a json_object of type json_type_string
973  * @see json_object_new_string()
974  */
975 JSON_EXPORT struct json_object *json_object_new_string_len(const char *s, const int len);
976
977 /** Get the string value of a json_object
978  *
979  * If the passed object is of type json_type_null (i.e. obj == NULL),
980  * NULL is returned.
981  *
982  * If the passed object of type json_type_string, the string contents
983  * are returned.
984  *
985  * Otherwise the JSON representation of the object is returned.
986  *
987  * The returned string memory is managed by the json_object and will
988  * be freed when the reference count of the json_object drops to zero.
989  *
990  * @param obj the json_object instance
991  * @returns a string or NULL
992  */
993 JSON_EXPORT const char *json_object_get_string(struct json_object *obj);
994
995 /** Get the string length of a json_object
996  *
997  * If the passed object is not of type json_type_string then zero
998  * will be returned.
999  *
1000  * @param obj the json_object instance
1001  * @returns int
1002  */
1003 JSON_EXPORT int json_object_get_string_len(const struct json_object *obj);
1004
1005 /** Set the string value of a json_object with zero terminated strings
1006  * equivalent to json_object_set_string_len (obj, new_value, strlen(new_value))
1007  * @returns 1 if value is set correctly, 0 otherwise
1008  */
1009 JSON_EXPORT int json_object_set_string(json_object *obj, const char *new_value);
1010
1011 /** Set the string value of a json_object str
1012  *
1013  * The type of obj is checked to be a json_type_string and 0 is returned
1014  * if it is not without any further actions. If type of obj is json_type_string
1015  * the object value is changed to new_value
1016  *
1017  * @param obj the json_object instance
1018  * @param new_value the value to be set; Since string length is given in len this need not be zero terminated
1019  * @param len the length of new_value
1020  * @returns 1 if value is set correctly, 0 otherwise
1021  */
1022 JSON_EXPORT int json_object_set_string_len(json_object *obj, const char *new_value, int len);
1023
1024 /** This method exists only to provide a complementary function
1025  * along the lines of the other json_object_new_* functions.
1026  * It always returns NULL, and it is entirely acceptable to simply use NULL directly.
1027  */
1028 JSON_EXPORT struct json_object *json_object_new_null(void);
1029
1030 /** Check if two json_object's are equal
1031  *
1032  * If the passed objects are equal 1 will be returned.
1033  * Equality is defined as follows:
1034  * - json_objects of different types are never equal
1035  * - json_objects of the same primitive type are equal if the
1036  *   c-representation of their value is equal
1037  * - json-arrays are considered equal if all values at the same
1038  *   indices are equal (same order)
1039  * - Complex json_objects are considered equal if all
1040  *   contained objects referenced by their key are equal,
1041  *   regardless their order.
1042  *
1043  * @param obj1 the first json_object instance
1044  * @param obj2 the second json_object instance
1045  * @returns whether both objects are equal or not
1046  */
1047 JSON_EXPORT int json_object_equal(struct json_object *obj1, struct json_object *obj2);
1048
1049 /**
1050  * Perform a shallow copy of src into *dst as part of an overall json_object_deep_copy().
1051  *
1052  * If src is part of a containing object or array, parent will be non-NULL,
1053  * and key or index will be provided.
1054  * When shallow_copy is called *dst will be NULL, and must be non-NULL when it returns.
1055  * src will never be NULL.
1056  *
1057  * If shallow_copy sets the serializer on an object, return 2 to indicate to
1058  *  json_object_deep_copy that it should not attempt to use the standard userdata
1059  *  copy function.
1060  *
1061  * @return On success 1 or 2, -1 on errors
1062  */
1063 typedef int(json_c_shallow_copy_fn)(json_object *src, json_object *parent, const char *key,
1064                                     size_t index, json_object **dst);
1065
1066 /**
1067  * The default shallow copy implementation for use with json_object_deep_copy().
1068  * This simply calls the appropriate json_object_new_<type>() function and
1069  * copies over the serializer function (_to_json_string internal field of
1070  * the json_object structure) but not any _userdata or _user_delete values.
1071  *
1072  * If you're writing a custom shallow_copy function, perhaps because you're using
1073  * your own custom serializer, you can call this first to create the new object
1074  * before customizing it with json_object_set_serializer().
1075  *
1076  * @return 1 on success, -1 on errors, but never 2.
1077  */
1078 JSON_EXPORT json_c_shallow_copy_fn json_c_shallow_copy_default;
1079
1080 /**
1081  * Copy the contents of the JSON object.
1082  * The destination object must be initialized to NULL,
1083  * to make sure this function won't overwrite an existing JSON object.
1084  *
1085  * This does roughly the same thing as
1086  * `json_tokener_parse(json_object_get_string(src))`.
1087  *
1088  * @param src source JSON object whose contents will be copied
1089  * @param dst pointer to the destination object where the contents of `src`;
1090  *            make sure this pointer is initialized to NULL
1091  * @param shallow_copy an optional function to copy individual objects, needed
1092  *                     when custom serializers are in use.  See also
1093  *                     json_object set_serializer.
1094  *
1095  * @returns 0 if the copy went well, -1 if an error occurred during copy
1096  *          or if the destination pointer is non-NULL
1097  */
1098
1099 JSON_EXPORT int json_object_deep_copy(struct json_object *src, struct json_object **dst,
1100                                       json_c_shallow_copy_fn *shallow_copy);
1101 #ifdef __cplusplus
1102 }
1103 #endif
1104
1105 #endif