blob: 441a9e6ef0f97b061cb84ad669887564353ceeb1 [file] [log] [blame]
Luiz Capitulino66f70482009-08-28 15:27:06 -03001/*
2 * QString data type.
3 *
4 * Copyright (C) 2009 Red Hat Inc.
5 *
6 * Authors:
7 * Luiz Capitulino <lcapitulino@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 */
12#include "qobject.h"
13#include "qstring.h"
14#include "qemu-common.h"
15
Blue Swirlaa43d9c2009-09-04 17:43:37 +000016static void qstring_destroy_obj(QObject *obj);
17
18static const QType qstring_type = {
19 .code = QTYPE_QSTRING,
20 .destroy = qstring_destroy_obj,
21};
Luiz Capitulino66f70482009-08-28 15:27:06 -030022
23/**
Anthony Liguorid30ec842009-11-11 10:49:51 -060024 * qstring_new(): Create a new empty QString
25 *
26 * Return strong reference.
27 */
28QString *qstring_new(void)
29{
30 return qstring_from_str("");
31}
32
33/**
Luiz Capitulino66f70482009-08-28 15:27:06 -030034 * qstring_from_str(): Create a new QString from a regular C string
35 *
36 * Return strong reference.
37 */
38QString *qstring_from_str(const char *str)
39{
40 QString *qstring;
41
42 qstring = qemu_malloc(sizeof(*qstring));
Anthony Liguorid30ec842009-11-11 10:49:51 -060043
44 qstring->length = strlen(str);
45 qstring->capacity = qstring->length;
46
47 qstring->string = qemu_malloc(qstring->capacity + 1);
48 memcpy(qstring->string, str, qstring->length);
49 qstring->string[qstring->length] = 0;
50
Luiz Capitulino66f70482009-08-28 15:27:06 -030051 QOBJECT_INIT(qstring, &qstring_type);
52
53 return qstring;
54}
55
Anthony Liguorid30ec842009-11-11 10:49:51 -060056/* qstring_append(): Append a C string to a QString
57 */
58void qstring_append(QString *qstring, const char *str)
59{
60 size_t len = strlen(str);
61
62 if (qstring->capacity < (qstring->length + len)) {
63 qstring->capacity += len;
64 qstring->capacity *= 2; /* use exponential growth */
65
66 qstring->string = qemu_realloc(qstring->string, qstring->capacity + 1);
67 }
68
69 memcpy(qstring->string + qstring->length, str, len);
70 qstring->length += len;
71 qstring->string[qstring->length] = 0;
72}
73
Luiz Capitulino66f70482009-08-28 15:27:06 -030074/**
75 * qobject_to_qstring(): Convert a QObject to a QString
76 */
77QString *qobject_to_qstring(const QObject *obj)
78{
79 if (qobject_type(obj) != QTYPE_QSTRING)
80 return NULL;
81
82 return container_of(obj, QString, base);
83}
84
85/**
86 * qstring_get_str(): Return a pointer to the stored string
87 *
88 * NOTE: Should be used with caution, if the object is deallocated
89 * this pointer becomes invalid.
90 */
91const char *qstring_get_str(const QString *qstring)
92{
93 return qstring->string;
94}
95
96/**
97 * qstring_destroy_obj(): Free all memory allocated by a QString
98 * object
99 */
100static void qstring_destroy_obj(QObject *obj)
101{
102 QString *qs;
103
104 assert(obj != NULL);
105 qs = qobject_to_qstring(obj);
106 qemu_free(qs->string);
107 qemu_free(qs);
108}