]> mj.ucw.cz Git - libucw.git/blob - ucw-json/json-test.c
JSON: Tests and bug fixes
[libucw.git] / ucw-json / json-test.c
1 /*
2  *      UCW JSON Library -- Tests
3  *
4  *      (c) 2015 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/fastbuf.h>
12 #include <ucw/fw-hex.h>
13 #include <ucw/opt.h>
14 #include <ucw/trans.h>
15 #include <ucw-json/json.h>
16
17 static int opt_read;
18 static int opt_write;
19 static int opt_escape;
20 static int opt_indent;
21 static int opt_read_hex;
22 static int opt_write_hex;
23
24 static struct opt_section options = {
25   OPT_ITEMS {
26     OPT_HELP("Test program for UCW JSON library."),
27     OPT_HELP("Usage: json-test [options]"),
28     OPT_HELP(""),
29     OPT_HELP("Options:"),
30     OPT_HELP_OPTION,
31     OPT_BOOL('r', "read", opt_read, 0, "\tRead JSON from standard input"),
32     OPT_BOOL('R', "read-hex", opt_read_hex, 0, "\tRead JSON, interpreting <XY> as hex escapes"),
33     OPT_BOOL('w', "write", opt_write, 0, "\tWrite JSON to standard output"),
34     OPT_BOOL('W', "write-hex", opt_write_hex, 0, "\tWrite JSON, print non-ASCII as hex escapes"),
35     OPT_BOOL('e', "escape", opt_escape, 0, "\tEscape non-ASCII characters in strings"),
36     OPT_BOOL('i', "indent", opt_indent, 0, "\tIndent output"),
37     OPT_END
38   }
39 };
40
41 static struct json_node *do_parse(struct json_context *js, struct fastbuf *fb)
42 {
43   struct json_node *n;
44   TRANS_TRY
45     {
46       n = json_parse(js, fb);
47     }
48   TRANS_CATCH(x)
49     {
50       fprintf(stderr, "ERROR: %s\n", x->msg);
51       exit(1);
52     }
53   TRANS_END;
54   return n;
55 }
56
57 int main(int argc UNUSED, char **argv)
58 {
59   opt_parse(&options, argv+1);
60
61   struct json_context *js = json_new();
62   struct json_node *n = NULL;
63
64   if (opt_escape)
65     js->format_options |= JSON_FORMAT_ESCAPE_NONASCII;
66   if (opt_indent)
67     js->format_options |= JSON_FORMAT_INDENT;
68
69   if (opt_read || opt_read_hex)
70     {
71       struct fastbuf *fb = bfdopen_shared(0, 65536);
72       if (opt_read_hex)
73         fb = fb_wrap_hex_in(fb);
74       n = do_parse(js, fb);
75       bclose(fb);
76     }
77
78   if (!n)
79     n = json_new_number(js, 42);
80
81   if (opt_write || opt_write_hex)
82     {
83       struct fastbuf *fb = bfdopen_shared(1, 65536);
84       if (opt_write_hex)
85         fb = fb_wrap_hex_out(fb);
86       json_write(js, fb, n);
87       bclose(fb);
88     }
89
90   json_delete(js);
91   return 0;
92 }