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