diff options
author | Mark Pulford <mark@kyne.com.au> | 2011-04-15 20:58:53 +0930 |
---|---|---|
committer | Mark Pulford <mark@kyne.com.au> | 2011-04-15 20:58:53 +0930 |
commit | bbf1f5d35e8312fb7373a997664309adf9527af4 (patch) | |
tree | 39dbd1d56cd730e07a27854adda504b8a120ce2f | |
parent | a336401403ed55ca1956c627a5413e456b1f87e8 (diff) | |
download | lua-cjson-bbf1f5d35e8312fb7373a997664309adf9527af4.tar.gz lua-cjson-bbf1f5d35e8312fb7373a997664309adf9527af4.tar.bz2 lua-cjson-bbf1f5d35e8312fb7373a997664309adf9527af4.zip |
Initial commit
Split Lua JSON from parent project to create standalone module.
Remove unnecesssary files from new repo.
-rw-r--r-- | lua_json_decode.c | 405 | ||||
-rw-r--r-- | lua_json_encode.c | 256 | ||||
-rw-r--r-- | rfc4627.txt | 563 | ||||
-rw-r--r-- | strbuf.c | 130 | ||||
-rw-r--r-- | strbuf.h | 48 |
5 files changed, 1402 insertions, 0 deletions
diff --git a/lua_json_decode.c b/lua_json_decode.c new file mode 100644 index 0000000..ae35574 --- /dev/null +++ b/lua_json_decode.c | |||
@@ -0,0 +1,405 @@ | |||
1 | #include <assert.h> | ||
2 | #include <string.h> | ||
3 | #include <lua.h> | ||
4 | #include <lauxlib.h> | ||
5 | #include "strbuf.h" | ||
6 | |||
7 | /* Caveats: | ||
8 | * - NULL values do not work in objects (unssuported by Lua tables). | ||
9 | * - Could use a secial "null" table object, that is unique | ||
10 | * - NULL values work in arrays (probably not at the end) | ||
11 | */ | ||
12 | |||
13 | /* FIXME: | ||
14 | * - Ensure JSON data is UTF-8. Fail otherwise. | ||
15 | * - Alternatively, dynamically support Unicode in JSON string. Return current locale. | ||
16 | * - Use lua_checkstack() to ensure there is enough stack space left to | ||
17 | * fulfill an operation. What happens if we don't, is that acceptible too? | ||
18 | * Does lua_checkstack grow the stack, or merely check if it is possible? | ||
19 | * - Merge encode/decode files | ||
20 | */ | ||
21 | |||
22 | typedef struct { | ||
23 | const char *data; | ||
24 | int index; | ||
25 | strbuf_t *tmp; /* Temporary storage for strings */ | ||
26 | } json_parse_t; | ||
27 | |||
28 | typedef enum { | ||
29 | T_OBJ_BEGIN, | ||
30 | T_OBJ_END, | ||
31 | T_ARR_BEGIN, | ||
32 | T_ARR_END, | ||
33 | T_STRING, | ||
34 | T_NUMBER, | ||
35 | T_BOOLEAN, | ||
36 | T_NULL, | ||
37 | T_COLON, | ||
38 | T_COMMA, | ||
39 | T_END, | ||
40 | T_WHITESPACE, | ||
41 | T_ERROR, | ||
42 | T_UNKNOWN | ||
43 | } json_token_type_t; | ||
44 | |||
45 | static const char *json_token_type_name[] = { | ||
46 | "T_OBJ_BEGIN", | ||
47 | "T_OBJ_END", | ||
48 | "T_ARR_BEGIN", | ||
49 | "T_ARR_END", | ||
50 | "T_STRING", | ||
51 | "T_NUMBER", | ||
52 | "T_BOOLEAN", | ||
53 | "T_NULL", | ||
54 | "T_COLON", | ||
55 | "T_COMMA", | ||
56 | "T_END", | ||
57 | "T_WHITESPACE", | ||
58 | "T_ERROR", | ||
59 | "T_UNKNOWN", | ||
60 | NULL | ||
61 | }; | ||
62 | |||
63 | typedef struct { | ||
64 | json_token_type_t type; | ||
65 | int index; | ||
66 | union { | ||
67 | char *string; | ||
68 | double number; | ||
69 | int boolean; | ||
70 | } value; | ||
71 | int length; /* FIXME: Merge into union? Won't save memory, but more logical */ | ||
72 | } json_token_t; | ||
73 | |||
74 | static void json_process_value(lua_State *l, json_parse_t *json, json_token_t *token); | ||
75 | |||
76 | static json_token_type_t json_ch2token[256]; | ||
77 | static char json_ch2escape[256]; | ||
78 | |||
79 | void json_init_lookup_tables() | ||
80 | { | ||
81 | int i; | ||
82 | |||
83 | /* Tag all characters as an error */ | ||
84 | for (i = 0; i < 256; i++) | ||
85 | json_ch2token[i] = T_ERROR; | ||
86 | |||
87 | /* Set tokens that require no further processing */ | ||
88 | json_ch2token['{'] = T_OBJ_BEGIN; | ||
89 | json_ch2token['}'] = T_OBJ_END; | ||
90 | json_ch2token['['] = T_ARR_BEGIN; | ||
91 | json_ch2token[']'] = T_ARR_END; | ||
92 | json_ch2token[','] = T_COMMA; | ||
93 | json_ch2token[':'] = T_COLON; | ||
94 | json_ch2token['\0'] = T_END; | ||
95 | json_ch2token[' '] = T_WHITESPACE; | ||
96 | json_ch2token['\t'] = T_WHITESPACE; | ||
97 | json_ch2token['\n'] = T_WHITESPACE; | ||
98 | json_ch2token['\r'] = T_WHITESPACE; | ||
99 | |||
100 | /* Update characters that require further processing */ | ||
101 | json_ch2token['n'] = T_UNKNOWN; | ||
102 | json_ch2token['t'] = T_UNKNOWN; | ||
103 | json_ch2token['f'] = T_UNKNOWN; | ||
104 | json_ch2token['"'] = T_UNKNOWN; | ||
105 | json_ch2token['-'] = T_UNKNOWN; | ||
106 | for (i = 0; i < 10; i++) | ||
107 | json_ch2token['0' + i] = T_UNKNOWN; | ||
108 | |||
109 | for (i = 0; i < 256; i++) | ||
110 | json_ch2escape[i] = 0; /* String error */ | ||
111 | |||
112 | json_ch2escape['"'] = '"'; | ||
113 | json_ch2escape['\\'] = '\\'; | ||
114 | json_ch2escape['/'] = '/'; | ||
115 | json_ch2escape['b'] = '\b'; | ||
116 | json_ch2escape['t'] = '\t'; | ||
117 | json_ch2escape['n'] = '\n'; | ||
118 | json_ch2escape['f'] = '\f'; | ||
119 | json_ch2escape['r'] = '\r'; | ||
120 | json_ch2escape['u'] = 'u'; /* This needs to be parsed as unicode */ | ||
121 | } | ||
122 | |||
123 | static void json_next_string_token(json_parse_t *json, json_token_t *token) | ||
124 | { | ||
125 | char ch; | ||
126 | |||
127 | /* Caller must ensure a string is next */ | ||
128 | assert(json->data[json->index] == '"'); | ||
129 | |||
130 | /* Gobble string. FIXME, ugly */ | ||
131 | |||
132 | json->tmp->length = 0; | ||
133 | while ((ch = json->data[++json->index]) != '"') { | ||
134 | /* Handle escapes */ | ||
135 | if (ch == '\\') { | ||
136 | /* Translate escape code */ | ||
137 | ch = json_ch2escape[(unsigned char)json->data[++json->index]]; | ||
138 | if (!ch) { | ||
139 | /* Invalid escape code */ | ||
140 | token->type = T_ERROR; | ||
141 | return; | ||
142 | } | ||
143 | if (ch == 'u') { | ||
144 | /* Process unicode */ | ||
145 | /* FIXME: cleanup memory handling. Implement iconv(3) | ||
146 | * conversion from UCS-2 -> UTF-8 | ||
147 | */ | ||
148 | if (!memcmp(&json->data[json->index], "u0000", 5)) { | ||
149 | /* Handle NULL */ | ||
150 | ch = 0; | ||
151 | json->index += 4; | ||
152 | } else { | ||
153 | /* Remaining codepoints unhandled */ | ||
154 | token->type = T_ERROR; | ||
155 | return; | ||
156 | } | ||
157 | } | ||
158 | } | ||
159 | strbuf_append_char(json->tmp, ch); | ||
160 | } | ||
161 | json->index++; /* Eat final quote (") */ | ||
162 | |||
163 | strbuf_ensure_null(json->tmp); | ||
164 | |||
165 | token->type = T_STRING; | ||
166 | token->value.string = json->tmp->data; | ||
167 | token->length = json->tmp->length; | ||
168 | } | ||
169 | |||
170 | static void json_next_number_token(json_parse_t *json, json_token_t *token) | ||
171 | { | ||
172 | const char *startptr; | ||
173 | char *endptr; | ||
174 | |||
175 | /* FIXME: | ||
176 | * Verify that the number takes the following form: | ||
177 | * -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)? | ||
178 | * strtod() below allows other forms (Hex, infinity, NaN,..) */ | ||
179 | /* i = json->index; | ||
180 | if (json->data[i] == '-') | ||
181 | i++; | ||
182 | j = i; | ||
183 | while ('0' <= json->data[i] && json->data[i] <= '9') | ||
184 | i++; | ||
185 | if (i == j) | ||
186 | return T_ERROR; */ | ||
187 | |||
188 | token->type = T_NUMBER; | ||
189 | startptr = &json->data[json->index]; | ||
190 | token->value.number = strtod(&json->data[json->index], &endptr); | ||
191 | if (startptr == endptr) | ||
192 | token->type = T_ERROR; | ||
193 | else | ||
194 | json->index += endptr - startptr; /* Skip the processed number */ | ||
195 | |||
196 | return; | ||
197 | } | ||
198 | |||
199 | /* Fills in the token struct. | ||
200 | * T_STRING will return a pointer to the json_parse_t temporary string | ||
201 | * T_ERROR will leave the json->index pointer at the error. | ||
202 | */ | ||
203 | static void json_next_token(json_parse_t *json, json_token_t *token) | ||
204 | { | ||
205 | int ch; | ||
206 | |||
207 | /* Eat whitespace. FIXME: UGLY */ | ||
208 | token->type = json_ch2token[(unsigned char)json->data[json->index]]; | ||
209 | while (token->type == T_WHITESPACE) | ||
210 | token->type = json_ch2token[(unsigned char)json->data[++json->index]]; | ||
211 | |||
212 | token->index = json->index; | ||
213 | |||
214 | /* Don't advance the pointer for an error or the end */ | ||
215 | if (token->type == T_ERROR || token->type == T_END) | ||
216 | return; | ||
217 | |||
218 | /* Found a known token, advance index and return */ | ||
219 | if (token->type != T_UNKNOWN) { | ||
220 | json->index++; | ||
221 | return; | ||
222 | } | ||
223 | |||
224 | ch = json->data[json->index]; | ||
225 | |||
226 | /* Process characters which triggered T_UNKNOWN */ | ||
227 | if (ch == '"') { | ||
228 | json_next_string_token(json, token); | ||
229 | return; | ||
230 | } else if (ch == '-' || ('0' <= ch && ch <= '9')) { | ||
231 | json_next_number_token(json, token); | ||
232 | return; | ||
233 | } else if (!strncmp(&json->data[json->index], "true", 4)) { | ||
234 | token->type = T_BOOLEAN; | ||
235 | token->value.boolean = 1; | ||
236 | json->index += 4; | ||
237 | return; | ||
238 | } else if (!strncmp(&json->data[json->index], "false", 5)) { | ||
239 | token->type = T_BOOLEAN; | ||
240 | token->value.boolean = 0; | ||
241 | json->index += 5; | ||
242 | return; | ||
243 | } else if (!strncmp(&json->data[json->index], "null", 4)) { | ||
244 | token->type = T_NULL; | ||
245 | json->index += 4; | ||
246 | return; | ||
247 | } | ||
248 | |||
249 | token->type = T_ERROR; | ||
250 | } | ||
251 | |||
252 | /* This function does not return. | ||
253 | * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED. | ||
254 | * The only allowed exception is the temporary parser string | ||
255 | * json->tmp struct. | ||
256 | * json and token should exist on the stack somewhere. | ||
257 | * luaL_error() will long_jmp and release the stack */ | ||
258 | static void json_throw_parse_error(lua_State *l, json_parse_t *json, | ||
259 | const char *exp, json_token_t *token) | ||
260 | { | ||
261 | strbuf_free(json->tmp); | ||
262 | luaL_error(l, "Expected %s but found type <%s> at character %d", | ||
263 | exp, json_token_type_name[token->type], token->index); | ||
264 | } | ||
265 | |||
266 | static void json_parse_object_context(lua_State *l, json_parse_t *json) | ||
267 | { | ||
268 | json_token_t token; | ||
269 | |||
270 | lua_newtable(l); | ||
271 | |||
272 | json_next_token(json, &token); | ||
273 | |||
274 | /* Handle empty objects */ | ||
275 | if (token.type == T_OBJ_END) | ||
276 | return; | ||
277 | |||
278 | while (1) { | ||
279 | if (token.type != T_STRING) | ||
280 | json_throw_parse_error(l, json, "object key", &token); | ||
281 | |||
282 | lua_pushlstring(l, token.value.string, token.length); /* Push key */ | ||
283 | |||
284 | json_next_token(json, &token); | ||
285 | if (token.type != T_COLON) | ||
286 | json_throw_parse_error(l, json, "colon", &token); | ||
287 | |||
288 | json_next_token(json, &token); | ||
289 | json_process_value(l, json, &token); | ||
290 | lua_rawset(l, -3); /* Set key = value */ | ||
291 | |||
292 | json_next_token(json, &token); | ||
293 | |||
294 | if (token.type == T_OBJ_END) | ||
295 | return; | ||
296 | |||
297 | if (token.type != T_COMMA) | ||
298 | json_throw_parse_error(l, json, "comma or object end", &token); | ||
299 | |||
300 | json_next_token(json, &token); | ||
301 | } while (1); | ||
302 | |||
303 | } | ||
304 | |||
305 | /* Handle the array context */ | ||
306 | static void json_parse_array_context(lua_State *l, json_parse_t *json) | ||
307 | { | ||
308 | json_token_t token; | ||
309 | int i; | ||
310 | |||
311 | lua_newtable(l); | ||
312 | |||
313 | json_next_token(json, &token); | ||
314 | |||
315 | /* Handle empty arrays */ | ||
316 | if (token.type == T_ARR_END) | ||
317 | return; | ||
318 | |||
319 | i = 1; | ||
320 | while (1) { | ||
321 | json_process_value(l, json, &token); | ||
322 | lua_rawseti(l, -2, i); /* arr[i] = value */ | ||
323 | |||
324 | json_next_token(json, &token); | ||
325 | |||
326 | if (token.type == T_ARR_END) | ||
327 | return; | ||
328 | |||
329 | if (token.type != T_COMMA) | ||
330 | json_throw_parse_error(l, json, "comma or array end", &token); | ||
331 | |||
332 | json_next_token(json, &token); | ||
333 | i++; | ||
334 | } | ||
335 | } | ||
336 | |||
337 | /* Handle the "value" context */ | ||
338 | static void json_process_value(lua_State *l, json_parse_t *json, json_token_t *token) | ||
339 | { | ||
340 | switch (token->type) { | ||
341 | case T_STRING: | ||
342 | lua_pushlstring(l, token->value.string, token->length); | ||
343 | break;; | ||
344 | case T_NUMBER: | ||
345 | lua_pushnumber(l, token->value.number); | ||
346 | break;; | ||
347 | case T_BOOLEAN: | ||
348 | lua_pushboolean(l, token->value.boolean); | ||
349 | break;; | ||
350 | case T_OBJ_BEGIN: | ||
351 | json_parse_object_context(l, json); | ||
352 | break;; | ||
353 | case T_ARR_BEGIN: | ||
354 | json_parse_array_context(l, json); | ||
355 | break;; | ||
356 | case T_NULL: | ||
357 | lua_pushnil(l); | ||
358 | break;; | ||
359 | default: | ||
360 | json_throw_parse_error(l, json, "value", token); | ||
361 | } | ||
362 | } | ||
363 | |||
364 | /* json_text must be null terminated string */ | ||
365 | void json_parse(lua_State *l, const char *json_text) | ||
366 | { | ||
367 | json_parse_t json; | ||
368 | json_token_t token; | ||
369 | |||
370 | json.data = json_text; | ||
371 | json.index = 0; | ||
372 | json.tmp = strbuf_new(); | ||
373 | json.tmp->scale = 256; | ||
374 | |||
375 | json_next_token(&json, &token); | ||
376 | json_process_value(l, &json, &token); | ||
377 | |||
378 | /* Ensure there is no more input left */ | ||
379 | json_next_token(&json, &token); | ||
380 | |||
381 | if (token.type != T_END) | ||
382 | json_throw_parse_error(l, &json, "the end", &token); | ||
383 | |||
384 | strbuf_free(json.tmp); | ||
385 | } | ||
386 | |||
387 | int lua_json_decode(lua_State *l) | ||
388 | { | ||
389 | int i, n; | ||
390 | |||
391 | n = lua_gettop(l); | ||
392 | |||
393 | for (i = 1; i <= n; i++) { | ||
394 | if (lua_isstring(l, i)) { | ||
395 | json_parse(l, lua_tostring(l, i)); | ||
396 | } else { | ||
397 | lua_pushnil(l); | ||
398 | } | ||
399 | } | ||
400 | |||
401 | return n; /* Number of results */ | ||
402 | } | ||
403 | |||
404 | /* vi:ai et sw=4 ts=4: | ||
405 | */ | ||
diff --git a/lua_json_encode.c b/lua_json_encode.c new file mode 100644 index 0000000..201f769 --- /dev/null +++ b/lua_json_encode.c | |||
@@ -0,0 +1,256 @@ | |||
1 | /* | ||
2 | * Lua JSON routines | ||
3 | * | ||
4 | * CAVEATS: | ||
5 | * - JSON "null" handling: | ||
6 | * - Decoding a "null" in an array will leave a "nil" placeholder in Lua, but will not show up at the end of the array. | ||
7 | * - Decoding a "null" in an object will ensure that particular key is deleted in the Lua table. | ||
8 | */ | ||
9 | |||
10 | #include <string.h> | ||
11 | #include <math.h> | ||
12 | |||
13 | #include <lua.h> | ||
14 | #include <lauxlib.h> | ||
15 | #include <json/json.h> | ||
16 | |||
17 | #include "lua_json.h" | ||
18 | #include "utils.h" | ||
19 | #include "str.h" | ||
20 | |||
21 | /* FIXME: | ||
22 | * - Don't just pushnil on error and return? | ||
23 | * - Review all strbuf usage for NULL termination | ||
24 | */ | ||
25 | |||
26 | /* JSON escape a character if required, or return NULL */ | ||
27 | static inline char *json_escape_char(int c) | ||
28 | { | ||
29 | switch(c) { | ||
30 | case 0: | ||
31 | return "\\u0000"; | ||
32 | case '\\': | ||
33 | return "\\\\"; | ||
34 | case '"': | ||
35 | return "\\\""; | ||
36 | case '\b': | ||
37 | return "\\b"; | ||
38 | case '\t': | ||
39 | return "\\t"; | ||
40 | case '\n': | ||
41 | return "\\n"; | ||
42 | case '\f': | ||
43 | return "\\f"; | ||
44 | case '\r': | ||
45 | return "\\r"; | ||
46 | } | ||
47 | |||
48 | return NULL; | ||
49 | } | ||
50 | |||
51 | /* FIXME: | ||
52 | * - Use lua_checklstring() instead of lua_tolstring() ?* | ||
53 | */ | ||
54 | |||
55 | /* FIXME: | ||
56 | * - Option to encode non-printable characters? Only \" \\ are required | ||
57 | * - Unicode? | ||
58 | * - Improve performance? | ||
59 | */ | ||
60 | static void json_append_string(lua_State *l, struct str *json, int index) | ||
61 | { | ||
62 | char *p; | ||
63 | int i; | ||
64 | const char *str; | ||
65 | size_t len; | ||
66 | |||
67 | str = lua_tolstring(l, index, &len); | ||
68 | |||
69 | strbuf_append_char(json, '\"'); | ||
70 | for (i = 0; i < len; i++) { | ||
71 | p = json_escape_char(str[i]); | ||
72 | if (p) | ||
73 | strbuf_append_mem(json, p, strlen(p)); | ||
74 | else | ||
75 | strbuf_append_char(json, str[i]); | ||
76 | } | ||
77 | strbuf_append_char(json, '\"'); | ||
78 | } | ||
79 | |||
80 | /* Find the size of the array on the top of the Lua stack | ||
81 | * -1 object | ||
82 | * >=0 elements in array | ||
83 | */ | ||
84 | static int lua_array_length(lua_State *l) | ||
85 | { | ||
86 | double k; | ||
87 | int max; | ||
88 | |||
89 | max = 0; | ||
90 | |||
91 | lua_pushnil(l); | ||
92 | /* table, startkey */ | ||
93 | while (lua_next(l, -2) != 0) { | ||
94 | /* table, key, value */ | ||
95 | if ((k = lua_tonumber(l, -2))) { | ||
96 | /* Integer >= 1 ? */ | ||
97 | if (floor(k) == k && k >= 1) { | ||
98 | if (k > max) | ||
99 | max = k; | ||
100 | lua_pop(l, 1); | ||
101 | continue; | ||
102 | } | ||
103 | } | ||
104 | |||
105 | /* Must not be an array (non integer key) */ | ||
106 | lua_pop(l, 2); | ||
107 | return -1; | ||
108 | } | ||
109 | |||
110 | return max; | ||
111 | } | ||
112 | |||
113 | static void json_append_data(lua_State *l, struct str *s); | ||
114 | |||
115 | static void json_append_array(lua_State *l, struct str *s, int size) | ||
116 | { | ||
117 | int comma, i; | ||
118 | |||
119 | strbuf_append_mem(s, "[ ", 2); | ||
120 | |||
121 | comma = 0; | ||
122 | for (i = 1; i <= size; i++) { | ||
123 | if (comma) | ||
124 | strbuf_append_mem(s, ", ", 2); | ||
125 | else | ||
126 | comma = 1; | ||
127 | |||
128 | lua_rawgeti(l, -1, i); | ||
129 | json_append_data(l, s); | ||
130 | lua_pop(l, 1); | ||
131 | } | ||
132 | |||
133 | strbuf_append_mem(s, " ]", 2); | ||
134 | } | ||
135 | |||
136 | static void json_append_object(lua_State *l, struct str *s) | ||
137 | { | ||
138 | int comma, keytype; | ||
139 | |||
140 | /* Object */ | ||
141 | strbuf_append_mem(s, "{ ", 2); | ||
142 | |||
143 | lua_pushnil(l); | ||
144 | /* table, startkey */ | ||
145 | comma = 0; | ||
146 | while (lua_next(l, -2) != 0) { | ||
147 | if (comma) | ||
148 | strbuf_append_mem(s, ", ", 2); | ||
149 | else | ||
150 | comma = 1; | ||
151 | |||
152 | /* table, key, value */ | ||
153 | keytype = lua_type(l, -2); | ||
154 | if (keytype == LUA_TNUMBER) { | ||
155 | strbuf_append(s, "\"" LUA_NUMBER_FMT "\": ", lua_tonumber(l, -2)); | ||
156 | } else if (keytype == LUA_TSTRING) { | ||
157 | json_append_string(l, s, -2); | ||
158 | strbuf_append_mem(s, ": ", 2); | ||
159 | } else { | ||
160 | die("Cannot serialise table key %s", lua_typename(l, lua_type(l, -2))); | ||
161 | } | ||
162 | |||
163 | /* table, key, value */ | ||
164 | json_append_data(l, s); | ||
165 | lua_pop(l, 1); | ||
166 | /* table, key */ | ||
167 | } | ||
168 | |||
169 | strbuf_append_mem(s, " }", 2); | ||
170 | } | ||
171 | |||
172 | /* Serialise Lua data into JSON string. | ||
173 | * | ||
174 | * FIXME: | ||
175 | * - Error handling when cannot serialise key or value (return to script) | ||
176 | */ | ||
177 | static void json_append_data(lua_State *l, struct str *s) | ||
178 | { | ||
179 | int len; | ||
180 | |||
181 | switch (lua_type(l, -1)) { | ||
182 | case LUA_TSTRING: | ||
183 | json_append_string(l, s, -1); | ||
184 | break; | ||
185 | case LUA_TNUMBER: | ||
186 | strbuf_append(s, "%lf", lua_tonumber(l, -1)); | ||
187 | break; | ||
188 | case LUA_TBOOLEAN: | ||
189 | if (lua_toboolean(l, -1)) | ||
190 | strbuf_append_mem(s, "true", 4); | ||
191 | else | ||
192 | strbuf_append_mem(s, "false", 5); | ||
193 | break; | ||
194 | case LUA_TTABLE: | ||
195 | len = lua_array_length(l); | ||
196 | if (len >= 0) | ||
197 | json_append_array(l, s, len); | ||
198 | else | ||
199 | json_append_object(l, s); | ||
200 | break; | ||
201 | case LUA_TNIL: | ||
202 | strbuf_append_mem(s, "null", 4); | ||
203 | break; | ||
204 | default: | ||
205 | /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD, and LUA_TLIGHTUSERDATA) | ||
206 | * cannot be serialised */ | ||
207 | /* FIXME: return error */ | ||
208 | die("Cannot serialise %s", lua_typename(l, lua_type(l, -1))); | ||
209 | } | ||
210 | } | ||
211 | |||
212 | char *lua_to_json(lua_State *l, int *len) | ||
213 | { | ||
214 | struct str *s; | ||
215 | char *data; | ||
216 | |||
217 | s = strbuf_new(); | ||
218 | strbuf_set_increment(s, 256); | ||
219 | json_append_data(l, s); | ||
220 | data = strbuf_to_char(s, len); | ||
221 | |||
222 | return data; | ||
223 | } | ||
224 | |||
225 | int lua_json_encode(lua_State *l) | ||
226 | { | ||
227 | char *json; | ||
228 | int len; | ||
229 | |||
230 | json = lua_to_json(l, &len); | ||
231 | lua_pushlstring(l, json, len); | ||
232 | free(json); | ||
233 | |||
234 | return 1; | ||
235 | } | ||
236 | |||
237 | void lua_json_init(lua_State *l) | ||
238 | { | ||
239 | luaL_Reg reg[] = { | ||
240 | { "encode", lua_json_encode }, | ||
241 | { "decode", lua_json_decode }, | ||
242 | { NULL, NULL } | ||
243 | }; | ||
244 | |||
245 | /* Create "db" table. | ||
246 | * Added functions as table entries | ||
247 | */ | ||
248 | |||
249 | luaL_register(l, "json", reg); | ||
250 | |||
251 | /* FIXME: Debugging */ | ||
252 | json_init_lookup_tables(); | ||
253 | } | ||
254 | |||
255 | /* vi:ai et sw=4 ts=4: | ||
256 | */ | ||
diff --git a/rfc4627.txt b/rfc4627.txt new file mode 100644 index 0000000..67b8909 --- /dev/null +++ b/rfc4627.txt | |||
@@ -0,0 +1,563 @@ | |||
1 | |||
2 | |||
3 | |||
4 | |||
5 | |||
6 | |||
7 | Network Working Group D. Crockford | ||
8 | Request for Comments: 4627 JSON.org | ||
9 | Category: Informational July 2006 | ||
10 | |||
11 | |||
12 | The application/json Media Type for JavaScript Object Notation (JSON) | ||
13 | |||
14 | Status of This Memo | ||
15 | |||
16 | This memo provides information for the Internet community. It does | ||
17 | not specify an Internet standard of any kind. Distribution of this | ||
18 | memo is unlimited. | ||
19 | |||
20 | Copyright Notice | ||
21 | |||
22 | Copyright (C) The Internet Society (2006). | ||
23 | |||
24 | Abstract | ||
25 | |||
26 | JavaScript Object Notation (JSON) is a lightweight, text-based, | ||
27 | language-independent data interchange format. It was derived from | ||
28 | the ECMAScript Programming Language Standard. JSON defines a small | ||
29 | set of formatting rules for the portable representation of structured | ||
30 | data. | ||
31 | |||
32 | 1. Introduction | ||
33 | |||
34 | JavaScript Object Notation (JSON) is a text format for the | ||
35 | serialization of structured data. It is derived from the object | ||
36 | literals of JavaScript, as defined in the ECMAScript Programming | ||
37 | Language Standard, Third Edition [ECMA]. | ||
38 | |||
39 | JSON can represent four primitive types (strings, numbers, booleans, | ||
40 | and null) and two structured types (objects and arrays). | ||
41 | |||
42 | A string is a sequence of zero or more Unicode characters [UNICODE]. | ||
43 | |||
44 | An object is an unordered collection of zero or more name/value | ||
45 | pairs, where a name is a string and a value is a string, number, | ||
46 | boolean, null, object, or array. | ||
47 | |||
48 | An array is an ordered sequence of zero or more values. | ||
49 | |||
50 | The terms "object" and "array" come from the conventions of | ||
51 | JavaScript. | ||
52 | |||
53 | JSON's design goals were for it to be minimal, portable, textual, and | ||
54 | a subset of JavaScript. | ||
55 | |||
56 | |||
57 | |||
58 | Crockford Informational [Page 1] | ||
59 | |||
60 | RFC 4627 JSON July 2006 | ||
61 | |||
62 | |||
63 | 1.1. Conventions Used in This Document | ||
64 | |||
65 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", | ||
66 | "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this | ||
67 | document are to be interpreted as described in [RFC2119]. | ||
68 | |||
69 | The grammatical rules in this document are to be interpreted as | ||
70 | described in [RFC4234]. | ||
71 | |||
72 | 2. JSON Grammar | ||
73 | |||
74 | A JSON text is a sequence of tokens. The set of tokens includes six | ||
75 | structural characters, strings, numbers, and three literal names. | ||
76 | |||
77 | A JSON text is a serialized object or array. | ||
78 | |||
79 | JSON-text = object / array | ||
80 | |||
81 | These are the six structural characters: | ||
82 | |||
83 | begin-array = ws %x5B ws ; [ left square bracket | ||
84 | |||
85 | begin-object = ws %x7B ws ; { left curly bracket | ||
86 | |||
87 | end-array = ws %x5D ws ; ] right square bracket | ||
88 | |||
89 | end-object = ws %x7D ws ; } right curly bracket | ||
90 | |||
91 | name-separator = ws %x3A ws ; : colon | ||
92 | |||
93 | value-separator = ws %x2C ws ; , comma | ||
94 | |||
95 | Insignificant whitespace is allowed before or after any of the six | ||
96 | structural characters. | ||
97 | |||
98 | ws = *( | ||
99 | %x20 / ; Space | ||
100 | %x09 / ; Horizontal tab | ||
101 | %x0A / ; Line feed or New line | ||
102 | %x0D ; Carriage return | ||
103 | ) | ||
104 | |||
105 | 2.1. Values | ||
106 | |||
107 | A JSON value MUST be an object, array, number, or string, or one of | ||
108 | the following three literal names: | ||
109 | |||
110 | false null true | ||
111 | |||
112 | |||
113 | |||
114 | Crockford Informational [Page 2] | ||
115 | |||
116 | RFC 4627 JSON July 2006 | ||
117 | |||
118 | |||
119 | The literal names MUST be lowercase. No other literal names are | ||
120 | allowed. | ||
121 | |||
122 | value = false / null / true / object / array / number / string | ||
123 | |||
124 | false = %x66.61.6c.73.65 ; false | ||
125 | |||
126 | null = %x6e.75.6c.6c ; null | ||
127 | |||
128 | true = %x74.72.75.65 ; true | ||
129 | |||
130 | 2.2. Objects | ||
131 | |||
132 | An object structure is represented as a pair of curly brackets | ||
133 | surrounding zero or more name/value pairs (or members). A name is a | ||
134 | string. A single colon comes after each name, separating the name | ||
135 | from the value. A single comma separates a value from a following | ||
136 | name. The names within an object SHOULD be unique. | ||
137 | |||
138 | object = begin-object [ member *( value-separator member ) ] | ||
139 | end-object | ||
140 | |||
141 | member = string name-separator value | ||
142 | |||
143 | 2.3. Arrays | ||
144 | |||
145 | An array structure is represented as square brackets surrounding zero | ||
146 | or more values (or elements). Elements are separated by commas. | ||
147 | |||
148 | array = begin-array [ value *( value-separator value ) ] end-array | ||
149 | |||
150 | 2.4. Numbers | ||
151 | |||
152 | The representation of numbers is similar to that used in most | ||
153 | programming languages. A number contains an integer component that | ||
154 | may be prefixed with an optional minus sign, which may be followed by | ||
155 | a fraction part and/or an exponent part. | ||
156 | |||
157 | Octal and hex forms are not allowed. Leading zeros are not allowed. | ||
158 | |||
159 | A fraction part is a decimal point followed by one or more digits. | ||
160 | |||
161 | An exponent part begins with the letter E in upper or lowercase, | ||
162 | which may be followed by a plus or minus sign. The E and optional | ||
163 | sign are followed by one or more digits. | ||
164 | |||
165 | Numeric values that cannot be represented as sequences of digits | ||
166 | (such as Infinity and NaN) are not permitted. | ||
167 | |||
168 | |||
169 | |||
170 | Crockford Informational [Page 3] | ||
171 | |||
172 | RFC 4627 JSON July 2006 | ||
173 | |||
174 | |||
175 | number = [ minus ] int [ frac ] [ exp ] | ||
176 | |||
177 | decimal-point = %x2E ; . | ||
178 | |||
179 | digit1-9 = %x31-39 ; 1-9 | ||
180 | |||
181 | e = %x65 / %x45 ; e E | ||
182 | |||
183 | exp = e [ minus / plus ] 1*DIGIT | ||
184 | |||
185 | frac = decimal-point 1*DIGIT | ||
186 | |||
187 | int = zero / ( digit1-9 *DIGIT ) | ||
188 | |||
189 | minus = %x2D ; - | ||
190 | |||
191 | plus = %x2B ; + | ||
192 | |||
193 | zero = %x30 ; 0 | ||
194 | |||
195 | 2.5. Strings | ||
196 | |||
197 | The representation of strings is similar to conventions used in the C | ||
198 | family of programming languages. A string begins and ends with | ||
199 | quotation marks. All Unicode characters may be placed within the | ||
200 | quotation marks except for the characters that must be escaped: | ||
201 | quotation mark, reverse solidus, and the control characters (U+0000 | ||
202 | through U+001F). | ||
203 | |||
204 | Any character may be escaped. If the character is in the Basic | ||
205 | Multilingual Plane (U+0000 through U+FFFF), then it may be | ||
206 | represented as a six-character sequence: a reverse solidus, followed | ||
207 | by the lowercase letter u, followed by four hexadecimal digits that | ||
208 | encode the character's code point. The hexadecimal letters A though | ||
209 | F can be upper or lowercase. So, for example, a string containing | ||
210 | only a single reverse solidus character may be represented as | ||
211 | "\u005C". | ||
212 | |||
213 | Alternatively, there are two-character sequence escape | ||
214 | representations of some popular characters. So, for example, a | ||
215 | string containing only a single reverse solidus character may be | ||
216 | represented more compactly as "\\". | ||
217 | |||
218 | To escape an extended character that is not in the Basic Multilingual | ||
219 | Plane, the character is represented as a twelve-character sequence, | ||
220 | encoding the UTF-16 surrogate pair. So, for example, a string | ||
221 | containing only the G clef character (U+1D11E) may be represented as | ||
222 | "\uD834\uDD1E". | ||
223 | |||
224 | |||
225 | |||
226 | Crockford Informational [Page 4] | ||
227 | |||
228 | RFC 4627 JSON July 2006 | ||
229 | |||
230 | |||
231 | string = quotation-mark *char quotation-mark | ||
232 | |||
233 | char = unescaped / | ||
234 | escape ( | ||
235 | %x22 / ; " quotation mark U+0022 | ||
236 | %x5C / ; \ reverse solidus U+005C | ||
237 | %x2F / ; / solidus U+002F | ||
238 | %x62 / ; b backspace U+0008 | ||
239 | %x66 / ; f form feed U+000C | ||
240 | %x6E / ; n line feed U+000A | ||
241 | %x72 / ; r carriage return U+000D | ||
242 | %x74 / ; t tab U+0009 | ||
243 | %x75 4HEXDIG ) ; uXXXX U+XXXX | ||
244 | |||
245 | escape = %x5C ; \ | ||
246 | |||
247 | quotation-mark = %x22 ; " | ||
248 | |||
249 | unescaped = %x20-21 / %x23-5B / %x5D-10FFFF | ||
250 | |||
251 | 3. Encoding | ||
252 | |||
253 | JSON text SHALL be encoded in Unicode. The default encoding is | ||
254 | UTF-8. | ||
255 | |||
256 | Since the first two characters of a JSON text will always be ASCII | ||
257 | characters [RFC0020], it is possible to determine whether an octet | ||
258 | stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking | ||
259 | at the pattern of nulls in the first four octets. | ||
260 | |||
261 | 00 00 00 xx UTF-32BE | ||
262 | 00 xx 00 xx UTF-16BE | ||
263 | xx 00 00 00 UTF-32LE | ||
264 | xx 00 xx 00 UTF-16LE | ||
265 | xx xx xx xx UTF-8 | ||
266 | |||
267 | 4. Parsers | ||
268 | |||
269 | A JSON parser transforms a JSON text into another representation. A | ||
270 | JSON parser MUST accept all texts that conform to the JSON grammar. | ||
271 | A JSON parser MAY accept non-JSON forms or extensions. | ||
272 | |||
273 | An implementation may set limits on the size of texts that it | ||
274 | accepts. An implementation may set limits on the maximum depth of | ||
275 | nesting. An implementation may set limits on the range of numbers. | ||
276 | An implementation may set limits on the length and character contents | ||
277 | of strings. | ||
278 | |||
279 | |||
280 | |||
281 | |||
282 | Crockford Informational [Page 5] | ||
283 | |||
284 | RFC 4627 JSON July 2006 | ||
285 | |||
286 | |||
287 | 5. Generators | ||
288 | |||
289 | A JSON generator produces JSON text. The resulting text MUST | ||
290 | strictly conform to the JSON grammar. | ||
291 | |||
292 | 6. IANA Considerations | ||
293 | |||
294 | The MIME media type for JSON text is application/json. | ||
295 | |||
296 | Type name: application | ||
297 | |||
298 | Subtype name: json | ||
299 | |||
300 | Required parameters: n/a | ||
301 | |||
302 | Optional parameters: n/a | ||
303 | |||
304 | Encoding considerations: 8bit if UTF-8; binary if UTF-16 or UTF-32 | ||
305 | |||
306 | JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON | ||
307 | is written in UTF-8, JSON is 8bit compatible. When JSON is | ||
308 | written in UTF-16 or UTF-32, the binary content-transfer-encoding | ||
309 | must be used. | ||
310 | |||
311 | Security considerations: | ||
312 | |||
313 | Generally there are security issues with scripting languages. JSON | ||
314 | is a subset of JavaScript, but it is a safe subset that excludes | ||
315 | assignment and invocation. | ||
316 | |||
317 | A JSON text can be safely passed into JavaScript's eval() function | ||
318 | (which compiles and executes a string) if all the characters not | ||
319 | enclosed in strings are in the set of characters that form JSON | ||
320 | tokens. This can be quickly determined in JavaScript with two | ||
321 | regular expressions and calls to the test and replace methods. | ||
322 | |||
323 | var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( | ||
324 | text.replace(/"(\\.|[^"\\])*"/g, ''))) && | ||
325 | eval('(' + text + ')'); | ||
326 | |||
327 | Interoperability considerations: n/a | ||
328 | |||
329 | Published specification: RFC 4627 | ||
330 | |||
331 | |||
332 | |||
333 | |||
334 | |||
335 | |||
336 | |||
337 | |||
338 | Crockford Informational [Page 6] | ||
339 | |||
340 | RFC 4627 JSON July 2006 | ||
341 | |||
342 | |||
343 | Applications that use this media type: | ||
344 | |||
345 | JSON has been used to exchange data between applications written | ||
346 | in all of these programming languages: ActionScript, C, C#, | ||
347 | ColdFusion, Common Lisp, E, Erlang, Java, JavaScript, Lua, | ||
348 | Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Scheme. | ||
349 | |||
350 | Additional information: | ||
351 | |||
352 | Magic number(s): n/a | ||
353 | File extension(s): .json | ||
354 | Macintosh file type code(s): TEXT | ||
355 | |||
356 | Person & email address to contact for further information: | ||
357 | Douglas Crockford | ||
358 | douglas@crockford.com | ||
359 | |||
360 | Intended usage: COMMON | ||
361 | |||
362 | Restrictions on usage: none | ||
363 | |||
364 | Author: | ||
365 | Douglas Crockford | ||
366 | douglas@crockford.com | ||
367 | |||
368 | Change controller: | ||
369 | Douglas Crockford | ||
370 | douglas@crockford.com | ||
371 | |||
372 | 7. Security Considerations | ||
373 | |||
374 | See Security Considerations in Section 6. | ||
375 | |||
376 | 8. Examples | ||
377 | |||
378 | This is a JSON object: | ||
379 | |||
380 | { | ||
381 | "Image": { | ||
382 | "Width": 800, | ||
383 | "Height": 600, | ||
384 | "Title": "View from 15th Floor", | ||
385 | "Thumbnail": { | ||
386 | "Url": "http://www.example.com/image/481989943", | ||
387 | "Height": 125, | ||
388 | "Width": "100" | ||
389 | }, | ||
390 | "IDs": [116, 943, 234, 38793] | ||
391 | |||
392 | |||
393 | |||
394 | Crockford Informational [Page 7] | ||
395 | |||
396 | RFC 4627 JSON July 2006 | ||
397 | |||
398 | |||
399 | } | ||
400 | } | ||
401 | |||
402 | Its Image member is an object whose Thumbnail member is an object | ||
403 | and whose IDs member is an array of numbers. | ||
404 | |||
405 | This is a JSON array containing two objects: | ||
406 | |||
407 | [ | ||
408 | { | ||
409 | "precision": "zip", | ||
410 | "Latitude": 37.7668, | ||
411 | "Longitude": -122.3959, | ||
412 | "Address": "", | ||
413 | "City": "SAN FRANCISCO", | ||
414 | "State": "CA", | ||
415 | "Zip": "94107", | ||
416 | "Country": "US" | ||
417 | }, | ||
418 | { | ||
419 | "precision": "zip", | ||
420 | "Latitude": 37.371991, | ||
421 | "Longitude": -122.026020, | ||
422 | "Address": "", | ||
423 | "City": "SUNNYVALE", | ||
424 | "State": "CA", | ||
425 | "Zip": "94085", | ||
426 | "Country": "US" | ||
427 | } | ||
428 | ] | ||
429 | |||
430 | 9. References | ||
431 | |||
432 | 9.1. Normative References | ||
433 | |||
434 | [ECMA] European Computer Manufacturers Association, "ECMAScript | ||
435 | Language Specification 3rd Edition", December 1999, | ||
436 | <http://www.ecma-international.org/publications/files/ | ||
437 | ecma-st/ECMA-262.pdf>. | ||
438 | |||
439 | [RFC0020] Cerf, V., "ASCII format for network interchange", RFC 20, | ||
440 | October 1969. | ||
441 | |||
442 | [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate | ||
443 | Requirement Levels", BCP 14, RFC 2119, March 1997. | ||
444 | |||
445 | [RFC4234] Crocker, D. and P. Overell, "Augmented BNF for Syntax | ||
446 | Specifications: ABNF", RFC 4234, October 2005. | ||
447 | |||
448 | |||
449 | |||
450 | Crockford Informational [Page 8] | ||
451 | |||
452 | RFC 4627 JSON July 2006 | ||
453 | |||
454 | |||
455 | [UNICODE] The Unicode Consortium, "The Unicode Standard Version 4.0", | ||
456 | 2003, <http://www.unicode.org/versions/Unicode4.1.0/>. | ||
457 | |||
458 | Author's Address | ||
459 | |||
460 | Douglas Crockford | ||
461 | JSON.org | ||
462 | EMail: douglas@crockford.com | ||
463 | |||
464 | |||
465 | |||
466 | |||
467 | |||
468 | |||
469 | |||
470 | |||
471 | |||
472 | |||
473 | |||
474 | |||
475 | |||
476 | |||
477 | |||
478 | |||
479 | |||
480 | |||
481 | |||
482 | |||
483 | |||
484 | |||
485 | |||
486 | |||
487 | |||
488 | |||
489 | |||
490 | |||
491 | |||
492 | |||
493 | |||
494 | |||
495 | |||
496 | |||
497 | |||
498 | |||
499 | |||
500 | |||
501 | |||
502 | |||
503 | |||
504 | |||
505 | |||
506 | Crockford Informational [Page 9] | ||
507 | |||
508 | RFC 4627 JSON July 2006 | ||
509 | |||
510 | |||
511 | Full Copyright Statement | ||
512 | |||
513 | Copyright (C) The Internet Society (2006). | ||
514 | |||
515 | This document is subject to the rights, licenses and restrictions | ||
516 | contained in BCP 78, and except as set forth therein, the authors | ||
517 | retain all their rights. | ||
518 | |||
519 | This document and the information contained herein are provided on an | ||
520 | "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS | ||
521 | OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET | ||
522 | ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, | ||
523 | INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE | ||
524 | INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED | ||
525 | WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
526 | |||
527 | Intellectual Property | ||
528 | |||
529 | The IETF takes no position regarding the validity or scope of any | ||
530 | Intellectual Property Rights or other rights that might be claimed to | ||
531 | pertain to the implementation or use of the technology described in | ||
532 | this document or the extent to which any license under such rights | ||
533 | might or might not be available; nor does it represent that it has | ||
534 | made any independent effort to identify any such rights. Information | ||
535 | on the procedures with respect to rights in RFC documents can be | ||
536 | found in BCP 78 and BCP 79. | ||
537 | |||
538 | Copies of IPR disclosures made to the IETF Secretariat and any | ||
539 | assurances of licenses to be made available, or the result of an | ||
540 | attempt made to obtain a general license or permission for the use of | ||
541 | such proprietary rights by implementers or users of this | ||
542 | specification can be obtained from the IETF on-line IPR repository at | ||
543 | http://www.ietf.org/ipr. | ||
544 | |||
545 | The IETF invites any interested party to bring to its attention any | ||
546 | copyrights, patents or patent applications, or other proprietary | ||
547 | rights that may cover technology that may be required to implement | ||
548 | this standard. Please address the information to the IETF at | ||
549 | ietf-ipr@ietf.org. | ||
550 | |||
551 | Acknowledgement | ||
552 | |||
553 | Funding for the RFC Editor function is provided by the IETF | ||
554 | Administrative Support Activity (IASA). | ||
555 | |||
556 | |||
557 | |||
558 | |||
559 | |||
560 | |||
561 | |||
562 | Crockford Informational [Page 10] | ||
563 | |||
diff --git a/strbuf.c b/strbuf.c new file mode 100644 index 0000000..f823884 --- /dev/null +++ b/strbuf.c | |||
@@ -0,0 +1,130 @@ | |||
1 | #include <stdio.h> | ||
2 | #include <stdlib.h> | ||
3 | #include <stdarg.h> | ||
4 | #include <string.h> | ||
5 | |||
6 | #include "strbuf.h" | ||
7 | |||
8 | static void die(const char *format, ...) | ||
9 | { | ||
10 | va_list arg; | ||
11 | |||
12 | va_start(arg, format); | ||
13 | vfprintf(stderr, format, arg); | ||
14 | va_end(arg); | ||
15 | |||
16 | exit(-1); | ||
17 | } | ||
18 | |||
19 | void strbuf_init(strbuf_t *s) | ||
20 | { | ||
21 | s->data = NULL; | ||
22 | s->size = 0; | ||
23 | s->length = 0; | ||
24 | s->increment = STRBUF_DEFAULT_INCREMENT; | ||
25 | } | ||
26 | |||
27 | strbuf_t *strbuf_new() | ||
28 | { | ||
29 | strbuf_t *s; | ||
30 | |||
31 | s = malloc(sizeof(strbuf_t)); | ||
32 | if (!s) | ||
33 | die("Out of memory"); | ||
34 | |||
35 | strbuf_init(s); | ||
36 | |||
37 | return s; | ||
38 | } | ||
39 | |||
40 | void strbuf_set_increment(strbuf_t *s, int increment) | ||
41 | { | ||
42 | if (increment <= 0) | ||
43 | die("BUG: Invalid string increment"); | ||
44 | |||
45 | s->increment = increment; | ||
46 | } | ||
47 | |||
48 | void strbuf_free(strbuf_t *s) | ||
49 | { | ||
50 | if (s->data) | ||
51 | free(s->data); | ||
52 | free(s); | ||
53 | } | ||
54 | |||
55 | char *strbuf_to_char(strbuf_t *s, int *len) | ||
56 | { | ||
57 | char *data; | ||
58 | |||
59 | data = s->data; | ||
60 | if (len) | ||
61 | *len = s->length; | ||
62 | |||
63 | free(s); | ||
64 | |||
65 | return data; | ||
66 | } | ||
67 | |||
68 | /* Ensure strbuf can handle a string length bytes long (ignoring NULL | ||
69 | * optional termination). */ | ||
70 | void strbuf_resize(strbuf_t *s, int len) | ||
71 | { | ||
72 | int newsize; | ||
73 | |||
74 | /* Esnure there is room for optional NULL termination */ | ||
75 | newsize = len + 1; | ||
76 | /* Round up to the next increment */ | ||
77 | newsize = ((newsize + s->increment - 1) / s->increment) * s->increment; | ||
78 | s->size = newsize; | ||
79 | s->data = realloc(s->data, s->size); | ||
80 | if (!s->data) | ||
81 | die("Out of memory"); | ||
82 | } | ||
83 | |||
84 | void strbuf_append_mem(strbuf_t *s, const char *c, int len) | ||
85 | { | ||
86 | if (len > strbuf_emptylen(s)) | ||
87 | strbuf_resize(s, s->length + len); | ||
88 | |||
89 | memcpy(s->data + s->length, c, len); | ||
90 | s->length += len; | ||
91 | } | ||
92 | |||
93 | void strbuf_ensure_null(strbuf_t *s) | ||
94 | { | ||
95 | s->data[s->length] = 0; | ||
96 | } | ||
97 | |||
98 | void strbuf_append_fmt(strbuf_t *s, const char *fmt, ...) | ||
99 | { | ||
100 | va_list arg; | ||
101 | int fmt_len, try; | ||
102 | int empty_len; | ||
103 | |||
104 | /* If the first attempt to append fails, resize the buffer appropriately | ||
105 | * and try again */ | ||
106 | for (try = 0; ; try++) { | ||
107 | va_start(arg, fmt); | ||
108 | /* Append the new formatted string */ | ||
109 | /* fmt_len is the length of the string required, excluding the | ||
110 | * trailing NULL */ | ||
111 | empty_len = strbuf_emptylen(s); | ||
112 | /* Add 1 since there is also space for the terminating NULL. | ||
113 | * If the string hasn't been allocated then empty_len == -1, | ||
114 | * and vsprintf() won't store anything on the first pass */ | ||
115 | fmt_len = vsnprintf(s->data + s->length, empty_len + 1, fmt, arg); | ||
116 | va_end(arg); | ||
117 | |||
118 | if (fmt_len <= empty_len) | ||
119 | break; /* SUCCESS */ | ||
120 | if (try > 0) | ||
121 | die("BUG: length of formatted string changed"); | ||
122 | |||
123 | strbuf_resize(s, s->length + fmt_len); | ||
124 | } | ||
125 | |||
126 | s->length += fmt_len; | ||
127 | } | ||
128 | |||
129 | /* vi:ai et sw=4 ts=4: | ||
130 | */ | ||
diff --git a/strbuf.h b/strbuf.h new file mode 100644 index 0000000..fb07e6f --- /dev/null +++ b/strbuf.h | |||
@@ -0,0 +1,48 @@ | |||
1 | #include <stdlib.h> | ||
2 | #include <stdarg.h> | ||
3 | |||
4 | typedef struct { | ||
5 | char *data; | ||
6 | int size; /* Bytes allocated */ | ||
7 | int length; /* Current length of string, not including NULL */ | ||
8 | int increment; /* Allocation Increments */ | ||
9 | } strbuf_t; | ||
10 | |||
11 | #ifndef STRBUF_DEFAULT_INCREMENT | ||
12 | #define STRBUF_DEFAULT_INCREMENT 8 | ||
13 | #endif | ||
14 | |||
15 | extern void strbuf_init(strbuf_t *s); | ||
16 | extern strbuf_t *strbuf_new(); | ||
17 | extern void strbuf_free(strbuf_t *s); | ||
18 | extern char *strbuf_to_char(strbuf_t *s, int *len); | ||
19 | |||
20 | extern void strbuf_set_increment(strbuf_t *s, int increment); | ||
21 | extern void strbuf_resize(strbuf_t *s, int len); | ||
22 | extern void strbuf_append_fmt(strbuf_t *s, const char *format, ...); | ||
23 | extern void strbuf_append_mem(strbuf_t *s, const char *c, int len); | ||
24 | extern void strbuf_ensure_null(strbuf_t *s); | ||
25 | |||
26 | /* Return bytes remaining in the string buffer | ||
27 | * Ensure there is space for a NULL. | ||
28 | * Returns -1 if the string has not been allocated yet */ | ||
29 | static inline int strbuf_emptylen(strbuf_t *s) | ||
30 | { | ||
31 | return s->size - s->length - 1; | ||
32 | } | ||
33 | |||
34 | static inline int strbuf_length(strbuf_t *s) | ||
35 | { | ||
36 | return s->length; | ||
37 | } | ||
38 | |||
39 | static inline void strbuf_append_char(strbuf_t *s, const char c) | ||
40 | { | ||
41 | if (strbuf_emptylen(s) < 1) | ||
42 | strbuf_resize(s, s->length + 1); | ||
43 | |||
44 | s->data[s->length++] = c; | ||
45 | } | ||
46 | |||
47 | /* vi:ai et sw=4 ts=4: | ||
48 | */ | ||