4 * Copyright (C) 2009 Red Hat Inc.
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.
13 #include "qapi/qmp/qlist.h"
14 #include "qapi/qmp/qobject.h"
15 #include "qemu/queue.h"
16 #include "qemu-common.h"
19 * qlist_new(): Create a new QList
21 * Return strong reference.
23 QList *qlist_new(void)
27 qlist = g_malloc(sizeof(*qlist));
28 qobject_init(QOBJECT(qlist), QTYPE_QLIST);
29 QTAILQ_INIT(&qlist->head);
34 static void qlist_copy_elem(QObject *obj, void *opaque)
39 qlist_append_obj(dst, obj);
42 QList *qlist_copy(QList *src)
44 QList *dst = qlist_new();
46 qlist_iter(src, qlist_copy_elem, dst);
52 * qlist_append_obj(): Append an QObject into QList
54 * NOTE: ownership of 'value' is transferred to the QList
56 void qlist_append_obj(QList *qlist, QObject *value)
60 entry = g_malloc(sizeof(*entry));
63 QTAILQ_INSERT_TAIL(&qlist->head, entry, next);
67 * qlist_iter(): Iterate over all the list's stored values.
69 * This function allows the user to provide an iterator, which will be
70 * called for each stored value in the list.
72 void qlist_iter(const QList *qlist,
73 void (*iter)(QObject *obj, void *opaque), void *opaque)
77 QTAILQ_FOREACH(entry, &qlist->head, next)
78 iter(entry->value, opaque);
81 QObject *qlist_pop(QList *qlist)
86 if (qlist == NULL || QTAILQ_EMPTY(&qlist->head)) {
90 entry = QTAILQ_FIRST(&qlist->head);
91 QTAILQ_REMOVE(&qlist->head, entry, next);
99 QObject *qlist_peek(QList *qlist)
104 if (qlist == NULL || QTAILQ_EMPTY(&qlist->head)) {
108 entry = QTAILQ_FIRST(&qlist->head);
115 int qlist_empty(const QList *qlist)
117 return QTAILQ_EMPTY(&qlist->head);
120 static void qlist_size_iter(QObject *obj, void *opaque)
122 size_t *count = opaque;
126 size_t qlist_size(const QList *qlist)
129 qlist_iter(qlist, qlist_size_iter, &count);
134 * qobject_to_qlist(): Convert a QObject into a QList
136 QList *qobject_to_qlist(const QObject *obj)
138 if (!obj || qobject_type(obj) != QTYPE_QLIST) {
141 return container_of(obj, QList, base);
145 * qlist_destroy_obj(): Free all the memory allocated by a QList
147 void qlist_destroy_obj(QObject *obj)
150 QListEntry *entry, *next_entry;
153 qlist = qobject_to_qlist(obj);
155 QTAILQ_FOREACH_SAFE(entry, &qlist->head, next, next_entry) {
156 QTAILQ_REMOVE(&qlist->head, entry, next);
157 qobject_decref(entry->value);