1
2
3
4
5
6
7
8
9
10
11
12
13#include "qapi/qmp/qobject.h"
14#include "qapi/qmp/qstring.h"
15#include "qemu-common.h"
16
17static void qstring_destroy_obj(QObject *obj);
18
19static const QType qstring_type = {
20 .code = QTYPE_QSTRING,
21 .destroy = qstring_destroy_obj,
22};
23
24
25
26
27
28
29QString *qstring_new(void)
30{
31 return qstring_from_str("");
32}
33
34
35
36
37size_t qstring_get_length(const QString *qstring)
38{
39 return qstring->length;
40}
41
42
43
44
45
46
47QString *qstring_from_substr(const char *str, int start, int end)
48{
49 QString *qstring;
50
51 qstring = g_malloc(sizeof(*qstring));
52
53 qstring->length = end - start + 1;
54 qstring->capacity = qstring->length;
55
56 qstring->string = g_malloc(qstring->capacity + 1);
57 memcpy(qstring->string, str + start, qstring->length);
58 qstring->string[qstring->length] = 0;
59
60 QOBJECT_INIT(qstring, &qstring_type);
61
62 return qstring;
63}
64
65
66
67
68
69
70QString *qstring_from_str(const char *str)
71{
72 return qstring_from_substr(str, 0, strlen(str) - 1);
73}
74
75static void capacity_increase(QString *qstring, size_t len)
76{
77 if (qstring->capacity < (qstring->length + len)) {
78 qstring->capacity += len;
79 qstring->capacity *= 2;
80
81 qstring->string = g_realloc(qstring->string, qstring->capacity + 1);
82 }
83}
84
85
86
87void qstring_append(QString *qstring, const char *str)
88{
89 size_t len = strlen(str);
90
91 capacity_increase(qstring, len);
92 memcpy(qstring->string + qstring->length, str, len);
93 qstring->length += len;
94 qstring->string[qstring->length] = 0;
95}
96
97void qstring_append_int(QString *qstring, int64_t value)
98{
99 char num[32];
100
101 snprintf(num, sizeof(num), "%" PRId64, value);
102 qstring_append(qstring, num);
103}
104
105
106
107
108void qstring_append_chr(QString *qstring, int c)
109{
110 capacity_increase(qstring, 1);
111 qstring->string[qstring->length++] = c;
112 qstring->string[qstring->length] = 0;
113}
114
115
116
117
118QString *qobject_to_qstring(const QObject *obj)
119{
120 if (qobject_type(obj) != QTYPE_QSTRING)
121 return NULL;
122
123 return container_of(obj, QString, base);
124}
125
126
127
128
129
130
131
132const char *qstring_get_str(const QString *qstring)
133{
134 return qstring->string;
135}
136
137
138
139
140
141static void qstring_destroy_obj(QObject *obj)
142{
143 QString *qs;
144
145 assert(obj != NULL);
146 qs = qobject_to_qstring(obj);
147 g_free(qs->string);
148 g_free(qs);
149}
150