Make hashtable less generic
[jansson.git] / src / dump.c
1 /*
2  * Copyright (c) 2009-2011 Petri Lehtinen <petri@digip.org>
3  *
4  * Jansson is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13
14 #include <jansson.h>
15 #include "jansson_private.h"
16 #include "strbuffer.h"
17 #include "utf.h"
18
19 #define MAX_INTEGER_STR_LENGTH  100
20 #define MAX_REAL_STR_LENGTH     100
21
22 struct object_key {
23     size_t serial;
24     const char *key;
25 };
26
27 static int dump_to_strbuffer(const char *buffer, size_t size, void *data)
28 {
29     return strbuffer_append_bytes((strbuffer_t *)data, buffer, size);
30 }
31
32 static int dump_to_file(const char *buffer, size_t size, void *data)
33 {
34     FILE *dest = (FILE *)data;
35     if(fwrite(buffer, size, 1, dest) != 1)
36         return -1;
37     return 0;
38 }
39
40 /* 32 spaces (the maximum indentation size) */
41 static char whitespace[] = "                                ";
42
43 static int dump_indent(size_t flags, int depth, int space, json_dump_callback_t dump, void *data)
44 {
45     if(JSON_INDENT(flags) > 0)
46     {
47         int i, ws_count = JSON_INDENT(flags);
48
49         if(dump("\n", 1, data))
50             return -1;
51
52         for(i = 0; i < depth; i++)
53         {
54             if(dump(whitespace, ws_count, data))
55                 return -1;
56         }
57     }
58     else if(space && !(flags & JSON_COMPACT))
59     {
60         return dump(" ", 1, data);
61     }
62     return 0;
63 }
64
65 static int dump_string(const char *str, int ascii, json_dump_callback_t dump, void *data)
66 {
67     const char *pos, *end;
68     int32_t codepoint;
69
70     if(dump("\"", 1, data))
71         return -1;
72
73     end = pos = str;
74     while(1)
75     {
76         const char *text;
77         char seq[13];
78         int length;
79
80         while(*end)
81         {
82             end = utf8_iterate(pos, &codepoint);
83             if(!end)
84                 return -1;
85
86             /* mandatory escape or control char */
87             if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20)
88                 break;
89
90             /* non-ASCII */
91             if(ascii && codepoint > 0x7F)
92                 break;
93
94             pos = end;
95         }
96
97         if(pos != str) {
98             if(dump(str, pos - str, data))
99                 return -1;
100         }
101
102         if(end == pos)
103             break;
104
105         /* handle \, ", and control codes */
106         length = 2;
107         switch(codepoint)
108         {
109             case '\\': text = "\\\\"; break;
110             case '\"': text = "\\\""; break;
111             case '\b': text = "\\b"; break;
112             case '\f': text = "\\f"; break;
113             case '\n': text = "\\n"; break;
114             case '\r': text = "\\r"; break;
115             case '\t': text = "\\t"; break;
116             default:
117             {
118                 /* codepoint is in BMP */
119                 if(codepoint < 0x10000)
120                 {
121                     sprintf(seq, "\\u%04x", codepoint);
122                     length = 6;
123                 }
124
125                 /* not in BMP -> construct a UTF-16 surrogate pair */
126                 else
127                 {
128                     int32_t first, last;
129
130                     codepoint -= 0x10000;
131                     first = 0xD800 | ((codepoint & 0xffc00) >> 10);
132                     last = 0xDC00 | (codepoint & 0x003ff);
133
134                     sprintf(seq, "\\u%04x\\u%04x", first, last);
135                     length = 12;
136                 }
137
138                 text = seq;
139                 break;
140             }
141         }
142
143         if(dump(text, length, data))
144             return -1;
145
146         str = pos = end;
147     }
148
149     return dump("\"", 1, data);
150 }
151
152 static int object_key_compare_keys(const void *key1, const void *key2)
153 {
154     return strcmp(((const struct object_key *)key1)->key,
155                   ((const struct object_key *)key2)->key);
156 }
157
158 static int object_key_compare_serials(const void *key1, const void *key2)
159 {
160     size_t a = ((const struct object_key *)key1)->serial;
161     size_t b = ((const struct object_key *)key2)->serial;
162
163     return a < b ? -1 : a == b ? 0 : 1;
164 }
165
166 static int do_dump(const json_t *json, size_t flags, int depth,
167                    json_dump_callback_t dump, void *data)
168 {
169     int ascii = flags & JSON_ENSURE_ASCII ? 1 : 0;
170
171     switch(json_typeof(json)) {
172         case JSON_NULL:
173             return dump("null", 4, data);
174
175         case JSON_TRUE:
176             return dump("true", 4, data);
177
178         case JSON_FALSE:
179             return dump("false", 5, data);
180
181         case JSON_INTEGER:
182         {
183             char buffer[MAX_INTEGER_STR_LENGTH];
184             int size;
185
186             size = snprintf(buffer, MAX_INTEGER_STR_LENGTH,
187                             "%" JSON_INTEGER_FORMAT,
188                             json_integer_value(json));
189             if(size >= MAX_INTEGER_STR_LENGTH)
190                 return -1;
191
192             return dump(buffer, size, data);
193         }
194
195         case JSON_REAL:
196         {
197             char buffer[MAX_REAL_STR_LENGTH];
198             int size;
199             double value = json_real_value(json);
200
201             size = jsonp_dtostr(buffer, MAX_REAL_STR_LENGTH, value);
202             if(size < 0)
203                 return -1;
204
205             return dump(buffer, size, data);
206         }
207
208         case JSON_STRING:
209             return dump_string(json_string_value(json), ascii, dump, data);
210
211         case JSON_ARRAY:
212         {
213             int i;
214             int n;
215             json_array_t *array;
216
217             /* detect circular references */
218             array = json_to_array(json);
219             if(array->visited)
220                 goto array_error;
221             array->visited = 1;
222
223             n = json_array_size(json);
224
225             if(dump("[", 1, data))
226                 goto array_error;
227             if(n == 0) {
228                 array->visited = 0;
229                 return dump("]", 1, data);
230             }
231             if(dump_indent(flags, depth + 1, 0, dump, data))
232                 goto array_error;
233
234             for(i = 0; i < n; ++i) {
235                 if(do_dump(json_array_get(json, i), flags, depth + 1,
236                            dump, data))
237                     goto array_error;
238
239                 if(i < n - 1)
240                 {
241                     if(dump(",", 1, data) ||
242                        dump_indent(flags, depth + 1, 1, dump, data))
243                         goto array_error;
244                 }
245                 else
246                 {
247                     if(dump_indent(flags, depth, 0, dump, data))
248                         goto array_error;
249                 }
250             }
251
252             array->visited = 0;
253             return dump("]", 1, data);
254
255         array_error:
256             array->visited = 0;
257             return -1;
258         }
259
260         case JSON_OBJECT:
261         {
262             json_object_t *object;
263             void *iter;
264             const char *separator;
265             int separator_length;
266
267             if(flags & JSON_COMPACT) {
268                 separator = ":";
269                 separator_length = 1;
270             }
271             else {
272                 separator = ": ";
273                 separator_length = 2;
274             }
275
276             /* detect circular references */
277             object = json_to_object(json);
278             if(object->visited)
279                 goto object_error;
280             object->visited = 1;
281
282             iter = json_object_iter((json_t *)json);
283
284             if(dump("{", 1, data))
285                 goto object_error;
286             if(!iter) {
287                 object->visited = 0;
288                 return dump("}", 1, data);
289             }
290             if(dump_indent(flags, depth + 1, 0, dump, data))
291                 goto object_error;
292
293             if(flags & JSON_SORT_KEYS || flags & JSON_PRESERVE_ORDER)
294             {
295                 struct object_key *keys;
296                 size_t size, i;
297                 int (*cmp_func)(const void *, const void *);
298
299                 size = json_object_size(json);
300                 keys = jsonp_malloc(size * sizeof(struct object_key));
301                 if(!keys)
302                     goto object_error;
303
304                 i = 0;
305                 while(iter)
306                 {
307                     keys[i].serial = hashtable_iter_serial(iter);
308                     keys[i].key = json_object_iter_key(iter);
309                     iter = json_object_iter_next((json_t *)json, iter);
310                     i++;
311                 }
312                 assert(i == size);
313
314                 if(flags & JSON_SORT_KEYS)
315                     cmp_func = object_key_compare_keys;
316                 else
317                     cmp_func = object_key_compare_serials;
318
319                 qsort(keys, size, sizeof(struct object_key), cmp_func);
320
321                 for(i = 0; i < size; i++)
322                 {
323                     const char *key;
324                     json_t *value;
325
326                     key = keys[i].key;
327                     value = json_object_get(json, key);
328                     assert(value);
329
330                     dump_string(key, ascii, dump, data);
331                     if(dump(separator, separator_length, data) ||
332                        do_dump(value, flags, depth + 1, dump, data))
333                     {
334                         jsonp_free(keys);
335                         goto object_error;
336                     }
337
338                     if(i < size - 1)
339                     {
340                         if(dump(",", 1, data) ||
341                            dump_indent(flags, depth + 1, 1, dump, data))
342                         {
343                             jsonp_free(keys);
344                             goto object_error;
345                         }
346                     }
347                     else
348                     {
349                         if(dump_indent(flags, depth, 0, dump, data))
350                         {
351                             jsonp_free(keys);
352                             goto object_error;
353                         }
354                     }
355                 }
356
357                 jsonp_free(keys);
358             }
359             else
360             {
361                 /* Don't sort keys */
362
363                 while(iter)
364                 {
365                     void *next = json_object_iter_next((json_t *)json, iter);
366
367                     dump_string(json_object_iter_key(iter), ascii, dump, data);
368                     if(dump(separator, separator_length, data) ||
369                        do_dump(json_object_iter_value(iter), flags, depth + 1,
370                                dump, data))
371                         goto object_error;
372
373                     if(next)
374                     {
375                         if(dump(",", 1, data) ||
376                            dump_indent(flags, depth + 1, 1, dump, data))
377                             goto object_error;
378                     }
379                     else
380                     {
381                         if(dump_indent(flags, depth, 0, dump, data))
382                             goto object_error;
383                     }
384
385                     iter = next;
386                 }
387             }
388
389             object->visited = 0;
390             return dump("}", 1, data);
391
392         object_error:
393             object->visited = 0;
394             return -1;
395         }
396
397         default:
398             /* not reached */
399             return -1;
400     }
401 }
402
403 char *json_dumps(const json_t *json, size_t flags)
404 {
405     strbuffer_t strbuff;
406     char *result;
407
408     if(strbuffer_init(&strbuff))
409         return NULL;
410
411     if(json_dump_callback(json, dump_to_strbuffer, (void *)&strbuff, flags))
412         result = NULL;
413     else
414         result = jsonp_strdup(strbuffer_value(&strbuff));
415
416     strbuffer_close(&strbuff);
417     return result;
418 }
419
420 int json_dumpf(const json_t *json, FILE *output, size_t flags)
421 {
422     return json_dump_callback(json, dump_to_file, (void *)output, flags);
423 }
424
425 int json_dump_file(const json_t *json, const char *path, size_t flags)
426 {
427     int result;
428
429     FILE *output = fopen(path, "w");
430     if(!output)
431         return -1;
432
433     result = json_dumpf(json, output, flags);
434
435     fclose(output);
436     return result;
437 }
438
439 int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data, size_t flags)
440 {
441     if(!(flags & JSON_ENCODE_ANY)) {
442         if(!json_is_array(json) && !json_is_object(json))
443            return -1;
444     }
445
446     return do_dump(json, flags, 0, callback, data);
447 }