Implement JSON_ENSURE_ASCII encoding flag
[jansson.git] / src / dump.c
1 /*
2  * Copyright (c) 2009 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 <stdint.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 do_dump(const json_t *json, unsigned long flags, int depth,
157                    dump_func dump, void *data)
158 {
159     int ascii = flags & JSON_ENSURE_ASCII ? 1 : 0;
160
161     switch(json_typeof(json)) {
162         case JSON_NULL:
163             return dump("null", 4, data);
164
165         case JSON_TRUE:
166             return dump("true", 4, data);
167
168         case JSON_FALSE:
169             return dump("false", 5, data);
170
171         case JSON_INTEGER:
172         {
173             char buffer[MAX_INTEGER_STR_LENGTH];
174             int size;
175
176             size = snprintf(buffer, MAX_INTEGER_STR_LENGTH, "%d", json_integer_value(json));
177             if(size >= MAX_INTEGER_STR_LENGTH)
178                 return -1;
179
180             return dump(buffer, size, data);
181         }
182
183         case JSON_REAL:
184         {
185             char buffer[MAX_REAL_STR_LENGTH];
186             int size;
187
188             size = snprintf(buffer, MAX_REAL_STR_LENGTH, "%0.17f", json_real_value(json));
189             if(size >= MAX_REAL_STR_LENGTH)
190                 return -1;
191
192             return dump(buffer, size, data);
193         }
194
195         case JSON_STRING:
196             return dump_string(json_string_value(json), ascii, dump, data);
197
198         case JSON_ARRAY:
199         {
200             int i;
201             int n;
202             json_array_t *array;
203
204             /* detect circular references */
205             array = json_to_array(json);
206             if(array->visited)
207                 return -1;
208             array->visited = 1;
209
210             n = json_array_size(json);
211
212             if(dump("[", 1, data))
213                 return -1;
214             if(n == 0)
215                 return dump("]", 1, data);
216             if(dump_indent(flags, depth + 1, 0, dump, data))
217                 return -1;
218
219             for(i = 0; i < n; ++i) {
220                 if(do_dump(json_array_get(json, i), flags, depth + 1,
221                            dump, data))
222                     return -1;
223
224                 if(i < n - 1)
225                 {
226                     if(dump(",", 1, data) ||
227                        dump_indent(flags, depth + 1, 1, dump, data))
228                         return -1;
229                 }
230                 else
231                 {
232                     if(dump_indent(flags, depth, 0, dump, data))
233                         return -1;
234                 }
235             }
236
237             array->visited = 0;
238             return dump("]", 1, data);
239         }
240
241         case JSON_OBJECT:
242         {
243             json_object_t *object;
244             void *iter;
245             const char *separator;
246             int separator_length;
247
248             if(flags & JSON_COMPACT) {
249                 separator = ":";
250                 separator_length = 1;
251             }
252             else {
253                 separator = ": ";
254                 separator_length = 2;
255             }
256
257             /* detect circular references */
258             object = json_to_object(json);
259             if(object->visited)
260                 return -1;
261             object->visited = 1;
262
263             iter = json_object_iter((json_t *)json);
264
265             if(dump("{", 1, data))
266                 return -1;
267             if(!iter)
268                 return dump("}", 1, data);
269             if(dump_indent(flags, depth + 1, 0, dump, data))
270                 return -1;
271
272             while(iter)
273             {
274                 void *next = json_object_iter_next((json_t *)json, iter);
275
276                 dump_string(json_object_iter_key(iter), ascii, dump, data);
277                 if(dump(separator, separator_length, data) ||
278                    do_dump(json_object_iter_value(iter), flags, depth + 1,
279                            dump, data))
280                     return -1;
281
282                 if(next)
283                 {
284                     if(dump(",", 1, data) ||
285                        dump_indent(flags, depth + 1, 1, dump, data))
286                         return -1;
287                 }
288                 else
289                 {
290                     if(dump_indent(flags, depth, 0, dump, data))
291                         return -1;
292                 }
293
294                 iter = next;
295             }
296
297             object->visited = 0;
298             return dump("}", 1, data);
299         }
300
301         default:
302             /* not reached */
303             return -1;
304     }
305 }
306
307
308 char *json_dumps(const json_t *json, unsigned long flags)
309 {
310     strbuffer_t strbuff;
311     char *result;
312
313     if(!json_is_array(json) && !json_is_object(json))
314         return NULL;
315
316     if(strbuffer_init(&strbuff))
317         return NULL;
318
319     if(do_dump(json, flags, 0, dump_to_strbuffer, (void *)&strbuff)) {
320         strbuffer_close(&strbuff);
321         return NULL;
322     }
323
324     result = strdup(strbuffer_value(&strbuff));
325     strbuffer_close(&strbuff);
326
327     return result;
328 }
329
330 int json_dumpf(const json_t *json, FILE *output, unsigned long flags)
331 {
332     if(!json_is_array(json) && !json_is_object(json))
333         return -1;
334
335     return do_dump(json, flags, 0, dump_to_file, (void *)output);
336 }
337
338 int json_dump_file(const json_t *json, const char *path, unsigned long flags)
339 {
340     int result;
341
342     FILE *output = fopen(path, "w");
343     if(!output)
344         return -1;
345
346     result = json_dumpf(json, output, flags);
347
348     fclose(output);
349     return result;
350 }