1
2
3
4
5
6
7
8
9
10
11
12
13
14#include "qemu/osdep.h"
15#include <qapi/qmp/qstring.h>
16#include <glib.h>
17#include <qjson.h>
18#include <qemu/module.h>
19#include <qom/object.h>
20
21struct QJSON {
22 Object obj;
23 QString *str;
24 bool omit_comma;
25};
26
27#define QJSON(obj) OBJECT_CHECK(QJSON, (obj), TYPE_QJSON)
28
29static void json_emit_element(QJSON *json, const char *name)
30{
31
32 if (json->omit_comma) {
33 json->omit_comma = false;
34 } else {
35 qstring_append(json->str, ", ");
36 }
37
38 if (name) {
39 qstring_append(json->str, "\"");
40 qstring_append(json->str, name);
41 qstring_append(json->str, "\" : ");
42 }
43}
44
45void json_start_object(QJSON *json, const char *name)
46{
47 json_emit_element(json, name);
48 qstring_append(json->str, "{ ");
49 json->omit_comma = true;
50}
51
52void json_end_object(QJSON *json)
53{
54 qstring_append(json->str, " }");
55 json->omit_comma = false;
56}
57
58void json_start_array(QJSON *json, const char *name)
59{
60 json_emit_element(json, name);
61 qstring_append(json->str, "[ ");
62 json->omit_comma = true;
63}
64
65void json_end_array(QJSON *json)
66{
67 qstring_append(json->str, " ]");
68 json->omit_comma = false;
69}
70
71void json_prop_int(QJSON *json, const char *name, int64_t val)
72{
73 json_emit_element(json, name);
74 qstring_append_int(json->str, val);
75}
76
77void json_prop_str(QJSON *json, const char *name, const char *str)
78{
79 json_emit_element(json, name);
80 qstring_append_chr(json->str, '"');
81 qstring_append(json->str, str);
82 qstring_append_chr(json->str, '"');
83}
84
85const char *qjson_get_str(QJSON *json)
86{
87 return qstring_get_str(json->str);
88}
89
90QJSON *qjson_new(void)
91{
92 QJSON *json = QJSON(object_new(TYPE_QJSON));
93 return json;
94}
95
96void qjson_finish(QJSON *json)
97{
98 json_end_object(json);
99}
100
101static void qjson_initfn(Object *obj)
102{
103 QJSON *json = QJSON(obj);
104
105 json->str = qstring_from_str("{ ");
106 json->omit_comma = true;
107}
108
109static void qjson_finalizefn(Object *obj)
110{
111 QJSON *json = QJSON(obj);
112
113 qobject_decref(QOBJECT(json->str));
114}
115
116static const TypeInfo qjson_type_info = {
117 .name = TYPE_QJSON,
118 .parent = TYPE_OBJECT,
119 .instance_size = sizeof(QJSON),
120 .instance_init = qjson_initfn,
121 .instance_finalize = qjson_finalizefn,
122};
123
124static void qjson_register_types(void)
125{
126 type_register_static(&qjson_type_info);
127}
128
129type_init(qjson_register_types)
130