Safe C

safe-c-std/json.h

Raw file ยท Directory on GitHub

1/* JSON, kept in one array of values and one text. Values point to each other
2   by index, so there is one thing to free; index 0 is the document.
3     struct json j = {0};
4     json_result r = json_parse(&j, text);
5     if (!r.ok) ... r.err.at ...              where it stopped
6     size_t name = json_get(&j, 0, STR("name"));     0 if it is not there
7     struct str s = json_text(&j, name);
8     json_free(&j); */
9#ifndef SAFEC_JSON_H
10#define SAFEC_JSON_H
11#include "text.h"
12#if defined(__clang__)
13#pragma clang assume_nonnull begin
14#endif
15
16enum json_kind { JSON_NULL, JSON_BOOL, JSON_NUMBER, JSON_TEXT, JSON_ARRAY, JSON_OBJECT };
17struct json_span { size_t at, len; };
18struct json_value {
19  struct json_span key; /* in an object */
20  size_t next;          /* the next one in the array or object, 0 at the end */
21  enum json_kind kind;
22  union _Tagged_by(kind) {
23    int none _When(JSON_NULL);
24    int truth _When(JSON_BOOL);
25    double number _When(JSON_NUMBER);
26    struct json_span text _When(JSON_TEXT);
27    size_t first _When(JSON_ARRAY, JSON_OBJECT); /* 0 if it is empty */
28  };
29};
30#if defined(__clang__)
31#pragma clang assume_nonnull end /* vec.h has its own */
32#endif
33#define VEC_NAME json_values
34#define VEC_TYPE struct json_value
35#include "vec.h"
36#if defined(__clang__)
37#pragma clang assume_nonnull begin
38#endif
39struct json {
40  struct json_values values;
41  struct text text;
42};
43
44static inline void json_free(struct json *_Empties j) {
45  json_values_free(&j->values);
46  text_free(&j->text);
47}
48static inline struct json_value json_at(const struct json *j, size_t i) {
49  struct json_value v = {.kind = JSON_NULL, .none = 0};
50  json_values_get(&j->values, i, &v);
51  return v;
52}
53static inline struct str json_key(const struct json *j, size_t i) {
54  struct json_value v = json_at(j, i);
55  return str_part(text_str(&j->text), v.key.at, v.key.len);
56}
57/* A text's bytes, or nothing if it is not one. */
58static inline struct str json_text(const struct json *j, size_t i) {
59  struct json_value v = json_at(j, i);
60  struct json_span s = {0, 0};
61  if (v.kind == JSON_TEXT)
62    s = v.text;
63  return str_part(text_str(&j->text), s.at, s.len);
64}
65static inline double json_number(const struct json *j, size_t i) {
66  struct json_value v = json_at(j, i);
67  return v.kind == JSON_NUMBER ? v.number : 0;
68}
69/* The first value in an array or object, then json_at(j, i).next. */
70static inline size_t json_first(const struct json *j, size_t i) {
71  struct json_value v = json_at(j, i);
72  if (v.kind == JSON_ARRAY || v.kind == JSON_OBJECT)
73    return v.first;
74  return 0;
75}
76static inline size_t json_get(const struct json *j, size_t i, struct str key) {
77  if (json_at(j, i).kind != JSON_OBJECT)
78    return 0;
79  for (size_t v = json_first(j, i); v; v = json_at(j, v).next)
80    if (str_eq(json_key(j, v), key))
81      return v;
82  return 0;
83}
84
85/* Parsing: s is the input, *at where we are. Each returns 0 if it is not JSON. */
86static inline int json_peek_(struct str s, const size_t *at) {
87  return *at < s.len ? (unsigned char)s.p[*at] : -1;
88}
89static inline void json_space_(struct str s, size_t *at) {
90  int c = json_peek_(s, at);
91  while (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
92    (*at)++;
93    c = json_peek_(s, at);
94  }
95}
96static inline int json_word_(struct str s, size_t *at, struct str word) {
97  if (!str_eq(str_part(s, *at, word.len), word))
98    return 0;
99  *at += word.len;
100  return 1;
101}
102static inline int json_digits_(struct str s, size_t *at) {
103  size_t from = *at;
104  while (json_peek_(s, at) >= '0' && json_peek_(s, at) <= '9')
105    (*at)++;
106  return *at > from;
107}
108static inline int json_number_(struct str s, size_t *at, double *out) {
109  size_t from = *at;
110  if (json_peek_(s, at) == '-')
111    (*at)++;
112  if (json_peek_(s, at) == '0')
113    (*at)++;
114  else if (!json_digits_(s, at))
115    return 0;
116  if (json_peek_(s, at) == '.') {
117    (*at)++;
118    if (!json_digits_(s, at))
119      return 0;
120  }
121  if (json_peek_(s, at) == 'e' || json_peek_(s, at) == 'E') {
122    (*at)++;
123    if (json_peek_(s, at) == '+' || json_peek_(s, at) == '-')
124      (*at)++;
125    if (!json_digits_(s, at))
126      return 0;
127  }
128  struct text t = {0};
129  struct str n = str_part(s, from, *at - from);
130  int ok = text_add(&t, n.p, n.len) && text_add(&t, "\0", 1) && t.p;
131  if (ok && t.p)
132    *out = strtod(t.p, NULL);
133  text_free(&t);
134  return ok;
135}
136static inline int json_hex_(struct str s, size_t *at, unsigned long *out) {
137  unsigned long v = 0;
138  for (int i = 0; i < 4; i++) {
139    int c = json_peek_(s, at);
140    (*at)++;
141    if (c >= '0' && c <= '9')
142      v = v * 16 + (unsigned long)(c - '0');
143    else if (c >= 'a' && c <= 'f')
144      v = v * 16 + (unsigned long)(c - 'a' + 10);
145    else if (c >= 'A' && c <= 'F')
146      v = v * 16 + (unsigned long)(c - 'A' + 10);
147    else
148      return 0;
149  }
150  *out = v;
151  return 1;
152}
153/* UTF-8. */
154static inline int json_rune_(struct text *t, unsigned long r) {
155  char b[4] = {0, 0, 0, 0};
156  size_t n = r < 0x80 ? 1 : r < 0x800 ? 2 : r < 0x10000 ? 3 : 4;
157  for (size_t i = n; i-- > 1; r >>= 6)
158    b[i] = (char)(0x80 | (r & 0x3f));
159  b[0] = (char)(n == 1 ? r : n == 2 ? 0xc0 | r : n == 3 ? 0xe0 | r : 0xf0 | r);
160  return text_add(t, b, n);
161}
162static inline int json_string_(struct json *j, struct str s, size_t *at, struct json_span *out) {
163  if (json_peek_(s, at) != '"')
164    return 0;
165  (*at)++;
166  size_t from = j->text.len;
167  for (;;) {
168    int c = json_peek_(s, at);
169    if (c < 0x20) /* the end, or a control character */
170      return 0;
171    (*at)++;
172    if (c == '"')
173      break;
174    char one = (char)c;
175    if (c == '\\') {
176      c = json_peek_(s, at);
177      if (c < 0)
178        return 0;
179      (*at)++;
180      if (c == 'u') {
181        unsigned long r = 0, low = 0;
182        if (!json_hex_(s, at, &r))
183          return 0;
184        if (r >= 0xdc00 && r < 0xe000)
185          return 0; /* half of a pair */
186        if (r >= 0xd800 && r < 0xdc00) {
187          if (!json_word_(s, at, STR("\\u")) || !json_hex_(s, at, &low) || low < 0xdc00 || low >= 0xe000)
188            return 0;
189          r = 0x10000 + ((r - 0xd800) << 10) + (low - 0xdc00);
190        }
191        if (!json_rune_(&j->text, r))
192          return 0;
193        continue;
194      }
195      size_t e = str_find(STR("\"\\/bfnrt"), (char)c);
196      if (c == 0 || e == 8)
197        return 0;
198      one = str_part(STR("\"\\/\b\f\n\r\t"), e, 1).p[0];
199    }
200    if (!text_add(&j->text, &one, 1))
201      return 0;
202  }
203  out->at = from;
204  out->len = j->text.len - from;
205  return 1;
206}
207static inline int json_value_(struct json *j, struct str s, size_t *at, struct json_span key, int depth, size_t *out);
208
209/* What is in an array or object, up to its close. */
210static inline int json_items_(struct json *j, struct str s, size_t *at, int object, int depth, size_t *first) {
211  int close = object ? '}' : ']';
212  size_t last = 0;
213  (*at)++;
214  json_space_(s, at);
215  if (json_peek_(s, at) == close) {
216    (*at)++;
217    return 1;
218  }
219  for (;;) {
220    struct json_span key = {0, 0};
221    size_t i = 0;
222    json_space_(s, at);
223    if (object) {
224      if (!json_string_(j, s, at, &key))
225        return 0;
226      json_space_(s, at);
227      if (json_peek_(s, at) != ':')
228        return 0;
229      (*at)++;
230    }
231    if (!json_value_(j, s, at, key, depth, &i))
232      return 0;
233    if (last) {
234      struct json_value v = json_at(j, last);
235      v.next = i;
236      json_values_set(&j->values, last, v);
237    } else {
238      *first = i;
239    }
240    last = i;
241    json_space_(s, at);
242    int c = json_peek_(s, at);
243    (*at)++;
244    if (c == close)
245      return 1;
246    if (c != ',')
247      return 0;
248  }
249}
250
251static inline int json_value_(struct json *j, struct str s, size_t *at, struct json_span key, int depth, size_t *out) {
252  struct json_value v = {.key = key, .kind = JSON_NULL, .none = 0};
253  size_t i = j->values.len, first = 0;
254  if (depth > 500 || !json_values_add(&j->values, v))
255    return 0;
256  json_space_(s, at);
257  int c = json_peek_(s, at);
258  if (c == '{' || c == '[') {
259    if (!json_items_(j, s, at, c == '{', depth + 1, &first))
260      return 0;
261    if (c == '{') {
262      v.kind = JSON_OBJECT;
263      v.first = first;
264    } else {
265      v.kind = JSON_ARRAY;
266      v.first = first;
267    }
268  } else if (c == '"') {
269    struct json_span t = {0, 0};
270    if (!json_string_(j, s, at, &t))
271      return 0;
272    v.kind = JSON_TEXT;
273    v.text = t;
274  } else if (c == 't' || c == 'f') {
275    int yes = c == 't';
276    if (!json_word_(s, at, yes ? STR("true") : STR("false")))
277      return 0;
278    v.kind = JSON_BOOL;
279    v.truth = yes;
280  } else if (c == 'n') {
281    if (!json_word_(s, at, STR("null")))
282      return 0;
283  } else {
284    double d = 0;
285    if (!json_number_(s, at, &d))
286      return 0;
287    v.kind = JSON_NUMBER;
288    v.number = d;
289  }
290  *out = i;
291  return json_values_set(&j->values, i, v);
292}
293
294/* True if s is JSON. If not (or no memory), j is empty and *stop, when not null, is the byte where
295   parsing stopped. */
296SAFEC_MUST_USE static inline bool json_parse(struct json *j, struct str s, size_t *_Nullable stop) {
297  struct json_span none = {0, 0};
298  size_t at = 0, root = 0;
299  json_free(j);
300  if (json_value_(j, s, &at, none, 0, &root)) {
301    json_space_(s, &at);
302    if (at == s.len)
303      return true;
304  }
305  json_free(j);
306  if (stop)
307    *stop = at;
308  return false;
309}
310
311#if defined(__clang__)
312#pragma clang assume_nonnull end
313#endif
314#endif
315