Make real number encoding and decoding work under all locales
[jansson.git] / test / suites / api / test_dump_callback.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 #include <jansson.h>
9 #include <string.h>
10 #include <stdlib.h>
11 #include "util.h"
12
13 struct my_sink {
14     char *buf;
15     size_t off;
16     size_t cap;
17 };
18
19 static int my_writer(const char *buffer, size_t len, void *data) {
20     struct my_sink *s = data;
21     if (len > s->cap - s->off) {
22         return -1;
23     }
24     memcpy(s->buf + s->off, buffer, len);
25     s->off += len;
26     return 0;
27 }
28
29 static void run_tests()
30 {
31     struct my_sink s;
32     json_t *json;
33     const char str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
34     char *dumped_to_string;
35
36     json = json_loads(str, 0, NULL);
37     if(!json) {
38         fail("json_loads failed");
39     }
40
41     dumped_to_string = json_dumps(json, 0);
42     if (!dumped_to_string) {
43         json_decref(json);
44         fail("json_dumps failed");
45     }
46
47     s.off = 0;
48     s.cap = strlen(dumped_to_string);
49     s.buf = malloc(s.cap);
50     if (!s.buf) {
51         json_decref(json);
52         free(dumped_to_string);
53         fail("malloc failed");
54     }
55
56     if (json_dump_callback(json, my_writer, &s, 0) == -1) {
57         json_decref(json);
58         free(dumped_to_string);
59         free(s.buf);
60         fail("json_dump_callback failed on an exact-length sink buffer");
61     }
62
63     if (strncmp(dumped_to_string, s.buf, s.off) != 0) {
64         json_decref(json);
65         free(dumped_to_string);
66         free(s.buf);
67         fail("json_dump_callback and json_dumps did not produce identical output");
68     }
69
70     s.off = 1;
71     if (json_dump_callback(json, my_writer, &s, 0) != -1) {
72         json_decref(json);
73         free(dumped_to_string);
74         free(s.buf);
75         fail("json_dump_callback succeeded on a short buffer when it should have failed");
76     }
77
78     json_decref(json);
79     free(dumped_to_string);
80     free(s.buf);
81 }