Make real number encoding and decoding work under all locales
[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 string
23 {
24     char *buffer;
25     int length;
26     int size;
27 };
28
29 static int dump_to_strbuffer(const char *buffer, size_t size, void *data)
30 {
31     return strbuffer_append_bytes((strbuffer_t *)data, buffer, size);
32 }
33
34 static int dump_to_file(const char *buffer, size_t size, void *data)
35 {
36     FILE *dest = (FILE *)data;
37     if(fwrite(buffer, size, 1, dest) != 1)
38         return -1;
39     return 0;
40 }
41
42 /* 32 spaces (the maximum indentation size) */
43 static char whitespace[] = "                                ";
44
45 static int dump_indent(size_t flags, int depth, int space, json_dump_callback_t dump, void *data)
46 {
47     if(JSON_INDENT(flags) > 0)
48     {
49         int i, ws_count = JSON_INDENT(flags);
50
51         if(dump("\n", 1, data))
52             return -1;
53
54         for(i = 0; i < depth; i++)
55         {
56             if(dump(whitespace, ws_count, data))
57                 return -1;
58         }
59     }
60     else if(space && !(flags & JSON_COMPACT))
61     {
62         return dump(" ", 1, data);
63     }
64     return 0;
65 }
66
67 static int dump_string(const char *str, int ascii, json_dump_callback_t dump, void *data)
68 {
69     const char *pos, *end;
70     int32_t codepoint;
71
72     if(dump("\"", 1, data))
73         return -1;
74
75     end = pos = str;
76     while(1)
77     {
78         const char *text;
79         char seq[13];
80         int length;
81
82         while(*end)
83         {
84             end = utf8_iterate(pos, &codepoint);
85             if(!end)
86                 return -1;
87
88             /* mandatory escape or control char */
89             if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20)
90                 break;
91
92             /* non-ASCII */
93             if(ascii && codepoint > 0x7F)
94                 break;
95
96             pos = end;
97         }
98
99         if(pos != str) {
100             if(dump(str, pos - str, data))
101                 return -1;
102         }
103
104         if(end == pos)
105             break;
106
107         /* handle \, ", and control codes */
108         length = 2;
109         switch(codepoint)
110         {
111             case '\\': text = "\\\\"; break;
112             case '\"': text = "\\\""; break;
113             case '\b': text = "\\b"; break;
114             case '\f': text = "\\f"; break;
115             case '\n': text = "\\n"; break;
116             case '\r': text = "\\r"; break;
117             case '\t': text = "\\t"; break;
118             default:
119             {
120                 /* codepoint is in BMP */
121                 if(codepoint < 0x10000)
122                 {
123                     sprintf(seq, "\\u%04x", codepoint);
124                     length = 6;
125                 }
126
127                 /* not in BMP -> construct a UTF-16 surrogate pair */
128                 else
129                 {
130                     int32_t first, last;
131
132                     codepoint -= 0x10000;
133                     first = 0xD800 | ((codepoint & 0xffc00) >> 10);
134                     last = 0xDC00 | (codepoint & 0x003ff);
135
136                     sprintf(seq, "\\u%04x\\u%04x", first, last);
137                     length = 12;
138                 }
139
140                 text = seq;
141                 break;
142             }
143         }
144
145         if(dump(text, length, data))
146             return -1;
147
148         str = pos = end;
149     }
150
151     return dump("\"", 1, data);
152 }
153
154 static int object_key_compare_keys(const void *key1, const void *key2)
155 {
156     return strcmp((*(const object_key_t **)key1)->key,
157                   (*(const object_key_t **)key2)->key);
158 }
159
160 static int object_key_compare_serials(const void *key1, const void *key2)
161 {
162     return (*(const object_key_t **)key1)->serial -
163            (*(const object_key_t **)key2)->serial;
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                 const object_key_t **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(object_key_t *));
301                 if(!keys)
302                     goto object_error;
303
304                 i = 0;
305                 while(iter)
306                 {
307                     keys[i] = jsonp_object_iter_fullkey(iter);
308                     iter = json_object_iter_next((json_t *)json, iter);
309                     i++;
310                 }
311                 assert(i == size);
312
313                 if(flags & JSON_SORT_KEYS)
314                     cmp_func = object_key_compare_keys;
315                 else
316                     cmp_func = object_key_compare_serials;
317
318                 qsort(keys, size, sizeof(object_key_t *), cmp_func);
319
320                 for(i = 0; i < size; i++)
321                 {
322                     const char *key;
323                     json_t *value;
324
325                     key = keys[i]->key;
326                     value = json_object_get(json, key);
327                     assert(value);
328
329                     dump_string(key, ascii, dump, data);
330                     if(dump(separator, separator_length, data) ||
331                        do_dump(value, flags, depth + 1, dump, data))
332                     {
333                         jsonp_free(keys);
334                         goto object_error;
335                     }
336
337                     if(i < size - 1)
338                     {
339                         if(dump(",", 1, data) ||
340                            dump_indent(flags, depth + 1, 1, dump, data))
341                         {
342                             jsonp_free(keys);
343                             goto object_error;
344                         }
345                     }
346                     else
347                     {
348                         if(dump_indent(flags, depth, 0, dump, data))
349                         {
350                             jsonp_free(keys);
351                             goto object_error;
352                         }
353                     }
354                 }
355
356                 jsonp_free(keys);
357             }
358             else
359             {
360                 /* Don't sort keys */
361
362                 while(iter)
363                 {
364                     void *next = json_object_iter_next((json_t *)json, iter);
365
366                     dump_string(json_object_iter_key(iter), ascii, dump, data);
367                     if(dump(separator, separator_length, data) ||
368                        do_dump(json_object_iter_value(iter), flags, depth + 1,
369                                dump, data))
370                         goto object_error;
371
372                     if(next)
373                     {
374                         if(dump(",", 1, data) ||
375                            dump_indent(flags, depth + 1, 1, dump, data))
376                             goto object_error;
377                     }
378                     else
379                     {
380                         if(dump_indent(flags, depth, 0, dump, data))
381                             goto object_error;
382                     }
383
384                     iter = next;
385                 }
386             }
387
388             object->visited = 0;
389             return dump("}", 1, data);
390
391         object_error:
392             object->visited = 0;
393             return -1;
394         }
395
396         default:
397             /* not reached */
398             return -1;
399     }
400 }
401
402 char *json_dumps(const json_t *json, size_t flags)
403 {
404     strbuffer_t strbuff;
405     char *result;
406
407     if(strbuffer_init(&strbuff))
408         return NULL;
409
410     if(json_dump_callback(json, dump_to_strbuffer, (void *)&strbuff, flags))
411         result = NULL;
412     else
413         result = jsonp_strdup(strbuffer_value(&strbuff));
414
415     strbuffer_close(&strbuff);
416     return result;
417 }
418
419 int json_dumpf(const json_t *json, FILE *output, size_t flags)
420 {
421     return json_dump_callback(json, dump_to_file, (void *)output, flags);
422 }
423
424 int json_dump_file(const json_t *json, const char *path, size_t flags)
425 {
426     int result;
427
428     FILE *output = fopen(path, "w");
429     if(!output)
430         return -1;
431
432     result = json_dumpf(json, output, flags);
433
434     fclose(output);
435     return result;
436 }
437
438 int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data, size_t flags)
439 {
440     if(!(flags & JSON_ENCODE_ANY)) {
441         if(!json_is_array(json) && !json_is_object(json))
442            return -1;
443     }
444
445     return do_dump(json, flags, 0, callback, data);
446 }