usb-mtp: Return error on suspicious TYPE_DATA packet from initiator
[qemu/ar7.git] / qobject / qdict.c
blob22800eecebe594210e164e3500da80fc9788f9d7
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 "qemu/osdep.h"
14 #include "qapi/qmp/qnum.h"
15 #include "qapi/qmp/qdict.h"
16 #include "qapi/qmp/qbool.h"
17 #include "qapi/qmp/qlist.h"
18 #include "qapi/qmp/qnull.h"
19 #include "qapi/qmp/qstring.h"
20 #include "qapi/error.h"
21 #include "qemu/queue.h"
22 #include "qemu-common.h"
23 #include "qemu/cutils.h"
25 /**
26 * qdict_new(): Create a new QDict
28 * Return strong reference.
30 QDict *qdict_new(void)
32 QDict *qdict;
34 qdict = g_malloc0(sizeof(*qdict));
35 qobject_init(QOBJECT(qdict), QTYPE_QDICT);
37 return qdict;
40 /**
41 * tdb_hash(): based on the hash agorithm from gdbm, via tdb
42 * (from module-init-tools)
44 static unsigned int tdb_hash(const char *name)
46 unsigned value; /* Used to compute the hash value. */
47 unsigned i; /* Used to cycle through random values. */
49 /* Set the initial value from the key size. */
50 for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
51 value = (value + (((const unsigned char *)name)[i] << (i*5 % 24)));
53 return (1103515243 * value + 12345);
56 /**
57 * alloc_entry(): allocate a new QDictEntry
59 static QDictEntry *alloc_entry(const char *key, QObject *value)
61 QDictEntry *entry;
63 entry = g_malloc0(sizeof(*entry));
64 entry->key = g_strdup(key);
65 entry->value = value;
67 return entry;
70 /**
71 * qdict_entry_value(): Return qdict entry value
73 * Return weak reference.
75 QObject *qdict_entry_value(const QDictEntry *entry)
77 return entry->value;
80 /**
81 * qdict_entry_key(): Return qdict entry key
83 * Return a *pointer* to the string, it has to be duplicated before being
84 * stored.
86 const char *qdict_entry_key(const QDictEntry *entry)
88 return entry->key;
91 /**
92 * qdict_find(): List lookup function
94 static QDictEntry *qdict_find(const QDict *qdict,
95 const char *key, unsigned int bucket)
97 QDictEntry *entry;
99 QLIST_FOREACH(entry, &qdict->table[bucket], next)
100 if (!strcmp(entry->key, key))
101 return entry;
103 return NULL;
107 * qdict_put_obj(): Put a new QObject into the dictionary
109 * Insert the pair 'key:value' into 'qdict', if 'key' already exists
110 * its 'value' will be replaced.
112 * This is done by freeing the reference to the stored QObject and
113 * storing the new one in the same entry.
115 * NOTE: ownership of 'value' is transferred to the QDict
117 void qdict_put_obj(QDict *qdict, const char *key, QObject *value)
119 unsigned int bucket;
120 QDictEntry *entry;
122 bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
123 entry = qdict_find(qdict, key, bucket);
124 if (entry) {
125 /* replace key's value */
126 qobject_unref(entry->value);
127 entry->value = value;
128 } else {
129 /* allocate a new entry */
130 entry = alloc_entry(key, value);
131 QLIST_INSERT_HEAD(&qdict->table[bucket], entry, next);
132 qdict->size++;
136 void qdict_put_int(QDict *qdict, const char *key, int64_t value)
138 qdict_put(qdict, key, qnum_from_int(value));
141 void qdict_put_bool(QDict *qdict, const char *key, bool value)
143 qdict_put(qdict, key, qbool_from_bool(value));
146 void qdict_put_str(QDict *qdict, const char *key, const char *value)
148 qdict_put(qdict, key, qstring_from_str(value));
151 void qdict_put_null(QDict *qdict, const char *key)
153 qdict_put(qdict, key, qnull());
157 * qdict_get(): Lookup for a given 'key'
159 * Return a weak reference to the QObject associated with 'key' if
160 * 'key' is present in the dictionary, NULL otherwise.
162 QObject *qdict_get(const QDict *qdict, const char *key)
164 QDictEntry *entry;
166 entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
167 return (entry == NULL ? NULL : entry->value);
171 * qdict_haskey(): Check if 'key' exists
173 * Return 1 if 'key' exists in the dict, 0 otherwise
175 int qdict_haskey(const QDict *qdict, const char *key)
177 unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
178 return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1);
182 * qdict_size(): Return the size of the dictionary
184 size_t qdict_size(const QDict *qdict)
186 return qdict->size;
190 * qdict_get_double(): Get an number mapped by 'key'
192 * This function assumes that 'key' exists and it stores a QNum.
194 * Return number mapped by 'key'.
196 double qdict_get_double(const QDict *qdict, const char *key)
198 return qnum_get_double(qobject_to(QNum, qdict_get(qdict, key)));
202 * qdict_get_int(): Get an integer mapped by 'key'
204 * This function assumes that 'key' exists and it stores a
205 * QNum representable as int.
207 * Return integer mapped by 'key'.
209 int64_t qdict_get_int(const QDict *qdict, const char *key)
211 return qnum_get_int(qobject_to(QNum, qdict_get(qdict, key)));
215 * qdict_get_bool(): Get a bool mapped by 'key'
217 * This function assumes that 'key' exists and it stores a
218 * QBool object.
220 * Return bool mapped by 'key'.
222 bool qdict_get_bool(const QDict *qdict, const char *key)
224 return qbool_get_bool(qobject_to(QBool, qdict_get(qdict, key)));
228 * qdict_get_qlist(): If @qdict maps @key to a QList, return it, else NULL.
230 QList *qdict_get_qlist(const QDict *qdict, const char *key)
232 return qobject_to(QList, qdict_get(qdict, key));
236 * qdict_get_qdict(): If @qdict maps @key to a QDict, return it, else NULL.
238 QDict *qdict_get_qdict(const QDict *qdict, const char *key)
240 return qobject_to(QDict, qdict_get(qdict, key));
244 * qdict_get_str(): Get a pointer to the stored string mapped
245 * by 'key'
247 * This function assumes that 'key' exists and it stores a
248 * QString object.
250 * Return pointer to the string mapped by 'key'.
252 const char *qdict_get_str(const QDict *qdict, const char *key)
254 return qstring_get_str(qobject_to(QString, qdict_get(qdict, key)));
258 * qdict_get_try_int(): Try to get integer mapped by 'key'
260 * Return integer mapped by 'key', if it is not present in the
261 * dictionary or if the stored object is not a QNum representing an
262 * integer, 'def_value' will be returned.
264 int64_t qdict_get_try_int(const QDict *qdict, const char *key,
265 int64_t def_value)
267 QNum *qnum = qobject_to(QNum, qdict_get(qdict, key));
268 int64_t val;
270 if (!qnum || !qnum_get_try_int(qnum, &val)) {
271 return def_value;
274 return val;
278 * qdict_get_try_bool(): Try to get a bool mapped by 'key'
280 * Return bool mapped by 'key', if it is not present in the
281 * dictionary or if the stored object is not of QBool type
282 * 'def_value' will be returned.
284 bool qdict_get_try_bool(const QDict *qdict, const char *key, bool def_value)
286 QBool *qbool = qobject_to(QBool, qdict_get(qdict, key));
288 return qbool ? qbool_get_bool(qbool) : def_value;
292 * qdict_get_try_str(): Try to get a pointer to the stored string
293 * mapped by 'key'
295 * Return a pointer to the string mapped by 'key', if it is not present
296 * in the dictionary or if the stored object is not of QString type
297 * NULL will be returned.
299 const char *qdict_get_try_str(const QDict *qdict, const char *key)
301 QString *qstr = qobject_to(QString, qdict_get(qdict, key));
303 return qstr ? qstring_get_str(qstr) : NULL;
307 * qdict_iter(): Iterate over all the dictionary's stored values.
309 * This function allows the user to provide an iterator, which will be
310 * called for each stored value in the dictionary.
312 void qdict_iter(const QDict *qdict,
313 void (*iter)(const char *key, QObject *obj, void *opaque),
314 void *opaque)
316 int i;
317 QDictEntry *entry;
319 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
320 QLIST_FOREACH(entry, &qdict->table[i], next)
321 iter(entry->key, entry->value, opaque);
325 static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket)
327 int i;
329 for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) {
330 if (!QLIST_EMPTY(&qdict->table[i])) {
331 return QLIST_FIRST(&qdict->table[i]);
335 return NULL;
339 * qdict_first(): Return first qdict entry for iteration.
341 const QDictEntry *qdict_first(const QDict *qdict)
343 return qdict_next_entry(qdict, 0);
347 * qdict_next(): Return next qdict entry in an iteration.
349 const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry)
351 QDictEntry *ret;
353 ret = QLIST_NEXT(entry, next);
354 if (!ret) {
355 unsigned int bucket = tdb_hash(entry->key) % QDICT_BUCKET_MAX;
356 ret = qdict_next_entry(qdict, bucket + 1);
359 return ret;
363 * qdict_clone_shallow(): Clones a given QDict. Its entries are not copied, but
364 * another reference is added.
366 QDict *qdict_clone_shallow(const QDict *src)
368 QDict *dest;
369 QDictEntry *entry;
370 int i;
372 dest = qdict_new();
374 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
375 QLIST_FOREACH(entry, &src->table[i], next) {
376 qdict_put_obj(dest, entry->key, qobject_ref(entry->value));
380 return dest;
384 * qentry_destroy(): Free all the memory allocated by a QDictEntry
386 static void qentry_destroy(QDictEntry *e)
388 assert(e != NULL);
389 assert(e->key != NULL);
390 assert(e->value != NULL);
392 qobject_unref(e->value);
393 g_free(e->key);
394 g_free(e);
398 * qdict_del(): Delete a 'key:value' pair from the dictionary
400 * This will destroy all data allocated by this entry.
402 void qdict_del(QDict *qdict, const char *key)
404 QDictEntry *entry;
406 entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
407 if (entry) {
408 QLIST_REMOVE(entry, next);
409 qentry_destroy(entry);
410 qdict->size--;
415 * qdict_is_equal(): Test whether the two QDicts are equal
417 * Here, equality means whether they contain the same keys and whether
418 * the respective values are in turn equal (i.e. invoking
419 * qobject_is_equal() on them yields true).
421 bool qdict_is_equal(const QObject *x, const QObject *y)
423 const QDict *dict_x = qobject_to(QDict, x);
424 const QDict *dict_y = qobject_to(QDict, y);
425 const QDictEntry *e;
427 if (qdict_size(dict_x) != qdict_size(dict_y)) {
428 return false;
431 for (e = qdict_first(dict_x); e; e = qdict_next(dict_x, e)) {
432 const QObject *obj_x = qdict_entry_value(e);
433 const QObject *obj_y = qdict_get(dict_y, qdict_entry_key(e));
435 if (!qobject_is_equal(obj_x, obj_y)) {
436 return false;
440 return true;
444 * qdict_destroy_obj(): Free all the memory allocated by a QDict
446 void qdict_destroy_obj(QObject *obj)
448 int i;
449 QDict *qdict;
451 assert(obj != NULL);
452 qdict = qobject_to(QDict, obj);
454 for (i = 0; i < QDICT_BUCKET_MAX; i++) {
455 QDictEntry *entry = QLIST_FIRST(&qdict->table[i]);
456 while (entry) {
457 QDictEntry *tmp = QLIST_NEXT(entry, next);
458 QLIST_REMOVE(entry, next);
459 qentry_destroy(entry);
460 entry = tmp;
464 g_free(qdict);
468 * qdict_copy_default(): If no entry mapped by 'key' exists in 'dst' yet, the
469 * value of 'key' in 'src' is copied there (and the refcount increased
470 * accordingly).
472 void qdict_copy_default(QDict *dst, QDict *src, const char *key)
474 QObject *val;
476 if (qdict_haskey(dst, key)) {
477 return;
480 val = qdict_get(src, key);
481 if (val) {
482 qdict_put_obj(dst, key, qobject_ref(val));
487 * qdict_set_default_str(): If no entry mapped by 'key' exists in 'dst' yet, a
488 * new QString initialised by 'val' is put there.
490 void qdict_set_default_str(QDict *dst, const char *key, const char *val)
492 if (qdict_haskey(dst, key)) {
493 return;
496 qdict_put_str(dst, key, val);
499 static void qdict_flatten_qdict(QDict *qdict, QDict *target,
500 const char *prefix);
502 static void qdict_flatten_qlist(QList *qlist, QDict *target, const char *prefix)
504 QObject *value;
505 const QListEntry *entry;
506 char *new_key;
507 int i;
509 /* This function is never called with prefix == NULL, i.e., it is always
510 * called from within qdict_flatten_q(list|dict)(). Therefore, it does not
511 * need to remove list entries during the iteration (the whole list will be
512 * deleted eventually anyway from qdict_flatten_qdict()). */
513 assert(prefix);
515 entry = qlist_first(qlist);
517 for (i = 0; entry; entry = qlist_next(entry), i++) {
518 value = qlist_entry_obj(entry);
519 new_key = g_strdup_printf("%s.%i", prefix, i);
521 if (qobject_type(value) == QTYPE_QDICT) {
522 qdict_flatten_qdict(qobject_to(QDict, value), target, new_key);
523 } else if (qobject_type(value) == QTYPE_QLIST) {
524 qdict_flatten_qlist(qobject_to(QList, value), target, new_key);
525 } else {
526 /* All other types are moved to the target unchanged. */
527 qdict_put_obj(target, new_key, qobject_ref(value));
530 g_free(new_key);
534 static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix)
536 QObject *value;
537 const QDictEntry *entry, *next;
538 char *new_key;
539 bool delete;
541 entry = qdict_first(qdict);
543 while (entry != NULL) {
545 next = qdict_next(qdict, entry);
546 value = qdict_entry_value(entry);
547 new_key = NULL;
548 delete = false;
550 if (prefix) {
551 new_key = g_strdup_printf("%s.%s", prefix, entry->key);
554 if (qobject_type(value) == QTYPE_QDICT) {
555 /* Entries of QDicts are processed recursively, the QDict object
556 * itself disappears. */
557 qdict_flatten_qdict(qobject_to(QDict, value), target,
558 new_key ? new_key : entry->key);
559 delete = true;
560 } else if (qobject_type(value) == QTYPE_QLIST) {
561 qdict_flatten_qlist(qobject_to(QList, value), target,
562 new_key ? new_key : entry->key);
563 delete = true;
564 } else if (prefix) {
565 /* All other objects are moved to the target unchanged. */
566 qdict_put_obj(target, new_key, qobject_ref(value));
567 delete = true;
570 g_free(new_key);
572 if (delete) {
573 qdict_del(qdict, entry->key);
575 /* Restart loop after modifying the iterated QDict */
576 entry = qdict_first(qdict);
577 continue;
580 entry = next;
585 * qdict_flatten(): For each nested QDict with key x, all fields with key y
586 * are moved to this QDict and their key is renamed to "x.y". For each nested
587 * QList with key x, the field at index y is moved to this QDict with the key
588 * "x.y" (i.e., the reverse of what qdict_array_split() does).
589 * This operation is applied recursively for nested QDicts and QLists.
591 void qdict_flatten(QDict *qdict)
593 qdict_flatten_qdict(qdict, qdict, NULL);
596 /* extract all the src QDict entries starting by start into dst */
597 void qdict_extract_subqdict(QDict *src, QDict **dst, const char *start)
600 const QDictEntry *entry, *next;
601 const char *p;
603 *dst = qdict_new();
604 entry = qdict_first(src);
606 while (entry != NULL) {
607 next = qdict_next(src, entry);
608 if (strstart(entry->key, start, &p)) {
609 qdict_put_obj(*dst, p, qobject_ref(entry->value));
610 qdict_del(src, entry->key);
612 entry = next;
616 static int qdict_count_prefixed_entries(const QDict *src, const char *start)
618 const QDictEntry *entry;
619 int count = 0;
621 for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
622 if (strstart(entry->key, start, NULL)) {
623 if (count == INT_MAX) {
624 return -ERANGE;
626 count++;
630 return count;
634 * qdict_array_split(): This function moves array-like elements of a QDict into
635 * a new QList. Every entry in the original QDict with a key "%u" or one
636 * prefixed "%u.", where %u designates an unsigned integer starting at 0 and
637 * incrementally counting up, will be moved to a new QDict at index %u in the
638 * output QList with the key prefix removed, if that prefix is "%u.". If the
639 * whole key is just "%u", the whole QObject will be moved unchanged without
640 * creating a new QDict. The function terminates when there is no entry in the
641 * QDict with a prefix directly (incrementally) following the last one; it also
642 * returns if there are both entries with "%u" and "%u." for the same index %u.
643 * Example: {"0.a": 42, "0.b": 23, "1.x": 0, "4.y": 1, "o.o": 7, "2": 66}
644 * (or {"1.x": 0, "4.y": 1, "0.a": 42, "o.o": 7, "0.b": 23, "2": 66})
645 * => [{"a": 42, "b": 23}, {"x": 0}, 66]
646 * and {"4.y": 1, "o.o": 7} (remainder of the old QDict)
648 void qdict_array_split(QDict *src, QList **dst)
650 unsigned i;
652 *dst = qlist_new();
654 for (i = 0; i < UINT_MAX; i++) {
655 QObject *subqobj;
656 bool is_subqdict;
657 QDict *subqdict;
658 char indexstr[32], prefix[32];
659 size_t snprintf_ret;
661 snprintf_ret = snprintf(indexstr, 32, "%u", i);
662 assert(snprintf_ret < 32);
664 subqobj = qdict_get(src, indexstr);
666 snprintf_ret = snprintf(prefix, 32, "%u.", i);
667 assert(snprintf_ret < 32);
669 /* Overflow is the same as positive non-zero results */
670 is_subqdict = qdict_count_prefixed_entries(src, prefix);
672 // There may be either a single subordinate object (named "%u") or
673 // multiple objects (each with a key prefixed "%u."), but not both.
674 if (!subqobj == !is_subqdict) {
675 break;
678 if (is_subqdict) {
679 qdict_extract_subqdict(src, &subqdict, prefix);
680 assert(qdict_size(subqdict) > 0);
681 } else {
682 qobject_ref(subqobj);
683 qdict_del(src, indexstr);
686 qlist_append_obj(*dst, subqobj ?: QOBJECT(subqdict));
691 * qdict_split_flat_key:
692 * @key: the key string to split
693 * @prefix: non-NULL pointer to hold extracted prefix
694 * @suffix: non-NULL pointer to remaining suffix
696 * Given a flattened key such as 'foo.0.bar', split it into two parts
697 * at the first '.' separator. Allows double dot ('..') to escape the
698 * normal separator.
700 * e.g.
701 * 'foo.0.bar' -> prefix='foo' and suffix='0.bar'
702 * 'foo..0.bar' -> prefix='foo.0' and suffix='bar'
704 * The '..' sequence will be unescaped in the returned 'prefix'
705 * string. The 'suffix' string will be left in escaped format, so it
706 * can be fed back into the qdict_split_flat_key() key as the input
707 * later.
709 * The caller is responsible for freeing the string returned in @prefix
710 * using g_free().
712 static void qdict_split_flat_key(const char *key, char **prefix,
713 const char **suffix)
715 const char *separator;
716 size_t i, j;
718 /* Find first '.' separator, but if there is a pair '..'
719 * that acts as an escape, so skip over '..' */
720 separator = NULL;
721 do {
722 if (separator) {
723 separator += 2;
724 } else {
725 separator = key;
727 separator = strchr(separator, '.');
728 } while (separator && separator[1] == '.');
730 if (separator) {
731 *prefix = g_strndup(key, separator - key);
732 *suffix = separator + 1;
733 } else {
734 *prefix = g_strdup(key);
735 *suffix = NULL;
738 /* Unescape the '..' sequence into '.' */
739 for (i = 0, j = 0; (*prefix)[i] != '\0'; i++, j++) {
740 if ((*prefix)[i] == '.') {
741 assert((*prefix)[i + 1] == '.');
742 i++;
744 (*prefix)[j] = (*prefix)[i];
746 (*prefix)[j] = '\0';
750 * qdict_is_list:
751 * @maybe_list: dict to check if keys represent list elements.
753 * Determine whether all keys in @maybe_list are valid list elements.
754 * If @maybe_list is non-zero in length and all the keys look like
755 * valid list indexes, this will return 1. If @maybe_list is zero
756 * length or all keys are non-numeric then it will return 0 to indicate
757 * it is a normal qdict. If there is a mix of numeric and non-numeric
758 * keys, or the list indexes are non-contiguous, an error is reported.
760 * Returns: 1 if a valid list, 0 if a dict, -1 on error
762 static int qdict_is_list(QDict *maybe_list, Error **errp)
764 const QDictEntry *ent;
765 ssize_t len = 0;
766 ssize_t max = -1;
767 int is_list = -1;
768 int64_t val;
770 for (ent = qdict_first(maybe_list); ent != NULL;
771 ent = qdict_next(maybe_list, ent)) {
773 if (qemu_strtoi64(ent->key, NULL, 10, &val) == 0) {
774 if (is_list == -1) {
775 is_list = 1;
776 } else if (!is_list) {
777 error_setg(errp,
778 "Cannot mix list and non-list keys");
779 return -1;
781 len++;
782 if (val > max) {
783 max = val;
785 } else {
786 if (is_list == -1) {
787 is_list = 0;
788 } else if (is_list) {
789 error_setg(errp,
790 "Cannot mix list and non-list keys");
791 return -1;
796 if (is_list == -1) {
797 assert(!qdict_size(maybe_list));
798 is_list = 0;
801 /* NB this isn't a perfect check - e.g. it won't catch
802 * a list containing '1', '+1', '01', '3', but that
803 * does not matter - we've still proved that the
804 * input is a list. It is up the caller to do a
805 * stricter check if desired */
806 if (len != (max + 1)) {
807 error_setg(errp, "List indices are not contiguous, "
808 "saw %zd elements but %zd largest index",
809 len, max);
810 return -1;
813 return is_list;
817 * qdict_crumple:
818 * @src: the original flat dictionary (only scalar values) to crumple
820 * Takes a flat dictionary whose keys use '.' separator to indicate
821 * nesting, and values are scalars, and crumples it into a nested
822 * structure.
824 * To include a literal '.' in a key name, it must be escaped as '..'
826 * For example, an input of:
828 * { 'foo.0.bar': 'one', 'foo.0.wizz': '1',
829 * 'foo.1.bar': 'two', 'foo.1.wizz': '2' }
831 * will result in an output of:
834 * 'foo': [
835 * { 'bar': 'one', 'wizz': '1' },
836 * { 'bar': 'two', 'wizz': '2' }
837 * ],
840 * The following scenarios in the input dict will result in an
841 * error being returned:
843 * - Any values in @src are non-scalar types
844 * - If keys in @src imply that a particular level is both a
845 * list and a dict. e.g., "foo.0.bar" and "foo.eek.bar".
846 * - If keys in @src imply that a particular level is a list,
847 * but the indices are non-contiguous. e.g. "foo.0.bar" and
848 * "foo.2.bar" without any "foo.1.bar" present.
849 * - If keys in @src represent list indexes, but are not in
850 * the "%zu" format. e.g. "foo.+0.bar"
852 * Returns: either a QDict or QList for the nested data structure, or NULL
853 * on error
855 QObject *qdict_crumple(const QDict *src, Error **errp)
857 const QDictEntry *ent;
858 QDict *two_level, *multi_level = NULL;
859 QObject *dst = NULL, *child;
860 size_t i;
861 char *prefix = NULL;
862 const char *suffix = NULL;
863 int is_list;
865 two_level = qdict_new();
867 /* Step 1: split our totally flat dict into a two level dict */
868 for (ent = qdict_first(src); ent != NULL; ent = qdict_next(src, ent)) {
869 if (qobject_type(ent->value) == QTYPE_QDICT ||
870 qobject_type(ent->value) == QTYPE_QLIST) {
871 error_setg(errp, "Value %s is not a scalar",
872 ent->key);
873 goto error;
876 qdict_split_flat_key(ent->key, &prefix, &suffix);
878 child = qdict_get(two_level, prefix);
879 if (suffix) {
880 QDict *child_dict = qobject_to(QDict, child);
881 if (!child_dict) {
882 if (child) {
883 error_setg(errp, "Key %s prefix is already set as a scalar",
884 prefix);
885 goto error;
888 child_dict = qdict_new();
889 qdict_put_obj(two_level, prefix, QOBJECT(child_dict));
892 qdict_put_obj(child_dict, suffix, qobject_ref(ent->value));
893 } else {
894 if (child) {
895 error_setg(errp, "Key %s prefix is already set as a dict",
896 prefix);
897 goto error;
899 qdict_put_obj(two_level, prefix, qobject_ref(ent->value));
902 g_free(prefix);
903 prefix = NULL;
906 /* Step 2: optionally process the two level dict recursively
907 * into a multi-level dict */
908 multi_level = qdict_new();
909 for (ent = qdict_first(two_level); ent != NULL;
910 ent = qdict_next(two_level, ent)) {
911 QDict *dict = qobject_to(QDict, ent->value);
912 if (dict) {
913 child = qdict_crumple(dict, errp);
914 if (!child) {
915 goto error;
918 qdict_put_obj(multi_level, ent->key, child);
919 } else {
920 qdict_put_obj(multi_level, ent->key, qobject_ref(ent->value));
923 qobject_unref(two_level);
924 two_level = NULL;
926 /* Step 3: detect if we need to turn our dict into list */
927 is_list = qdict_is_list(multi_level, errp);
928 if (is_list < 0) {
929 goto error;
932 if (is_list) {
933 dst = QOBJECT(qlist_new());
935 for (i = 0; i < qdict_size(multi_level); i++) {
936 char *key = g_strdup_printf("%zu", i);
938 child = qdict_get(multi_level, key);
939 g_free(key);
941 if (!child) {
942 error_setg(errp, "Missing list index %zu", i);
943 goto error;
946 qlist_append_obj(qobject_to(QList, dst), qobject_ref(child));
948 qobject_unref(multi_level);
949 multi_level = NULL;
950 } else {
951 dst = QOBJECT(multi_level);
954 return dst;
956 error:
957 g_free(prefix);
958 qobject_unref(multi_level);
959 qobject_unref(two_level);
960 qobject_unref(dst);
961 return NULL;
965 * qdict_array_entries(): Returns the number of direct array entries if the
966 * sub-QDict of src specified by the prefix in subqdict (or src itself for
967 * prefix == "") is valid as an array, i.e. the length of the created list if
968 * the sub-QDict would become empty after calling qdict_array_split() on it. If
969 * the array is not valid, -EINVAL is returned.
971 int qdict_array_entries(QDict *src, const char *subqdict)
973 const QDictEntry *entry;
974 unsigned i;
975 unsigned entries = 0;
976 size_t subqdict_len = strlen(subqdict);
978 assert(!subqdict_len || subqdict[subqdict_len - 1] == '.');
980 /* qdict_array_split() loops until UINT_MAX, but as we want to return
981 * negative errors, we only have a signed return value here. Any additional
982 * entries will lead to -EINVAL. */
983 for (i = 0; i < INT_MAX; i++) {
984 QObject *subqobj;
985 int subqdict_entries;
986 char *prefix = g_strdup_printf("%s%u.", subqdict, i);
988 subqdict_entries = qdict_count_prefixed_entries(src, prefix);
990 /* Remove ending "." */
991 prefix[strlen(prefix) - 1] = 0;
992 subqobj = qdict_get(src, prefix);
994 g_free(prefix);
996 if (subqdict_entries < 0) {
997 return subqdict_entries;
1000 /* There may be either a single subordinate object (named "%u") or
1001 * multiple objects (each with a key prefixed "%u."), but not both. */
1002 if (subqobj && subqdict_entries) {
1003 return -EINVAL;
1004 } else if (!subqobj && !subqdict_entries) {
1005 break;
1008 entries += subqdict_entries ? subqdict_entries : 1;
1011 /* Consider everything handled that isn't part of the given sub-QDict */
1012 for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
1013 if (!strstart(qdict_entry_key(entry), subqdict, NULL)) {
1014 entries++;
1018 /* Anything left in the sub-QDict that wasn't handled? */
1019 if (qdict_size(src) != entries) {
1020 return -EINVAL;
1023 return i;
1027 * qdict_join(): Absorb the src QDict into the dest QDict, that is, move all
1028 * elements from src to dest.
1030 * If an element from src has a key already present in dest, it will not be
1031 * moved unless overwrite is true.
1033 * If overwrite is true, the conflicting values in dest will be discarded and
1034 * replaced by the corresponding values from src.
1036 * Therefore, with overwrite being true, the src QDict will always be empty when
1037 * this function returns. If overwrite is false, the src QDict will be empty
1038 * iff there were no conflicts.
1040 void qdict_join(QDict *dest, QDict *src, bool overwrite)
1042 const QDictEntry *entry, *next;
1044 entry = qdict_first(src);
1045 while (entry) {
1046 next = qdict_next(src, entry);
1048 if (overwrite || !qdict_haskey(dest, entry->key)) {
1049 qdict_put_obj(dest, entry->key, qobject_ref(entry->value));
1050 qdict_del(src, entry->key);
1053 entry = next;
1058 * qdict_rename_keys(): Rename keys in qdict according to the replacements
1059 * specified in the array renames. The array must be terminated by an entry
1060 * with from = NULL.
1062 * The renames are performed individually in the order of the array, so entries
1063 * may be renamed multiple times and may or may not conflict depending on the
1064 * order of the renames array.
1066 * Returns true for success, false in error cases.
1068 bool qdict_rename_keys(QDict *qdict, const QDictRenames *renames, Error **errp)
1070 QObject *qobj;
1072 while (renames->from) {
1073 if (qdict_haskey(qdict, renames->from)) {
1074 if (qdict_haskey(qdict, renames->to)) {
1075 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
1076 "same time", renames->to, renames->from);
1077 return false;
1080 qobj = qdict_get(qdict, renames->from);
1081 qdict_put_obj(qdict, renames->to, qobject_ref(qobj));
1082 qdict_del(qdict, renames->from);
1085 renames++;
1087 return true;