xref: /qemu/qobject/qdict.c (revision 922a01a0)
1 /*
2  * QDict 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/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"
24 
25 /**
26  * qdict_new(): Create a new QDict
27  *
28  * Return strong reference.
29  */
30 QDict *qdict_new(void)
31 {
32     QDict *qdict;
33 
34     qdict = g_malloc0(sizeof(*qdict));
35     qobject_init(QOBJECT(qdict), QTYPE_QDICT);
36 
37     return qdict;
38 }
39 
40 /**
41  * qobject_to_qdict(): Convert a QObject into a QDict
42  */
43 QDict *qobject_to_qdict(const QObject *obj)
44 {
45     if (!obj || qobject_type(obj) != QTYPE_QDICT) {
46         return NULL;
47     }
48     return container_of(obj, QDict, base);
49 }
50 
51 /**
52  * tdb_hash(): based on the hash agorithm from gdbm, via tdb
53  * (from module-init-tools)
54  */
55 static unsigned int tdb_hash(const char *name)
56 {
57     unsigned value;	/* Used to compute the hash value.  */
58     unsigned   i;	/* Used to cycle through random values. */
59 
60     /* Set the initial value from the key size. */
61     for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
62         value = (value + (((const unsigned char *)name)[i] << (i*5 % 24)));
63 
64     return (1103515243 * value + 12345);
65 }
66 
67 /**
68  * alloc_entry(): allocate a new QDictEntry
69  */
70 static QDictEntry *alloc_entry(const char *key, QObject *value)
71 {
72     QDictEntry *entry;
73 
74     entry = g_malloc0(sizeof(*entry));
75     entry->key = g_strdup(key);
76     entry->value = value;
77 
78     return entry;
79 }
80 
81 /**
82  * qdict_entry_value(): Return qdict entry value
83  *
84  * Return weak reference.
85  */
86 QObject *qdict_entry_value(const QDictEntry *entry)
87 {
88     return entry->value;
89 }
90 
91 /**
92  * qdict_entry_key(): Return qdict entry key
93  *
94  * Return a *pointer* to the string, it has to be duplicated before being
95  * stored.
96  */
97 const char *qdict_entry_key(const QDictEntry *entry)
98 {
99     return entry->key;
100 }
101 
102 /**
103  * qdict_find(): List lookup function
104  */
105 static QDictEntry *qdict_find(const QDict *qdict,
106                               const char *key, unsigned int bucket)
107 {
108     QDictEntry *entry;
109 
110     QLIST_FOREACH(entry, &qdict->table[bucket], next)
111         if (!strcmp(entry->key, key))
112             return entry;
113 
114     return NULL;
115 }
116 
117 /**
118  * qdict_put_obj(): Put a new QObject into the dictionary
119  *
120  * Insert the pair 'key:value' into 'qdict', if 'key' already exists
121  * its 'value' will be replaced.
122  *
123  * This is done by freeing the reference to the stored QObject and
124  * storing the new one in the same entry.
125  *
126  * NOTE: ownership of 'value' is transferred to the QDict
127  */
128 void qdict_put_obj(QDict *qdict, const char *key, QObject *value)
129 {
130     unsigned int bucket;
131     QDictEntry *entry;
132 
133     bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
134     entry = qdict_find(qdict, key, bucket);
135     if (entry) {
136         /* replace key's value */
137         qobject_decref(entry->value);
138         entry->value = value;
139     } else {
140         /* allocate a new entry */
141         entry = alloc_entry(key, value);
142         QLIST_INSERT_HEAD(&qdict->table[bucket], entry, next);
143         qdict->size++;
144     }
145 }
146 
147 void qdict_put_int(QDict *qdict, const char *key, int64_t value)
148 {
149     qdict_put(qdict, key, qnum_from_int(value));
150 }
151 
152 void qdict_put_bool(QDict *qdict, const char *key, bool value)
153 {
154     qdict_put(qdict, key, qbool_from_bool(value));
155 }
156 
157 void qdict_put_str(QDict *qdict, const char *key, const char *value)
158 {
159     qdict_put(qdict, key, qstring_from_str(value));
160 }
161 
162 void qdict_put_null(QDict *qdict, const char *key)
163 {
164     qdict_put(qdict, key, qnull());
165 }
166 
167 /**
168  * qdict_get(): Lookup for a given 'key'
169  *
170  * Return a weak reference to the QObject associated with 'key' if
171  * 'key' is present in the dictionary, NULL otherwise.
172  */
173 QObject *qdict_get(const QDict *qdict, const char *key)
174 {
175     QDictEntry *entry;
176 
177     entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
178     return (entry == NULL ? NULL : entry->value);
179 }
180 
181 /**
182  * qdict_haskey(): Check if 'key' exists
183  *
184  * Return 1 if 'key' exists in the dict, 0 otherwise
185  */
186 int qdict_haskey(const QDict *qdict, const char *key)
187 {
188     unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
189     return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1);
190 }
191 
192 /**
193  * qdict_size(): Return the size of the dictionary
194  */
195 size_t qdict_size(const QDict *qdict)
196 {
197     return qdict->size;
198 }
199 
200 /**
201  * qdict_get_double(): Get an number mapped by 'key'
202  *
203  * This function assumes that 'key' exists and it stores a QNum.
204  *
205  * Return number mapped by 'key'.
206  */
207 double qdict_get_double(const QDict *qdict, const char *key)
208 {
209     return qnum_get_double(qobject_to_qnum(qdict_get(qdict, key)));
210 }
211 
212 /**
213  * qdict_get_int(): Get an integer mapped by 'key'
214  *
215  * This function assumes that 'key' exists and it stores a
216  * QNum representable as int.
217  *
218  * Return integer mapped by 'key'.
219  */
220 int64_t qdict_get_int(const QDict *qdict, const char *key)
221 {
222     return qnum_get_int(qobject_to_qnum(qdict_get(qdict, key)));
223 }
224 
225 /**
226  * qdict_get_bool(): Get a bool mapped by 'key'
227  *
228  * This function assumes that 'key' exists and it stores a
229  * QBool object.
230  *
231  * Return bool mapped by 'key'.
232  */
233 bool qdict_get_bool(const QDict *qdict, const char *key)
234 {
235     return qbool_get_bool(qobject_to_qbool(qdict_get(qdict, key)));
236 }
237 
238 /**
239  * qdict_get_qlist(): If @qdict maps @key to a QList, return it, else NULL.
240  */
241 QList *qdict_get_qlist(const QDict *qdict, const char *key)
242 {
243     return qobject_to_qlist(qdict_get(qdict, key));
244 }
245 
246 /**
247  * qdict_get_qdict(): If @qdict maps @key to a QDict, return it, else NULL.
248  */
249 QDict *qdict_get_qdict(const QDict *qdict, const char *key)
250 {
251     return qobject_to_qdict(qdict_get(qdict, key));
252 }
253 
254 /**
255  * qdict_get_str(): Get a pointer to the stored string mapped
256  * by 'key'
257  *
258  * This function assumes that 'key' exists and it stores a
259  * QString object.
260  *
261  * Return pointer to the string mapped by 'key'.
262  */
263 const char *qdict_get_str(const QDict *qdict, const char *key)
264 {
265     return qstring_get_str(qobject_to_qstring(qdict_get(qdict, key)));
266 }
267 
268 /**
269  * qdict_get_try_int(): Try to get integer mapped by 'key'
270  *
271  * Return integer mapped by 'key', if it is not present in the
272  * dictionary or if the stored object is not a QNum representing an
273  * integer, 'def_value' will be returned.
274  */
275 int64_t qdict_get_try_int(const QDict *qdict, const char *key,
276                           int64_t def_value)
277 {
278     QNum *qnum = qobject_to_qnum(qdict_get(qdict, key));
279     int64_t val;
280 
281     if (!qnum || !qnum_get_try_int(qnum, &val)) {
282         return def_value;
283     }
284 
285     return val;
286 }
287 
288 /**
289  * qdict_get_try_bool(): Try to get a bool mapped by 'key'
290  *
291  * Return bool mapped by 'key', if it is not present in the
292  * dictionary or if the stored object is not of QBool type
293  * 'def_value' will be returned.
294  */
295 bool qdict_get_try_bool(const QDict *qdict, const char *key, bool def_value)
296 {
297     QBool *qbool = qobject_to_qbool(qdict_get(qdict, key));
298 
299     return qbool ? qbool_get_bool(qbool) : def_value;
300 }
301 
302 /**
303  * qdict_get_try_str(): Try to get a pointer to the stored string
304  * mapped by 'key'
305  *
306  * Return a pointer to the string mapped by 'key', if it is not present
307  * in the dictionary or if the stored object is not of QString type
308  * NULL will be returned.
309  */
310 const char *qdict_get_try_str(const QDict *qdict, const char *key)
311 {
312     QString *qstr = qobject_to_qstring(qdict_get(qdict, key));
313 
314     return qstr ? qstring_get_str(qstr) : NULL;
315 }
316 
317 /**
318  * qdict_iter(): Iterate over all the dictionary's stored values.
319  *
320  * This function allows the user to provide an iterator, which will be
321  * called for each stored value in the dictionary.
322  */
323 void qdict_iter(const QDict *qdict,
324                 void (*iter)(const char *key, QObject *obj, void *opaque),
325                 void *opaque)
326 {
327     int i;
328     QDictEntry *entry;
329 
330     for (i = 0; i < QDICT_BUCKET_MAX; i++) {
331         QLIST_FOREACH(entry, &qdict->table[i], next)
332             iter(entry->key, entry->value, opaque);
333     }
334 }
335 
336 static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket)
337 {
338     int i;
339 
340     for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) {
341         if (!QLIST_EMPTY(&qdict->table[i])) {
342             return QLIST_FIRST(&qdict->table[i]);
343         }
344     }
345 
346     return NULL;
347 }
348 
349 /**
350  * qdict_first(): Return first qdict entry for iteration.
351  */
352 const QDictEntry *qdict_first(const QDict *qdict)
353 {
354     return qdict_next_entry(qdict, 0);
355 }
356 
357 /**
358  * qdict_next(): Return next qdict entry in an iteration.
359  */
360 const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry)
361 {
362     QDictEntry *ret;
363 
364     ret = QLIST_NEXT(entry, next);
365     if (!ret) {
366         unsigned int bucket = tdb_hash(entry->key) % QDICT_BUCKET_MAX;
367         ret = qdict_next_entry(qdict, bucket + 1);
368     }
369 
370     return ret;
371 }
372 
373 /**
374  * qdict_clone_shallow(): Clones a given QDict. Its entries are not copied, but
375  * another reference is added.
376  */
377 QDict *qdict_clone_shallow(const QDict *src)
378 {
379     QDict *dest;
380     QDictEntry *entry;
381     int i;
382 
383     dest = qdict_new();
384 
385     for (i = 0; i < QDICT_BUCKET_MAX; i++) {
386         QLIST_FOREACH(entry, &src->table[i], next) {
387             qobject_incref(entry->value);
388             qdict_put_obj(dest, entry->key, entry->value);
389         }
390     }
391 
392     return dest;
393 }
394 
395 /**
396  * qentry_destroy(): Free all the memory allocated by a QDictEntry
397  */
398 static void qentry_destroy(QDictEntry *e)
399 {
400     assert(e != NULL);
401     assert(e->key != NULL);
402     assert(e->value != NULL);
403 
404     qobject_decref(e->value);
405     g_free(e->key);
406     g_free(e);
407 }
408 
409 /**
410  * qdict_del(): Delete a 'key:value' pair from the dictionary
411  *
412  * This will destroy all data allocated by this entry.
413  */
414 void qdict_del(QDict *qdict, const char *key)
415 {
416     QDictEntry *entry;
417 
418     entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
419     if (entry) {
420         QLIST_REMOVE(entry, next);
421         qentry_destroy(entry);
422         qdict->size--;
423     }
424 }
425 
426 /**
427  * qdict_is_equal(): Test whether the two QDicts are equal
428  *
429  * Here, equality means whether they contain the same keys and whether
430  * the respective values are in turn equal (i.e. invoking
431  * qobject_is_equal() on them yields true).
432  */
433 bool qdict_is_equal(const QObject *x, const QObject *y)
434 {
435     const QDict *dict_x = qobject_to_qdict(x);
436     const QDict *dict_y = qobject_to_qdict(y);
437     const QDictEntry *e;
438 
439     if (qdict_size(dict_x) != qdict_size(dict_y)) {
440         return false;
441     }
442 
443     for (e = qdict_first(dict_x); e; e = qdict_next(dict_x, e)) {
444         const QObject *obj_x = qdict_entry_value(e);
445         const QObject *obj_y = qdict_get(dict_y, qdict_entry_key(e));
446 
447         if (!qobject_is_equal(obj_x, obj_y)) {
448             return false;
449         }
450     }
451 
452     return true;
453 }
454 
455 /**
456  * qdict_destroy_obj(): Free all the memory allocated by a QDict
457  */
458 void qdict_destroy_obj(QObject *obj)
459 {
460     int i;
461     QDict *qdict;
462 
463     assert(obj != NULL);
464     qdict = qobject_to_qdict(obj);
465 
466     for (i = 0; i < QDICT_BUCKET_MAX; i++) {
467         QDictEntry *entry = QLIST_FIRST(&qdict->table[i]);
468         while (entry) {
469             QDictEntry *tmp = QLIST_NEXT(entry, next);
470             QLIST_REMOVE(entry, next);
471             qentry_destroy(entry);
472             entry = tmp;
473         }
474     }
475 
476     g_free(qdict);
477 }
478 
479 /**
480  * qdict_copy_default(): If no entry mapped by 'key' exists in 'dst' yet, the
481  * value of 'key' in 'src' is copied there (and the refcount increased
482  * accordingly).
483  */
484 void qdict_copy_default(QDict *dst, QDict *src, const char *key)
485 {
486     QObject *val;
487 
488     if (qdict_haskey(dst, key)) {
489         return;
490     }
491 
492     val = qdict_get(src, key);
493     if (val) {
494         qobject_incref(val);
495         qdict_put_obj(dst, key, val);
496     }
497 }
498 
499 /**
500  * qdict_set_default_str(): If no entry mapped by 'key' exists in 'dst' yet, a
501  * new QString initialised by 'val' is put there.
502  */
503 void qdict_set_default_str(QDict *dst, const char *key, const char *val)
504 {
505     if (qdict_haskey(dst, key)) {
506         return;
507     }
508 
509     qdict_put_str(dst, key, val);
510 }
511 
512 static void qdict_flatten_qdict(QDict *qdict, QDict *target,
513                                 const char *prefix);
514 
515 static void qdict_flatten_qlist(QList *qlist, QDict *target, const char *prefix)
516 {
517     QObject *value;
518     const QListEntry *entry;
519     char *new_key;
520     int i;
521 
522     /* This function is never called with prefix == NULL, i.e., it is always
523      * called from within qdict_flatten_q(list|dict)(). Therefore, it does not
524      * need to remove list entries during the iteration (the whole list will be
525      * deleted eventually anyway from qdict_flatten_qdict()). */
526     assert(prefix);
527 
528     entry = qlist_first(qlist);
529 
530     for (i = 0; entry; entry = qlist_next(entry), i++) {
531         value = qlist_entry_obj(entry);
532         new_key = g_strdup_printf("%s.%i", prefix, i);
533 
534         if (qobject_type(value) == QTYPE_QDICT) {
535             qdict_flatten_qdict(qobject_to_qdict(value), target, new_key);
536         } else if (qobject_type(value) == QTYPE_QLIST) {
537             qdict_flatten_qlist(qobject_to_qlist(value), target, new_key);
538         } else {
539             /* All other types are moved to the target unchanged. */
540             qobject_incref(value);
541             qdict_put_obj(target, new_key, value);
542         }
543 
544         g_free(new_key);
545     }
546 }
547 
548 static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix)
549 {
550     QObject *value;
551     const QDictEntry *entry, *next;
552     char *new_key;
553     bool delete;
554 
555     entry = qdict_first(qdict);
556 
557     while (entry != NULL) {
558 
559         next = qdict_next(qdict, entry);
560         value = qdict_entry_value(entry);
561         new_key = NULL;
562         delete = false;
563 
564         if (prefix) {
565             new_key = g_strdup_printf("%s.%s", prefix, entry->key);
566         }
567 
568         if (qobject_type(value) == QTYPE_QDICT) {
569             /* Entries of QDicts are processed recursively, the QDict object
570              * itself disappears. */
571             qdict_flatten_qdict(qobject_to_qdict(value), target,
572                                 new_key ? new_key : entry->key);
573             delete = true;
574         } else if (qobject_type(value) == QTYPE_QLIST) {
575             qdict_flatten_qlist(qobject_to_qlist(value), target,
576                                 new_key ? new_key : entry->key);
577             delete = true;
578         } else if (prefix) {
579             /* All other objects are moved to the target unchanged. */
580             qobject_incref(value);
581             qdict_put_obj(target, new_key, value);
582             delete = true;
583         }
584 
585         g_free(new_key);
586 
587         if (delete) {
588             qdict_del(qdict, entry->key);
589 
590             /* Restart loop after modifying the iterated QDict */
591             entry = qdict_first(qdict);
592             continue;
593         }
594 
595         entry = next;
596     }
597 }
598 
599 /**
600  * qdict_flatten(): For each nested QDict with key x, all fields with key y
601  * are moved to this QDict and their key is renamed to "x.y". For each nested
602  * QList with key x, the field at index y is moved to this QDict with the key
603  * "x.y" (i.e., the reverse of what qdict_array_split() does).
604  * This operation is applied recursively for nested QDicts and QLists.
605  */
606 void qdict_flatten(QDict *qdict)
607 {
608     qdict_flatten_qdict(qdict, qdict, NULL);
609 }
610 
611 /* extract all the src QDict entries starting by start into dst */
612 void qdict_extract_subqdict(QDict *src, QDict **dst, const char *start)
613 
614 {
615     const QDictEntry *entry, *next;
616     const char *p;
617 
618     *dst = qdict_new();
619     entry = qdict_first(src);
620 
621     while (entry != NULL) {
622         next = qdict_next(src, entry);
623         if (strstart(entry->key, start, &p)) {
624             qobject_incref(entry->value);
625             qdict_put_obj(*dst, p, entry->value);
626             qdict_del(src, entry->key);
627         }
628         entry = next;
629     }
630 }
631 
632 static int qdict_count_prefixed_entries(const QDict *src, const char *start)
633 {
634     const QDictEntry *entry;
635     int count = 0;
636 
637     for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
638         if (strstart(entry->key, start, NULL)) {
639             if (count == INT_MAX) {
640                 return -ERANGE;
641             }
642             count++;
643         }
644     }
645 
646     return count;
647 }
648 
649 /**
650  * qdict_array_split(): This function moves array-like elements of a QDict into
651  * a new QList. Every entry in the original QDict with a key "%u" or one
652  * prefixed "%u.", where %u designates an unsigned integer starting at 0 and
653  * incrementally counting up, will be moved to a new QDict at index %u in the
654  * output QList with the key prefix removed, if that prefix is "%u.". If the
655  * whole key is just "%u", the whole QObject will be moved unchanged without
656  * creating a new QDict. The function terminates when there is no entry in the
657  * QDict with a prefix directly (incrementally) following the last one; it also
658  * returns if there are both entries with "%u" and "%u." for the same index %u.
659  * Example: {"0.a": 42, "0.b": 23, "1.x": 0, "4.y": 1, "o.o": 7, "2": 66}
660  *      (or {"1.x": 0, "4.y": 1, "0.a": 42, "o.o": 7, "0.b": 23, "2": 66})
661  *       => [{"a": 42, "b": 23}, {"x": 0}, 66]
662  *      and {"4.y": 1, "o.o": 7} (remainder of the old QDict)
663  */
664 void qdict_array_split(QDict *src, QList **dst)
665 {
666     unsigned i;
667 
668     *dst = qlist_new();
669 
670     for (i = 0; i < UINT_MAX; i++) {
671         QObject *subqobj;
672         bool is_subqdict;
673         QDict *subqdict;
674         char indexstr[32], prefix[32];
675         size_t snprintf_ret;
676 
677         snprintf_ret = snprintf(indexstr, 32, "%u", i);
678         assert(snprintf_ret < 32);
679 
680         subqobj = qdict_get(src, indexstr);
681 
682         snprintf_ret = snprintf(prefix, 32, "%u.", i);
683         assert(snprintf_ret < 32);
684 
685         /* Overflow is the same as positive non-zero results */
686         is_subqdict = qdict_count_prefixed_entries(src, prefix);
687 
688         // There may be either a single subordinate object (named "%u") or
689         // multiple objects (each with a key prefixed "%u."), but not both.
690         if (!subqobj == !is_subqdict) {
691             break;
692         }
693 
694         if (is_subqdict) {
695             qdict_extract_subqdict(src, &subqdict, prefix);
696             assert(qdict_size(subqdict) > 0);
697         } else {
698             qobject_incref(subqobj);
699             qdict_del(src, indexstr);
700         }
701 
702         qlist_append_obj(*dst, subqobj ?: QOBJECT(subqdict));
703     }
704 }
705 
706 /**
707  * qdict_split_flat_key:
708  * @key: the key string to split
709  * @prefix: non-NULL pointer to hold extracted prefix
710  * @suffix: non-NULL pointer to remaining suffix
711  *
712  * Given a flattened key such as 'foo.0.bar', split it into two parts
713  * at the first '.' separator. Allows double dot ('..') to escape the
714  * normal separator.
715  *
716  * e.g.
717  *    'foo.0.bar' -> prefix='foo' and suffix='0.bar'
718  *    'foo..0.bar' -> prefix='foo.0' and suffix='bar'
719  *
720  * The '..' sequence will be unescaped in the returned 'prefix'
721  * string. The 'suffix' string will be left in escaped format, so it
722  * can be fed back into the qdict_split_flat_key() key as the input
723  * later.
724  *
725  * The caller is responsible for freeing the string returned in @prefix
726  * using g_free().
727  */
728 static void qdict_split_flat_key(const char *key, char **prefix,
729                                  const char **suffix)
730 {
731     const char *separator;
732     size_t i, j;
733 
734     /* Find first '.' separator, but if there is a pair '..'
735      * that acts as an escape, so skip over '..' */
736     separator = NULL;
737     do {
738         if (separator) {
739             separator += 2;
740         } else {
741             separator = key;
742         }
743         separator = strchr(separator, '.');
744     } while (separator && separator[1] == '.');
745 
746     if (separator) {
747         *prefix = g_strndup(key, separator - key);
748         *suffix = separator + 1;
749     } else {
750         *prefix = g_strdup(key);
751         *suffix = NULL;
752     }
753 
754     /* Unescape the '..' sequence into '.' */
755     for (i = 0, j = 0; (*prefix)[i] != '\0'; i++, j++) {
756         if ((*prefix)[i] == '.') {
757             assert((*prefix)[i + 1] == '.');
758             i++;
759         }
760         (*prefix)[j] = (*prefix)[i];
761     }
762     (*prefix)[j] = '\0';
763 }
764 
765 /**
766  * qdict_is_list:
767  * @maybe_list: dict to check if keys represent list elements.
768  *
769  * Determine whether all keys in @maybe_list are valid list elements.
770  * If @maybe_list is non-zero in length and all the keys look like
771  * valid list indexes, this will return 1. If @maybe_list is zero
772  * length or all keys are non-numeric then it will return 0 to indicate
773  * it is a normal qdict. If there is a mix of numeric and non-numeric
774  * keys, or the list indexes are non-contiguous, an error is reported.
775  *
776  * Returns: 1 if a valid list, 0 if a dict, -1 on error
777  */
778 static int qdict_is_list(QDict *maybe_list, Error **errp)
779 {
780     const QDictEntry *ent;
781     ssize_t len = 0;
782     ssize_t max = -1;
783     int is_list = -1;
784     int64_t val;
785 
786     for (ent = qdict_first(maybe_list); ent != NULL;
787          ent = qdict_next(maybe_list, ent)) {
788 
789         if (qemu_strtoi64(ent->key, NULL, 10, &val) == 0) {
790             if (is_list == -1) {
791                 is_list = 1;
792             } else if (!is_list) {
793                 error_setg(errp,
794                            "Cannot mix list and non-list keys");
795                 return -1;
796             }
797             len++;
798             if (val > max) {
799                 max = val;
800             }
801         } else {
802             if (is_list == -1) {
803                 is_list = 0;
804             } else if (is_list) {
805                 error_setg(errp,
806                            "Cannot mix list and non-list keys");
807                 return -1;
808             }
809         }
810     }
811 
812     if (is_list == -1) {
813         assert(!qdict_size(maybe_list));
814         is_list = 0;
815     }
816 
817     /* NB this isn't a perfect check - e.g. it won't catch
818      * a list containing '1', '+1', '01', '3', but that
819      * does not matter - we've still proved that the
820      * input is a list. It is up the caller to do a
821      * stricter check if desired */
822     if (len != (max + 1)) {
823         error_setg(errp, "List indices are not contiguous, "
824                    "saw %zd elements but %zd largest index",
825                    len, max);
826         return -1;
827     }
828 
829     return is_list;
830 }
831 
832 /**
833  * qdict_crumple:
834  * @src: the original flat dictionary (only scalar values) to crumple
835  *
836  * Takes a flat dictionary whose keys use '.' separator to indicate
837  * nesting, and values are scalars, and crumples it into a nested
838  * structure.
839  *
840  * To include a literal '.' in a key name, it must be escaped as '..'
841  *
842  * For example, an input of:
843  *
844  * { 'foo.0.bar': 'one', 'foo.0.wizz': '1',
845  *   'foo.1.bar': 'two', 'foo.1.wizz': '2' }
846  *
847  * will result in an output of:
848  *
849  * {
850  *   'foo': [
851  *      { 'bar': 'one', 'wizz': '1' },
852  *      { 'bar': 'two', 'wizz': '2' }
853  *   ],
854  * }
855  *
856  * The following scenarios in the input dict will result in an
857  * error being returned:
858  *
859  *  - Any values in @src are non-scalar types
860  *  - If keys in @src imply that a particular level is both a
861  *    list and a dict. e.g., "foo.0.bar" and "foo.eek.bar".
862  *  - If keys in @src imply that a particular level is a list,
863  *    but the indices are non-contiguous. e.g. "foo.0.bar" and
864  *    "foo.2.bar" without any "foo.1.bar" present.
865  *  - If keys in @src represent list indexes, but are not in
866  *    the "%zu" format. e.g. "foo.+0.bar"
867  *
868  * Returns: either a QDict or QList for the nested data structure, or NULL
869  * on error
870  */
871 QObject *qdict_crumple(const QDict *src, Error **errp)
872 {
873     const QDictEntry *ent;
874     QDict *two_level, *multi_level = NULL;
875     QObject *dst = NULL, *child;
876     size_t i;
877     char *prefix = NULL;
878     const char *suffix = NULL;
879     int is_list;
880 
881     two_level = qdict_new();
882 
883     /* Step 1: split our totally flat dict into a two level dict */
884     for (ent = qdict_first(src); ent != NULL; ent = qdict_next(src, ent)) {
885         if (qobject_type(ent->value) == QTYPE_QDICT ||
886             qobject_type(ent->value) == QTYPE_QLIST) {
887             error_setg(errp, "Value %s is not a scalar",
888                        ent->key);
889             goto error;
890         }
891 
892         qdict_split_flat_key(ent->key, &prefix, &suffix);
893 
894         child = qdict_get(two_level, prefix);
895         if (suffix) {
896             if (child) {
897                 if (qobject_type(child) != QTYPE_QDICT) {
898                     error_setg(errp, "Key %s prefix is already set as a scalar",
899                                prefix);
900                     goto error;
901                 }
902             } else {
903                 child = QOBJECT(qdict_new());
904                 qdict_put_obj(two_level, prefix, child);
905             }
906             qobject_incref(ent->value);
907             qdict_put_obj(qobject_to_qdict(child), suffix, ent->value);
908         } else {
909             if (child) {
910                 error_setg(errp, "Key %s prefix is already set as a dict",
911                            prefix);
912                 goto error;
913             }
914             qobject_incref(ent->value);
915             qdict_put_obj(two_level, prefix, ent->value);
916         }
917 
918         g_free(prefix);
919         prefix = NULL;
920     }
921 
922     /* Step 2: optionally process the two level dict recursively
923      * into a multi-level dict */
924     multi_level = qdict_new();
925     for (ent = qdict_first(two_level); ent != NULL;
926          ent = qdict_next(two_level, ent)) {
927 
928         if (qobject_type(ent->value) == QTYPE_QDICT) {
929             child = qdict_crumple(qobject_to_qdict(ent->value), errp);
930             if (!child) {
931                 goto error;
932             }
933 
934             qdict_put_obj(multi_level, ent->key, child);
935         } else {
936             qobject_incref(ent->value);
937             qdict_put_obj(multi_level, ent->key, ent->value);
938         }
939     }
940     QDECREF(two_level);
941     two_level = NULL;
942 
943     /* Step 3: detect if we need to turn our dict into list */
944     is_list = qdict_is_list(multi_level, errp);
945     if (is_list < 0) {
946         goto error;
947     }
948 
949     if (is_list) {
950         dst = QOBJECT(qlist_new());
951 
952         for (i = 0; i < qdict_size(multi_level); i++) {
953             char *key = g_strdup_printf("%zu", i);
954 
955             child = qdict_get(multi_level, key);
956             g_free(key);
957 
958             if (!child) {
959                 error_setg(errp, "Missing list index %zu", i);
960                 goto error;
961             }
962 
963             qobject_incref(child);
964             qlist_append_obj(qobject_to_qlist(dst), child);
965         }
966         QDECREF(multi_level);
967         multi_level = NULL;
968     } else {
969         dst = QOBJECT(multi_level);
970     }
971 
972     return dst;
973 
974  error:
975     g_free(prefix);
976     QDECREF(multi_level);
977     QDECREF(two_level);
978     qobject_decref(dst);
979     return NULL;
980 }
981 
982 /**
983  * qdict_array_entries(): Returns the number of direct array entries if the
984  * sub-QDict of src specified by the prefix in subqdict (or src itself for
985  * prefix == "") is valid as an array, i.e. the length of the created list if
986  * the sub-QDict would become empty after calling qdict_array_split() on it. If
987  * the array is not valid, -EINVAL is returned.
988  */
989 int qdict_array_entries(QDict *src, const char *subqdict)
990 {
991     const QDictEntry *entry;
992     unsigned i;
993     unsigned entries = 0;
994     size_t subqdict_len = strlen(subqdict);
995 
996     assert(!subqdict_len || subqdict[subqdict_len - 1] == '.');
997 
998     /* qdict_array_split() loops until UINT_MAX, but as we want to return
999      * negative errors, we only have a signed return value here. Any additional
1000      * entries will lead to -EINVAL. */
1001     for (i = 0; i < INT_MAX; i++) {
1002         QObject *subqobj;
1003         int subqdict_entries;
1004         char *prefix = g_strdup_printf("%s%u.", subqdict, i);
1005 
1006         subqdict_entries = qdict_count_prefixed_entries(src, prefix);
1007 
1008         /* Remove ending "." */
1009         prefix[strlen(prefix) - 1] = 0;
1010         subqobj = qdict_get(src, prefix);
1011 
1012         g_free(prefix);
1013 
1014         if (subqdict_entries < 0) {
1015             return subqdict_entries;
1016         }
1017 
1018         /* There may be either a single subordinate object (named "%u") or
1019          * multiple objects (each with a key prefixed "%u."), but not both. */
1020         if (subqobj && subqdict_entries) {
1021             return -EINVAL;
1022         } else if (!subqobj && !subqdict_entries) {
1023             break;
1024         }
1025 
1026         entries += subqdict_entries ? subqdict_entries : 1;
1027     }
1028 
1029     /* Consider everything handled that isn't part of the given sub-QDict */
1030     for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) {
1031         if (!strstart(qdict_entry_key(entry), subqdict, NULL)) {
1032             entries++;
1033         }
1034     }
1035 
1036     /* Anything left in the sub-QDict that wasn't handled? */
1037     if (qdict_size(src) != entries) {
1038         return -EINVAL;
1039     }
1040 
1041     return i;
1042 }
1043 
1044 /**
1045  * qdict_join(): Absorb the src QDict into the dest QDict, that is, move all
1046  * elements from src to dest.
1047  *
1048  * If an element from src has a key already present in dest, it will not be
1049  * moved unless overwrite is true.
1050  *
1051  * If overwrite is true, the conflicting values in dest will be discarded and
1052  * replaced by the corresponding values from src.
1053  *
1054  * Therefore, with overwrite being true, the src QDict will always be empty when
1055  * this function returns. If overwrite is false, the src QDict will be empty
1056  * iff there were no conflicts.
1057  */
1058 void qdict_join(QDict *dest, QDict *src, bool overwrite)
1059 {
1060     const QDictEntry *entry, *next;
1061 
1062     entry = qdict_first(src);
1063     while (entry) {
1064         next = qdict_next(src, entry);
1065 
1066         if (overwrite || !qdict_haskey(dest, entry->key)) {
1067             qobject_incref(entry->value);
1068             qdict_put_obj(dest, entry->key, entry->value);
1069             qdict_del(src, entry->key);
1070         }
1071 
1072         entry = next;
1073     }
1074 }
1075