frozen.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*
  2. * Copyright (c) 2004-2013 Sergey Lyubka <[email protected]>
  3. * Copyright (c) 2018 Cesanta Software Limited
  4. * All rights reserved
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the ""License"");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef CS_FROZEN_FROZEN_H_
  19. #define CS_FROZEN_FROZEN_H_
  20. #ifdef __cplusplus
  21. extern "C" {
  22. #endif /* __cplusplus */
  23. #include <stdarg.h>
  24. #include <stddef.h>
  25. #include <stdio.h>
  26. typedef void *(*Alloc)(size_t);
  27. typedef void (*Free)(void*);
  28. typedef struct {
  29. Alloc alloc;
  30. Free free;
  31. } Allocator;
  32. extern Allocator allocator;
  33. #if defined(_WIN32) && _MSC_VER < 1700
  34. typedef int bool;
  35. enum { false = 0, true = 1 };
  36. #else
  37. #include <stdbool.h>
  38. #endif
  39. /* JSON token type */
  40. enum json_token_type {
  41. JSON_TYPE_INVALID = 0, /* memsetting to 0 should create INVALID value */
  42. JSON_TYPE_STRING,
  43. JSON_TYPE_NUMBER,
  44. JSON_TYPE_TRUE,
  45. JSON_TYPE_FALSE,
  46. JSON_TYPE_NULL,
  47. JSON_TYPE_OBJECT_START,
  48. JSON_TYPE_OBJECT_END,
  49. JSON_TYPE_ARRAY_START,
  50. JSON_TYPE_ARRAY_END,
  51. JSON_TYPES_CNT
  52. };
  53. /*
  54. * Structure containing token type and value. Used in `json_walk()` and
  55. * `json_scanf()` with the format specifier `%T`.
  56. */
  57. struct json_token {
  58. const char *ptr; /* Points to the beginning of the value */
  59. int len; /* Value length */
  60. enum json_token_type type; /* Type of the token, possible values are above */
  61. };
  62. #define JSON_INVALID_TOKEN \
  63. { 0, 0, JSON_TYPE_INVALID }
  64. /* Error codes */
  65. #define JSON_STRING_INVALID -1
  66. #define JSON_STRING_INCOMPLETE -2
  67. /*
  68. * Callback-based SAX-like API.
  69. *
  70. * Property name and length is given only if it's available: i.e. if current
  71. * event is an object's property. In other cases, `name` is `NULL`. For
  72. * example, name is never given:
  73. * - For the first value in the JSON string;
  74. * - For events JSON_TYPE_OBJECT_END and JSON_TYPE_ARRAY_END
  75. *
  76. * E.g. for the input `{ "foo": 123, "bar": [ 1, 2, { "baz": true } ] }`,
  77. * the sequence of callback invocations will be as follows:
  78. *
  79. * - type: JSON_TYPE_OBJECT_START, name: NULL, path: "", value: NULL
  80. * - type: JSON_TYPE_NUMBER, name: "foo", path: ".foo", value: "123"
  81. * - type: JSON_TYPE_ARRAY_START, name: "bar", path: ".bar", value: NULL
  82. * - type: JSON_TYPE_NUMBER, name: "0", path: ".bar[0]", value: "1"
  83. * - type: JSON_TYPE_NUMBER, name: "1", path: ".bar[1]", value: "2"
  84. * - type: JSON_TYPE_OBJECT_START, name: "2", path: ".bar[2]", value: NULL
  85. * - type: JSON_TYPE_TRUE, name: "baz", path: ".bar[2].baz", value: "true"
  86. * - type: JSON_TYPE_OBJECT_END, name: NULL, path: ".bar[2]", value: "{ \"baz\":
  87. *true }"
  88. * - type: JSON_TYPE_ARRAY_END, name: NULL, path: ".bar", value: "[ 1, 2, {
  89. *\"baz\": true } ]"
  90. * - type: JSON_TYPE_OBJECT_END, name: NULL, path: "", value: "{ \"foo\": 123,
  91. *\"bar\": [ 1, 2, { \"baz\": true } ] }"
  92. */
  93. typedef void (*json_walk_callback_t)(void *callback_data, const char *name,
  94. size_t name_len, const char *path,
  95. const struct json_token *token);
  96. /*
  97. * Parse `json_string`, invoking `callback` in a way similar to SAX parsers;
  98. * see `json_walk_callback_t`.
  99. * Return number of processed bytes, or a negative error code.
  100. */
  101. int json_walk(const char *json_string, int json_string_length,
  102. json_walk_callback_t callback, void *callback_data);
  103. /*
  104. * JSON generation API.
  105. * struct json_out abstracts output, allowing alternative printing plugins.
  106. */
  107. struct json_out {
  108. int (*printer)(struct json_out *, const char *str, size_t len);
  109. union {
  110. struct {
  111. char *buf;
  112. size_t size;
  113. size_t len;
  114. } buf;
  115. void *data;
  116. FILE *fp;
  117. } u;
  118. };
  119. extern int json_printer_buf(struct json_out *, const char *, size_t);
  120. extern int json_printer_file(struct json_out *, const char *, size_t);
  121. #define JSON_OUT_BUF(buf, len) \
  122. { \
  123. json_printer_buf, { \
  124. { buf, len, 0 } \
  125. } \
  126. }
  127. #define JSON_OUT_FILE(fp) \
  128. { \
  129. json_printer_file, { \
  130. { (char *) fp, 0, 0 } \
  131. } \
  132. }
  133. typedef int (*json_printf_callback_t)(struct json_out *, va_list *ap);
  134. /*
  135. * Generate formatted output into a given sting buffer.
  136. * This is a superset of printf() function, with extra format specifiers:
  137. * - `%B` print json boolean, `true` or `false`. Accepts an `int`.
  138. * - `%Q` print quoted escaped string or `null`. Accepts a `const char *`.
  139. * - `%.*Q` same as `%Q`, but with length. Accepts `int`, `const char *`
  140. * - `%V` print quoted base64-encoded string. Accepts a `const char *`, `int`.
  141. * - `%H` print quoted hex-encoded string. Accepts a `int`, `const char *`.
  142. * - `%M` invokes a json_printf_callback_t function. That callback function
  143. * can consume more parameters.
  144. *
  145. * Return number of bytes printed. If the return value is bigger than the
  146. * supplied buffer, that is an indicator of overflow. In the overflow case,
  147. * overflown bytes are not printed.
  148. */
  149. int json_printf(struct json_out *, const char *fmt, ...);
  150. int json_vprintf(struct json_out *, const char *fmt, va_list ap);
  151. /*
  152. * Same as json_printf, but prints to a file.
  153. * File is created if does not exist. File is truncated if already exists.
  154. */
  155. int json_fprintf(const char *file_name, const char *fmt, ...);
  156. int json_vfprintf(const char *file_name, const char *fmt, va_list ap);
  157. /*
  158. * Print JSON into an allocated 0-terminated string.
  159. * Return allocated string, or NULL on error.
  160. * Example:
  161. *
  162. * ```c
  163. * char *str = json_asprintf("{a:%H}", 3, "abc");
  164. * printf("%s\n", str); // Prints "616263"
  165. * free(str);
  166. * ```
  167. */
  168. char *json_asprintf(const char *fmt, ...);
  169. char *json_vasprintf(const char *fmt, va_list ap);
  170. /*
  171. * Helper %M callback that prints contiguous C arrays.
  172. * Consumes void *array_ptr, size_t array_size, size_t elem_size, char *fmt
  173. * Return number of bytes printed.
  174. */
  175. int json_printf_array(struct json_out *, va_list *ap);
  176. /*
  177. * Scan JSON string `str`, performing scanf-like conversions according to `fmt`.
  178. * This is a `scanf()` - like function, with following differences:
  179. *
  180. * 1. Object keys in the format string may be not quoted, e.g. "{key: %d}"
  181. * 2. Order of keys in an object is irrelevant.
  182. * 3. Several extra format specifiers are supported:
  183. * - %B: consumes `int *` (or `char *`, if `sizeof(bool) == sizeof(char)`),
  184. * expects boolean `true` or `false`.
  185. * - %Q: consumes `char **`, expects quoted, JSON-encoded string. Scanned
  186. * string is malloc-ed, caller must free() the string.
  187. * - %V: consumes `char **`, `int *`. Expects base64-encoded string.
  188. * Result string is base64-decoded, malloced and NUL-terminated.
  189. * The length of result string is stored in `int *` placeholder.
  190. * Caller must free() the result.
  191. * - %H: consumes `int *`, `char **`.
  192. * Expects a hex-encoded string, e.g. "fa014f".
  193. * Result string is hex-decoded, malloced and NUL-terminated.
  194. * The length of the result string is stored in `int *` placeholder.
  195. * Caller must free() the result.
  196. * - %M: consumes custom scanning function pointer and
  197. * `void *user_data` parameter - see json_scanner_t definition.
  198. * - %T: consumes `struct json_token *`, fills it out with matched token.
  199. *
  200. * Return number of elements successfully scanned & converted.
  201. * Negative number means scan error.
  202. */
  203. int json_scanf(const char *str, int str_len, const char *fmt, ...);
  204. int json_vscanf(const char *str, int str_len, const char *fmt, va_list ap);
  205. /* json_scanf's %M handler */
  206. typedef void (*json_scanner_t)(const char *str, int len, void *user_data);
  207. /*
  208. * Helper function to scan array item with given path and index.
  209. * Fills `token` with the matched JSON token.
  210. * Return -1 if no array element found, otherwise non-negative token length.
  211. */
  212. int json_scanf_array_elem(const char *s, int len, const char *path, int index,
  213. struct json_token *token);
  214. /*
  215. * Unescape JSON-encoded string src,slen into dst, dlen.
  216. * src and dst may overlap.
  217. * If destination buffer is too small (or zero-length), result string is not
  218. * written but the length is counted nevertheless (similar to snprintf).
  219. * Return the length of unescaped string in bytes.
  220. */
  221. int json_unescape(const char *src, int slen, char *dst, int dlen);
  222. /*
  223. * Escape a string `str`, `str_len` into the printer `out`.
  224. * Return the number of bytes printed.
  225. */
  226. int json_escape(struct json_out *out, const char *str, size_t str_len);
  227. int json_get_utf8_char_len(unsigned char ch);
  228. /*
  229. * Read the whole file in memory.
  230. * Return malloc-ed file content, or NULL on error. The caller must free().
  231. */
  232. char *json_fread(const char *file_name);
  233. /*
  234. * Update given JSON string `s,len` by changing the value at given `json_path`.
  235. * The result is saved to `out`. If `json_fmt` == NULL, that deletes the key.
  236. * If path is not present, missing keys are added. Array path without an
  237. * index pushes a value to the end of an array.
  238. * Return 1 if the string was changed, 0 otherwise.
  239. *
  240. * Example: s is a JSON string { "a": 1, "b": [ 2 ] }
  241. * json_setf(s, len, out, ".a", "7"); // { "a": 7, "b": [ 2 ] }
  242. * json_setf(s, len, out, ".b", "7"); // { "a": 1, "b": 7 }
  243. * json_setf(s, len, out, ".b[]", "7"); // { "a": 1, "b": [ 2,7 ] }
  244. * json_setf(s, len, out, ".b", NULL); // { "a": 1 }
  245. */
  246. int json_setf(const char *s, int len, struct json_out *out,
  247. const char *json_path, const char *json_fmt, ...);
  248. int json_vsetf(const char *s, int len, struct json_out *out,
  249. const char *json_path, const char *json_fmt, va_list ap);
  250. /*
  251. * Pretty-print JSON string `s,len` into `out`.
  252. * Return number of processed bytes in `s`.
  253. */
  254. int json_prettify(const char *s, int len, struct json_out *out);
  255. /*
  256. * Prettify JSON file `file_name`.
  257. * Return number of processed bytes, or negative number of error.
  258. * On error, file content is not modified.
  259. */
  260. int json_prettify_file(const char *file_name);
  261. /*
  262. * Iterate over an object at given JSON `path`.
  263. * On each iteration, fill the `key` and `val` tokens. It is OK to pass NULL
  264. * for `key`, or `val`, in which case they won't be populated.
  265. * Return an opaque value suitable for the next iteration, or NULL when done.
  266. *
  267. * Example:
  268. *
  269. * ```c
  270. * void *h = NULL;
  271. * struct json_token key, val;
  272. * while ((h = json_next_key(s, len, h, ".foo", &key, &val)) != NULL) {
  273. * printf("[%.*s] -> [%.*s]\n", key.len, key.ptr, val.len, val.ptr);
  274. * }
  275. * ```
  276. */
  277. void *json_next_key(const char *s, int len, void *handle, const char *path,
  278. struct json_token *key, struct json_token *val);
  279. /*
  280. * Iterate over an array at given JSON `path`.
  281. * Similar to `json_next_key`, but fills array index `idx` instead of `key`.
  282. */
  283. void *json_next_elem(const char *s, int len, void *handle, const char *path,
  284. int *idx, struct json_token *val);
  285. #ifndef JSON_MAX_PATH_LEN
  286. #define JSON_MAX_PATH_LEN 256
  287. #endif
  288. #ifndef JSON_MINIMAL
  289. #define JSON_MINIMAL 0
  290. #endif
  291. #ifndef JSON_ENABLE_BASE64
  292. #define JSON_ENABLE_BASE64 !JSON_MINIMAL
  293. #endif
  294. #ifndef JSON_ENABLE_HEX
  295. #define JSON_ENABLE_HEX !JSON_MINIMAL
  296. #endif
  297. #ifdef __cplusplus
  298. }
  299. #endif /* __cplusplus */
  300. #endif /* CS_FROZEN_FROZEN_H_ */