qdict: Make conversion from QObject * accept null
[qemu/ar7.git] / qobject / qdict.c
blob6b322850dcf3a6c137738889b8526a348cf309fc
1 /*
2 * QDict Module
4 * Copyright (C) 2009 Red Hat Inc.
6 * Authors:
7 * Luiz Capitulino <lcapitulino@redhat.com>
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/qint.h"
14 #include "qapi/qmp/qfloat.h"
15 #include "qapi/qmp/qdict.h"
16 #include "qapi/qmp/qbool.h"
17 #include "qapi/qmp/qstring.h"
18 #include "qapi/qmp/qobject.h"
19 #include "qemu/queue.h"
20 #include "qemu-common.h"
22 static void qdict_destroy_obj(QObject *obj);
24 static const QType qdict_type = {
25 .code = QTYPE_QDICT,
26 .destroy = qdict_destroy_obj,
29 /**
30 * qdict_new(): Create a new QDict
32 * Return strong reference.
34 QDict *qdict_new(void)
36 QDict *qdict;
38 qdict = g_malloc0(sizeof(*qdict));
39 QOBJECT_INIT(qdict, &qdict_type);
41 return qdict;
44 /**
45 * qobject_to_qdict(): Convert a QObject into a QDict
47 QDict *qobject_to_qdict(const QObject *obj)
49 if (!obj || qobject_type(obj) != QTYPE_QDICT) {
50 return NULL;
52 return container_of(obj, QDict, base);
55 /**
56 * tdb_hash(): based on the hash agorithm from gdbm, via tdb
57 * (from module-init-tools)
59 static unsigned int tdb_hash(const char *name)
61 unsigned value; /* Used to compute the hash value. */
62 unsigned i; /* Used to cycle through random values. */
64 /* Set the initial value from the key size. */
65 for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
66 value = (value + (((const unsigned char *)name)[i] << (i*5 % 24)));
68 return (1103515243 * value + 12345);
71 /**
72 * alloc_entry(): allocate a new QDictEntry
74 static QDictEntry *alloc_entry(const char *key, QObject *value)
76 QDictEntry *entry;
78 entry = g_malloc0(sizeof(*entry));
79 entry->key = g_strdup(key);
80 entry->value = value;
82 return entry;
85 /**
86 * qdict_entry_value(): Return qdict entry value
88 * Return weak reference.
90 QObject *qdict_entry_value(const QDictEntry *entry)
92 return entry->value;
95 /**
96 * qdict_entry_key(): Return qdict entry key
98 * Return a *pointer* to the string, it has to be duplicated before being
99 * stored.
101 const char *qdict_entry_key(const QDictEntry *entry)
103 return entry->key;
107 * qdict_find(): List lookup function
109 static QDictEntry *qdict_find(const QDict *qdict,
110 const char *key, unsigned int bucket)
112 QDictEntry *entry;
114 QLIST_FOREACH(entry, &qdict->table[bucket], next)
115 if (!strcmp(entry->key, key))
116 return entry;
118 return NULL;
122 * qdict_put_obj(): Put a new QObject into the dictionary
124 * Insert the pair 'key:value' into 'qdict', if 'key' already exists
125 * its 'value' will be replaced.
127 * This is done by freeing the reference to the stored QObject and
128 * storing the new one in the same entry.
130 * NOTE: ownership of 'value' is transferred to the QDict
132 void qdict_put_obj(QDict *qdict, const char *key, QObject *value)
134 unsigned int bucket;
135 QDictEntry *entry;
137 bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
138 entry = qdict_find(qdict, key, bucket);
139 if (entry) {
140 /* replace key's value */
141 qobject_decref(entry->value);
142 entry->value = value;
143 } else {
144 /* allocate a new entry */
145 entry = alloc_entry(key, value);
146 QLIST_INSERT_HEAD(&qdict->table[bucket], entry, next);
147 qdict->size++;
152 * qdict_get(): Lookup for a given 'key'
154 * Return a weak reference to the QObject associated with 'key' if
155 * 'key' is present in the dictionary, NULL otherwise.
157 QObject *qdict_get(const QDict *qdict, const char *key)
159 QDictEntry *entry;
161 entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
162 return (entry == NULL ? NULL : entry->value);
166 * qdict_haskey(): Check if 'key' exists
168 * Return 1 if 'key' exists in the dict, 0 otherwise
170 int qdict_haskey(const QDict *qdict, const char *key)
172 unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
173 return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1);
177 * qdict_size(): Return the size of the dictionary
179 size_t qdict_size(const QDict *qdict)
181 return qdict->size;
185 * qdict_get_obj(): Get a QObject of a specific type
187 static QObject *qdict_get_obj(const QDict *qdict, const char *key,
188 qtype_code type)
190 QObject *obj;
192 obj = qdict_get(qdict, key);
193 assert(obj != NULL);
194 assert(qobject_type(obj) == type);
196 return obj;
200 * qdict_get_double(): Get an number mapped by 'key'
202 * This function assumes that 'key' exists and it stores a
203 * QFloat or QInt object.
205 * Return number mapped by 'key'.
207 double qdict_get_double(const QDict *qdict, const char *key)
209 QObject *obj = qdict_get(qdict, key);
211 assert(obj);
212 switch (qobject_type(obj)) {
213 case QTYPE_QFLOAT:
214 return qfloat_get_double(qobject_to_qfloat(obj));
215 case QTYPE_QINT:
216 return qint_get_int(qobject_to_qint(obj));
217 default:
218 abort();
223 * qdict_get_int(): Get an integer mapped by 'key'
225 * This function assumes that 'key' exists and it stores a
226 * QInt object.
228 * Return integer mapped by 'key'.
230 int64_t qdict_get_int(const QDict *qdict, const char *key)
232 QObject *obj = qdict_get_obj(qdict, key, QTYPE_QINT);
233 return qint_get_int(qobject_to_qint(obj));
237 * qdict_get_bool(): Get a bool mapped by 'key'
239 * This function assumes that 'key' exists and it stores a
240 * QBool object.
242 * Return bool mapped by 'key'.
244 bool qdict_get_bool(const QDict *qdict, const char *key)
246 return qbool_get_bool(qobject_to_qbool(qdict_get(qdict, key)));
250 * qdict_get_qlist(): Get the QList mapped by 'key'
252 * This function assumes that 'key' exists and it stores a
253 * QList object.
255 * Return QList mapped by 'key'.
257 QList *qdict_get_qlist(const QDict *qdict, const char *key)
259 return qobject_to_qlist(qdict_get_obj(qdict, key, QTYPE_QLIST));
263 * qdict_get_qdict(): Get the QDict mapped by 'key'
265 * This function assumes that 'key' exists and it stores a
266 * QDict object.
268 * Return QDict mapped by 'key'.
270 QDict *qdict_get_qdict(const QDict *qdict, const char *key)
272 return qobject_to_qdict(qdict_get(qdict, key));
276 * qdict_get_str(): Get a pointer to the stored string mapped
277 * by 'key'
279 * This function assumes that 'key' exists and it stores a
280 * QString object.
282 * Return pointer to the string mapped by 'key'.
284 const char *qdict_get_str(const QDict *qdict, const char *key)
286 QObject *obj = qdict_get_obj(qdict, key, QTYPE_QSTRING);
287 return qstring_get_str(qobject_to_qstring(obj));
291 * qdict_get_try_int(): Try to get integer mapped by 'key'
293 * Return integer mapped by 'key', if it is not present in
294 * the dictionary or if the stored object is not of QInt type
295 * 'def_value' will be returned.
297 int64_t qdict_get_try_int(const QDict *qdict, const char *key,
298 int64_t def_value)
300 QObject *obj;
302 obj = qdict_get(qdict, key);
303 if (!obj || qobject_type(obj) != QTYPE_QINT)
304 return def_value;
306 return qint_get_int(qobject_to_qint(obj));
310 * qdict_get_try_bool(): Try to get a bool mapped by 'key'
312 * Return bool mapped by 'key', if it is not present in the
313 * dictionary or if the stored object is not of QBool type
314 * 'def_value' will be returned.
316 bool qdict_get_try_bool(const QDict *qdict, const char *key, bool def_value)
318 QBool *qbool = qobject_to_qbool(qdict_get(qdict, key));
320 return qbool ? qbool_get_bool(qbool) : def_value;
324 * qdict_get_try_str(): Try to get a pointer to the stored string
325 * mapped by 'key'
327 * Return a pointer to the string mapped by 'key', if it is not present
328 * in the dictionary or if the stored object is not of QString type
329 * NULL will be returned.
331 const char *qdict_get_try_str(const QDict *qdict, const char *key)
333 QObject *obj;
335 obj = qdict_get(qdict, key);
336 if (!obj || qobject_type(obj) != QTYPE_QSTRING)
337 return NULL;
339 return qstring_get_str(qobject_to_qstring(obj));
343 * qdict_iter(): Iterate over all the dictionary's stored values.
345 * This function allows the user to provide an iterator, which will be
346 * called for each stored value in the dictionary.
348 void qdict_iter(const QDict *qdict,
349 void (*iter)(const char *key, QObject *obj, void *opaque),
350 void *opaque)
352 int i;
353 QDictEntry *entry;
355 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
356 QLIST_FOREACH(entry, &qdict->table[i], next)
357 iter(entry->key, entry->value, opaque);
361 static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket)
363 int i;
365 for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) {
366 if (!QLIST_EMPTY(&qdict->table[i])) {
367 return QLIST_FIRST(&qdict->table[i]);
371 return NULL;
375 * qdict_first(): Return first qdict entry for iteration.
377 const QDictEntry *qdict_first(const QDict *qdict)
379 return qdict_next_entry(qdict, 0);
383 * qdict_next(): Return next qdict entry in an iteration.
385 const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry)
387 QDictEntry *ret;
389 ret = QLIST_NEXT(entry, next);
390 if (!ret) {
391 unsigned int bucket = tdb_hash(entry->key) % QDICT_BUCKET_MAX;
392 ret = qdict_next_entry(qdict, bucket + 1);
395 return ret;
399 * qdict_clone_shallow(): Clones a given QDict. Its entries are not copied, but
400 * another reference is added.
402 QDict *qdict_clone_shallow(const QDict *src)
404 QDict *dest;
405 QDictEntry *entry;
406 int i;
408 dest = qdict_new();
410 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
411 QLIST_FOREACH(entry, &src->table[i], next) {
412 qobject_incref(entry->value);
413 qdict_put_obj(dest, entry->key, entry->value);
417 return dest;
421 * qentry_destroy(): Free all the memory allocated by a QDictEntry
423 static void qentry_destroy(QDictEntry *e)
425 assert(e != NULL);
426 assert(e->key != NULL);
427 assert(e->value != NULL);
429 qobject_decref(e->value);
430 g_free(e->key);
431 g_free(e);
435 * qdict_del(): Delete a 'key:value' pair from the dictionary
437 * This will destroy all data allocated by this entry.
439 void qdict_del(QDict *qdict, const char *key)
441 QDictEntry *entry;
443 entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
444 if (entry) {
445 QLIST_REMOVE(entry, next);
446 qentry_destroy(entry);
447 qdict->size--;
452 * qdict_destroy_obj(): Free all the memory allocated by a QDict
454 static void qdict_destroy_obj(QObject *obj)
456 int i;
457 QDict *qdict;
459 assert(obj != NULL);
460 qdict = qobject_to_qdict(obj);
462 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
463 QDictEntry *entry = QLIST_FIRST(&qdict->table[i]);
464 while (entry) {
465 QDictEntry *tmp = QLIST_NEXT(entry, next);
466 QLIST_REMOVE(entry, next);
467 qentry_destroy(entry);
468 entry = tmp;
472 g_free(qdict);
476 * qdict_copy_default(): If no entry mapped by 'key' exists in 'dst' yet, the
477 * value of 'key' in 'src' is copied there (and the refcount increased
478 * accordingly).
480 void qdict_copy_default(QDict *dst, QDict *src, const char *key)
482 QObject *val;
484 if (qdict_haskey(dst, key)) {
485 return;
488 val = qdict_get(src, key);
489 if (val) {
490 qobject_incref(val);
491 qdict_put_obj(dst, key, val);
496 * qdict_set_default_str(): If no entry mapped by 'key' exists in 'dst' yet, a
497 * new QString initialised by 'val' is put there.
499 void qdict_set_default_str(QDict *dst, const char *key, const char *val)
501 if (qdict_haskey(dst, key)) {
502 return;
505 qdict_put(dst, key, qstring_from_str(val));
508 static void qdict_flatten_qdict(QDict *qdict, QDict *target,
509 const char *prefix);
511 static void qdict_flatten_qlist(QList *qlist, QDict *target, const char *prefix)
513 QObject *value;
514 const QListEntry *entry;
515 char *new_key;
516 int i;
518 /* This function is never called with prefix == NULL, i.e., it is always
519 * called from within qdict_flatten_q(list|dict)(). Therefore, it does not
520 * need to remove list entries during the iteration (the whole list will be
521 * deleted eventually anyway from qdict_flatten_qdict()). */
522 assert(prefix);
524 entry = qlist_first(qlist);
526 for (i = 0; entry; entry = qlist_next(entry), i++) {
527 value = qlist_entry_obj(entry);
528 new_key = g_strdup_printf("%s.%i", prefix, i);
530 if (qobject_type(value) == QTYPE_QDICT) {
531 qdict_flatten_qdict(qobject_to_qdict(value), target, new_key);
532 } else if (qobject_type(value) == QTYPE_QLIST) {
533 qdict_flatten_qlist(qobject_to_qlist(value), target, new_key);
534 } else {
535 /* All other types are moved to the target unchanged. */
536 qobject_incref(value);
537 qdict_put_obj(target, new_key, value);
540 g_free(new_key);
544 static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix)
546 QObject *value;
547 const QDictEntry *entry, *next;
548 char *new_key;
549 bool delete;
551 entry = qdict_first(qdict);
553 while (entry != NULL) {
555 next = qdict_next(qdict, entry);
556 value = qdict_entry_value(entry);
557 new_key = NULL;
558 delete = false;
560 if (prefix) {
561 new_key = g_strdup_printf("%s.%s", prefix, entry->key);
564 if (qobject_type(value) == QTYPE_QDICT) {
565 /* Entries of QDicts are processed recursively, the QDict object
566 * itself disappears. */
567 qdict_flatten_qdict(qobject_to_qdict(value), target,
568 new_key ? new_key : entry->key);
569 delete = true;
570 } else if (qobject_type(value) == QTYPE_QLIST) {
571 qdict_flatten_qlist(qobject_to_qlist(value), target,
572 new_key ? new_key : entry->key);
573 delete = true;
574 } else if (prefix) {
575 /* All other objects are moved to the target unchanged. */
576 qobject_incref(value);
577 qdict_put_obj(target, new_key, value);
578 delete = true;
581 g_free(new_key);
583 if (delete) {
584 qdict_del(qdict, entry->key);
586 /* Restart loop after modifying the iterated QDict */
587 entry = qdict_first(qdict);
588 continue;
591 entry = next;
596 * qdict_flatten(): For each nested QDict with key x, all fields with key y
597 * are moved to this QDict and their key is renamed to "x.y". For each nested
598 * QList with key x, the field at index y is moved to this QDict with the key
599 * "x.y" (i.e., the reverse of what qdict_array_split() does).
600 * This operation is applied recursively for nested QDicts and QLists.
602 void qdict_flatten(QDict *qdict)
604 qdict_flatten_qdict(qdict, qdict, NULL);
607 /* extract all the src QDict entries starting by start into dst */
608 void qdict_extract_subqdict(QDict *src, QDict **dst, const char *start)
611 const QDictEntry *entry, *next;
612 const char *p;
614 *dst = qdict_new();
615 entry = qdict_first(src);
617 while (entry != NULL) {
618 next = qdict_next(src, entry);
619 if (strstart(entry->key, start, &p)) {
620 qobject_incref(entry->value);
621 qdict_put_obj(*dst, p, entry->value);
622 qdict_del(src, entry->key);
624 entry = next;
628 static int qdict_count_prefixed_entries(const QDict *src, const char *start)
630 const QDictEntry *entry;
631 int count = 0;
633 for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
634 if (strstart(entry->key, start, NULL)) {
635 if (count == INT_MAX) {
636 return -ERANGE;
638 count++;
642 return count;
646 * qdict_array_split(): This function moves array-like elements of a QDict into
647 * a new QList. Every entry in the original QDict with a key "%u" or one
648 * prefixed "%u.", where %u designates an unsigned integer starting at 0 and
649 * incrementally counting up, will be moved to a new QDict at index %u in the
650 * output QList with the key prefix removed, if that prefix is "%u.". If the
651 * whole key is just "%u", the whole QObject will be moved unchanged without
652 * creating a new QDict. The function terminates when there is no entry in the
653 * QDict with a prefix directly (incrementally) following the last one; it also
654 * returns if there are both entries with "%u" and "%u." for the same index %u.
655 * Example: {"0.a": 42, "0.b": 23, "1.x": 0, "4.y": 1, "o.o": 7, "2": 66}
656 * (or {"1.x": 0, "4.y": 1, "0.a": 42, "o.o": 7, "0.b": 23, "2": 66})
657 * => [{"a": 42, "b": 23}, {"x": 0}, 66]
658 * and {"4.y": 1, "o.o": 7} (remainder of the old QDict)
660 void qdict_array_split(QDict *src, QList **dst)
662 unsigned i;
664 *dst = qlist_new();
666 for (i = 0; i < UINT_MAX; i++) {
667 QObject *subqobj;
668 bool is_subqdict;
669 QDict *subqdict;
670 char indexstr[32], prefix[32];
671 size_t snprintf_ret;
673 snprintf_ret = snprintf(indexstr, 32, "%u", i);
674 assert(snprintf_ret < 32);
676 subqobj = qdict_get(src, indexstr);
678 snprintf_ret = snprintf(prefix, 32, "%u.", i);
679 assert(snprintf_ret < 32);
681 /* Overflow is the same as positive non-zero results */
682 is_subqdict = qdict_count_prefixed_entries(src, prefix);
684 // There may be either a single subordinate object (named "%u") or
685 // multiple objects (each with a key prefixed "%u."), but not both.
686 if (!subqobj == !is_subqdict) {
687 break;
690 if (is_subqdict) {
691 qdict_extract_subqdict(src, &subqdict, prefix);
692 assert(qdict_size(subqdict) > 0);
693 } else {
694 qobject_incref(subqobj);
695 qdict_del(src, indexstr);
698 qlist_append_obj(*dst, subqobj ?: QOBJECT(subqdict));
703 * qdict_array_entries(): Returns the number of direct array entries if the
704 * sub-QDict of src specified by the prefix in subqdict (or src itself for
705 * prefix == "") is valid as an array, i.e. the length of the created list if
706 * the sub-QDict would become empty after calling qdict_array_split() on it. If
707 * the array is not valid, -EINVAL is returned.
709 int qdict_array_entries(QDict *src, const char *subqdict)
711 const QDictEntry *entry;
712 unsigned i;
713 unsigned entries = 0;
714 size_t subqdict_len = strlen(subqdict);
716 assert(!subqdict_len || subqdict[subqdict_len - 1] == '.');
718 /* qdict_array_split() loops until UINT_MAX, but as we want to return
719 * negative errors, we only have a signed return value here. Any additional
720 * entries will lead to -EINVAL. */
721 for (i = 0; i < INT_MAX; i++) {
722 QObject *subqobj;
723 int subqdict_entries;
724 size_t slen = 32 + subqdict_len;
725 char indexstr[slen], prefix[slen];
726 size_t snprintf_ret;
728 snprintf_ret = snprintf(indexstr, slen, "%s%u", subqdict, i);
729 assert(snprintf_ret < slen);
731 subqobj = qdict_get(src, indexstr);
733 snprintf_ret = snprintf(prefix, slen, "%s%u.", subqdict, i);
734 assert(snprintf_ret < slen);
736 subqdict_entries = qdict_count_prefixed_entries(src, prefix);
737 if (subqdict_entries < 0) {
738 return subqdict_entries;
741 /* There may be either a single subordinate object (named "%u") or
742 * multiple objects (each with a key prefixed "%u."), but not both. */
743 if (subqobj && subqdict_entries) {
744 return -EINVAL;
745 } else if (!subqobj && !subqdict_entries) {
746 break;
749 entries += subqdict_entries ? subqdict_entries : 1;
752 /* Consider everything handled that isn't part of the given sub-QDict */
753 for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
754 if (!strstart(qdict_entry_key(entry), subqdict, NULL)) {
755 entries++;
759 /* Anything left in the sub-QDict that wasn't handled? */
760 if (qdict_size(src) != entries) {
761 return -EINVAL;
764 return i;
768 * qdict_join(): Absorb the src QDict into the dest QDict, that is, move all
769 * elements from src to dest.
771 * If an element from src has a key already present in dest, it will not be
772 * moved unless overwrite is true.
774 * If overwrite is true, the conflicting values in dest will be discarded and
775 * replaced by the corresponding values from src.
777 * Therefore, with overwrite being true, the src QDict will always be empty when
778 * this function returns. If overwrite is false, the src QDict will be empty
779 * iff there were no conflicts.
781 void qdict_join(QDict *dest, QDict *src, bool overwrite)
783 const QDictEntry *entry, *next;
785 entry = qdict_first(src);
786 while (entry) {
787 next = qdict_next(src, entry);
789 if (overwrite || !qdict_haskey(dest, entry->key)) {
790 qobject_incref(entry->value);
791 qdict_put_obj(dest, entry->key, entry->value);
792 qdict_del(src, entry->key);
795 entry = next;