]> git.proxmox.com Git - mirror_qemu.git/blame - qjson.c
docs/atomics.txt: fix two typos
[mirror_qemu.git] / qjson.c
CommitLineData
190c882c
AG
1/*
2 * QEMU JSON writer
3 *
4 * Copyright Alexander Graf
5 *
6 * Authors:
559782cc 7 * Alexander Graf <agraf@suse.de>
190c882c
AG
8 *
9 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
10 * See the COPYING.LIB file in the top-level directory.
11 *
12 */
13
14#include <qapi/qmp/qstring.h>
15#include <stdbool.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
27static void json_emit_element(QJSON *json, const char *name)
28{
29 /* Check whether we need to print a , before an element */
30 if (json->omit_comma) {
31 json->omit_comma = false;
32 } else {
33 qstring_append(json->str, ", ");
34 }
35
36 if (name) {
37 qstring_append(json->str, "\"");
38 qstring_append(json->str, name);
39 qstring_append(json->str, "\" : ");
40 }
41}
42
43void json_start_object(QJSON *json, const char *name)
44{
45 json_emit_element(json, name);
46 qstring_append(json->str, "{ ");
47 json->omit_comma = true;
48}
49
50void json_end_object(QJSON *json)
51{
52 qstring_append(json->str, " }");
53 json->omit_comma = false;
54}
55
56void json_start_array(QJSON *json, const char *name)
57{
58 json_emit_element(json, name);
59 qstring_append(json->str, "[ ");
60 json->omit_comma = true;
61}
62
63void json_end_array(QJSON *json)
64{
65 qstring_append(json->str, " ]");
66 json->omit_comma = false;
67}
68
69void json_prop_int(QJSON *json, const char *name, int64_t val)
70{
71 json_emit_element(json, name);
72 qstring_append_int(json->str, val);
73}
74
75void json_prop_str(QJSON *json, const char *name, const char *str)
76{
77 json_emit_element(json, name);
78 qstring_append_chr(json->str, '"');
79 qstring_append(json->str, str);
80 qstring_append_chr(json->str, '"');
81}
82
83const char *qjson_get_str(QJSON *json)
84{
85 return qstring_get_str(json->str);
86}
87
88QJSON *qjson_new(void)
89{
90 QJSON *json = (QJSON *)object_new(TYPE_QJSON);
91 return json;
92}
93
94void qjson_finish(QJSON *json)
95{
96 json_end_object(json);
97}
98
99static void qjson_initfn(Object *obj)
100{
101 QJSON *json = (QJSON *)object_dynamic_cast(obj, TYPE_QJSON);
102 assert(json);
103
104 json->str = qstring_from_str("{ ");
105 json->omit_comma = true;
106}
107
108static void qjson_finalizefn(Object *obj)
109{
110 QJSON *json = (QJSON *)object_dynamic_cast(obj, TYPE_QJSON);
111
112 assert(json);
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)