xref: /openbmc/qemu/qobject/qstring.c (revision c6446a1b)
1 /*
2  * QString Module
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 LGPL, version 2.1 or later.
10  * See the COPYING.LIB file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 #include "qapi/qmp/qstring.h"
15 #include "qobject-internal.h"
16 
17 /**
18  * qstring_new(): Create a new empty QString
19  *
20  * Return strong reference.
21  */
22 QString *qstring_new(void)
23 {
24     return qstring_from_str("");
25 }
26 
27 /**
28  * qstring_from_substr(): Create a new QString from a C string substring
29  *
30  * Return string reference
31  */
32 QString *qstring_from_substr(const char *str, size_t start, size_t end)
33 {
34     QString *qstring;
35 
36     assert(start <= end);
37     qstring = g_malloc(sizeof(*qstring));
38     qobject_init(QOBJECT(qstring), QTYPE_QSTRING);
39     qstring->string = g_strndup(str + start, end - start);
40     return qstring;
41 }
42 
43 /**
44  * qstring_from_str(): Create a new QString from a regular C string
45  *
46  * Return strong reference.
47  */
48 QString *qstring_from_str(const char *str)
49 {
50     return qstring_from_substr(str, 0, strlen(str));
51 }
52 
53 /**
54  * qstring_from_gstring(): Convert a GString to a QString
55  *
56  * Return strong reference.
57  */
58 
59 QString *qstring_from_gstring(GString *gstr)
60 {
61     QString *qstring;
62 
63     qstring = g_malloc(sizeof(*qstring));
64     qobject_init(QOBJECT(qstring), QTYPE_QSTRING);
65     qstring->string = g_string_free(gstr, false);
66     return qstring;
67 }
68 
69 
70 /**
71  * qstring_get_str(): Return a pointer to the stored string
72  *
73  * NOTE: Should be used with caution, if the object is deallocated
74  * this pointer becomes invalid.
75  */
76 const char *qstring_get_str(const QString *qstring)
77 {
78     return qstring->string;
79 }
80 
81 /**
82  * qstring_is_equal(): Test whether the two QStrings are equal
83  */
84 bool qstring_is_equal(const QObject *x, const QObject *y)
85 {
86     return !strcmp(qobject_to(QString, x)->string,
87                    qobject_to(QString, y)->string);
88 }
89 
90 /**
91  * qstring_destroy_obj(): Free all memory allocated by a QString
92  * object
93  */
94 void qstring_destroy_obj(QObject *obj)
95 {
96     QString *qs;
97 
98     assert(obj != NULL);
99     qs = qobject_to(QString, obj);
100     g_free((char *)qs->string);
101     g_free(qs);
102 }
103