4 * Copyright (C) 2009 Red Hat Inc.
7 * Luiz Capitulino <lcapitulino@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
14 #include "qemu-common.h"
16 static void qstring_destroy_obj(QObject
*obj
);
18 static const QType qstring_type
= {
19 .code
= QTYPE_QSTRING
,
20 .destroy
= qstring_destroy_obj
,
24 * qstring_new(): Create a new empty QString
26 * Return strong reference.
28 QString
*qstring_new(void)
30 return qstring_from_str("");
34 * qstring_from_str(): Create a new QString from a regular C string
36 * Return strong reference.
38 QString
*qstring_from_str(const char *str
)
42 qstring
= qemu_malloc(sizeof(*qstring
));
44 qstring
->length
= strlen(str
);
45 qstring
->capacity
= qstring
->length
;
47 qstring
->string
= qemu_malloc(qstring
->capacity
+ 1);
48 memcpy(qstring
->string
, str
, qstring
->length
);
49 qstring
->string
[qstring
->length
] = 0;
51 QOBJECT_INIT(qstring
, &qstring_type
);
56 /* qstring_append(): Append a C string to a QString
58 void qstring_append(QString
*qstring
, const char *str
)
60 size_t len
= strlen(str
);
62 if (qstring
->capacity
< (qstring
->length
+ len
)) {
63 qstring
->capacity
+= len
;
64 qstring
->capacity
*= 2; /* use exponential growth */
66 qstring
->string
= qemu_realloc(qstring
->string
, qstring
->capacity
+ 1);
69 memcpy(qstring
->string
+ qstring
->length
, str
, len
);
70 qstring
->length
+= len
;
71 qstring
->string
[qstring
->length
] = 0;
75 * qobject_to_qstring(): Convert a QObject to a QString
77 QString
*qobject_to_qstring(const QObject
*obj
)
79 if (qobject_type(obj
) != QTYPE_QSTRING
)
82 return container_of(obj
, QString
, base
);
86 * qstring_get_str(): Return a pointer to the stored string
88 * NOTE: Should be used with caution, if the object is deallocated
89 * this pointer becomes invalid.
91 const char *qstring_get_str(const QString
*qstring
)
93 return qstring
->string
;
97 * qstring_destroy_obj(): Free all memory allocated by a QString
100 static void qstring_destroy_obj(QObject
*obj
)
105 qs
= qobject_to_qstring(obj
);
106 qemu_free(qs
->string
);