xref: /openbmc/qemu/qobject/qdict.c (revision fe7f9b8e)
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  * tdb_hash(): based on the hash agorithm from gdbm, via tdb
42  * (from module-init-tools)
43  */
44 static unsigned int tdb_hash(const char *name)
45 {
46     unsigned value;	/* Used to compute the hash value.  */
47     unsigned   i;	/* Used to cycle through random values. */
48 
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)));
52 
53     return (1103515243 * value + 12345);
54 }
55 
56 /**
57  * alloc_entry(): allocate a new QDictEntry
58  */
59 static QDictEntry *alloc_entry(const char *key, QObject *value)
60 {
61     QDictEntry *entry;
62 
63     entry = g_malloc0(sizeof(*entry));
64     entry->key = g_strdup(key);
65     entry->value = value;
66 
67     return entry;
68 }
69 
70 /**
71  * qdict_entry_value(): Return qdict entry value
72  *
73  * Return weak reference.
74  */
75 QObject *qdict_entry_value(const QDictEntry *entry)
76 {
77     return entry->value;
78 }
79 
80 /**
81  * qdict_entry_key(): Return qdict entry key
82  *
83  * Return a *pointer* to the string, it has to be duplicated before being
84  * stored.
85  */
86 const char *qdict_entry_key(const QDictEntry *entry)
87 {
88     return entry->key;
89 }
90 
91 /**
92  * qdict_find(): List lookup function
93  */
94 static QDictEntry *qdict_find(const QDict *qdict,
95                               const char *key, unsigned int bucket)
96 {
97     QDictEntry *entry;
98 
99     QLIST_FOREACH(entry, &qdict->table[bucket], next)
100         if (!strcmp(entry->key, key))
101             return entry;
102 
103     return NULL;
104 }
105 
106 /**
107  * qdict_put_obj(): Put a new QObject into the dictionary
108  *
109  * Insert the pair 'key:value' into 'qdict', if 'key' already exists
110  * its 'value' will be replaced.
111  *
112  * This is done by freeing the reference to the stored QObject and
113  * storing the new one in the same entry.
114  *
115  * NOTE: ownership of 'value' is transferred to the QDict
116  */
117 void qdict_put_obj(QDict *qdict, const char *key, QObject *value)
118 {
119     unsigned int bucket;
120     QDictEntry *entry;
121 
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++;
133     }
134 }
135 
136 void qdict_put_int(QDict *qdict, const char *key, int64_t value)
137 {
138     qdict_put(qdict, key, qnum_from_int(value));
139 }
140 
141 void qdict_put_bool(QDict *qdict, const char *key, bool value)
142 {
143     qdict_put(qdict, key, qbool_from_bool(value));
144 }
145 
146 void qdict_put_str(QDict *qdict, const char *key, const char *value)
147 {
148     qdict_put(qdict, key, qstring_from_str(value));
149 }
150 
151 void qdict_put_null(QDict *qdict, const char *key)
152 {
153     qdict_put(qdict, key, qnull());
154 }
155 
156 /**
157  * qdict_get(): Lookup for a given 'key'
158  *
159  * Return a weak reference to the QObject associated with 'key' if
160  * 'key' is present in the dictionary, NULL otherwise.
161  */
162 QObject *qdict_get(const QDict *qdict, const char *key)
163 {
164     QDictEntry *entry;
165 
166     entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
167     return (entry == NULL ? NULL : entry->value);
168 }
169 
170 /**
171  * qdict_haskey(): Check if 'key' exists
172  *
173  * Return 1 if 'key' exists in the dict, 0 otherwise
174  */
175 int qdict_haskey(const QDict *qdict, const char *key)
176 {
177     unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
178     return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1);
179 }
180 
181 /**
182  * qdict_size(): Return the size of the dictionary
183  */
184 size_t qdict_size(const QDict *qdict)
185 {
186     return qdict->size;
187 }
188 
189 /**
190  * qdict_get_double(): Get an number mapped by 'key'
191  *
192  * This function assumes that 'key' exists and it stores a QNum.
193  *
194  * Return number mapped by 'key'.
195  */
196 double qdict_get_double(const QDict *qdict, const char *key)
197 {
198     return qnum_get_double(qobject_to(QNum, qdict_get(qdict, key)));
199 }
200 
201 /**
202  * qdict_get_int(): Get an integer mapped by 'key'
203  *
204  * This function assumes that 'key' exists and it stores a
205  * QNum representable as int.
206  *
207  * Return integer mapped by 'key'.
208  */
209 int64_t qdict_get_int(const QDict *qdict, const char *key)
210 {
211     return qnum_get_int(qobject_to(QNum, qdict_get(qdict, key)));
212 }
213 
214 /**
215  * qdict_get_bool(): Get a bool mapped by 'key'
216  *
217  * This function assumes that 'key' exists and it stores a
218  * QBool object.
219  *
220  * Return bool mapped by 'key'.
221  */
222 bool qdict_get_bool(const QDict *qdict, const char *key)
223 {
224     return qbool_get_bool(qobject_to(QBool, qdict_get(qdict, key)));
225 }
226 
227 /**
228  * qdict_get_qlist(): If @qdict maps @key to a QList, return it, else NULL.
229  */
230 QList *qdict_get_qlist(const QDict *qdict, const char *key)
231 {
232     return qobject_to(QList, qdict_get(qdict, key));
233 }
234 
235 /**
236  * qdict_get_qdict(): If @qdict maps @key to a QDict, return it, else NULL.
237  */
238 QDict *qdict_get_qdict(const QDict *qdict, const char *key)
239 {
240     return qobject_to(QDict, qdict_get(qdict, key));
241 }
242 
243 /**
244  * qdict_get_str(): Get a pointer to the stored string mapped
245  * by 'key'
246  *
247  * This function assumes that 'key' exists and it stores a
248  * QString object.
249  *
250  * Return pointer to the string mapped by 'key'.
251  */
252 const char *qdict_get_str(const QDict *qdict, const char *key)
253 {
254     return qstring_get_str(qobject_to(QString, qdict_get(qdict, key)));
255 }
256 
257 /**
258  * qdict_get_try_int(): Try to get integer mapped by 'key'
259  *
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.
263  */
264 int64_t qdict_get_try_int(const QDict *qdict, const char *key,
265                           int64_t def_value)
266 {
267     QNum *qnum = qobject_to(QNum, qdict_get(qdict, key));
268     int64_t val;
269 
270     if (!qnum || !qnum_get_try_int(qnum, &val)) {
271         return def_value;
272     }
273 
274     return val;
275 }
276 
277 /**
278  * qdict_get_try_bool(): Try to get a bool mapped by 'key'
279  *
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.
283  */
284 bool qdict_get_try_bool(const QDict *qdict, const char *key, bool def_value)
285 {
286     QBool *qbool = qobject_to(QBool, qdict_get(qdict, key));
287 
288     return qbool ? qbool_get_bool(qbool) : def_value;
289 }
290 
291 /**
292  * qdict_get_try_str(): Try to get a pointer to the stored string
293  * mapped by 'key'
294  *
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.
298  */
299 const char *qdict_get_try_str(const QDict *qdict, const char *key)
300 {
301     QString *qstr = qobject_to(QString, qdict_get(qdict, key));
302 
303     return qstr ? qstring_get_str(qstr) : NULL;
304 }
305 
306 /**
307  * qdict_iter(): Iterate over all the dictionary's stored values.
308  *
309  * This function allows the user to provide an iterator, which will be
310  * called for each stored value in the dictionary.
311  */
312 void qdict_iter(const QDict *qdict,
313                 void (*iter)(const char *key, QObject *obj, void *opaque),
314                 void *opaque)
315 {
316     int i;
317     QDictEntry *entry;
318 
319     for (i = 0; i < QDICT_BUCKET_MAX; i++) {
320         QLIST_FOREACH(entry, &qdict->table[i], next)
321             iter(entry->key, entry->value, opaque);
322     }
323 }
324 
325 static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket)
326 {
327     int i;
328 
329     for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) {
330         if (!QLIST_EMPTY(&qdict->table[i])) {
331             return QLIST_FIRST(&qdict->table[i]);
332         }
333     }
334 
335     return NULL;
336 }
337 
338 /**
339  * qdict_first(): Return first qdict entry for iteration.
340  */
341 const QDictEntry *qdict_first(const QDict *qdict)
342 {
343     return qdict_next_entry(qdict, 0);
344 }
345 
346 /**
347  * qdict_next(): Return next qdict entry in an iteration.
348  */
349 const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry)
350 {
351     QDictEntry *ret;
352 
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);
357     }
358 
359     return ret;
360 }
361 
362 /**
363  * qdict_clone_shallow(): Clones a given QDict. Its entries are not copied, but
364  * another reference is added.
365  */
366 QDict *qdict_clone_shallow(const QDict *src)
367 {
368     QDict *dest;
369     QDictEntry *entry;
370     int i;
371 
372     dest = qdict_new();
373 
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));
377         }
378     }
379 
380     return dest;
381 }
382 
383 /**
384  * qentry_destroy(): Free all the memory allocated by a QDictEntry
385  */
386 static void qentry_destroy(QDictEntry *e)
387 {
388     assert(e != NULL);
389     assert(e->key != NULL);
390     assert(e->value != NULL);
391 
392     qobject_unref(e->value);
393     g_free(e->key);
394     g_free(e);
395 }
396 
397 /**
398  * qdict_del(): Delete a 'key:value' pair from the dictionary
399  *
400  * This will destroy all data allocated by this entry.
401  */
402 void qdict_del(QDict *qdict, const char *key)
403 {
404     QDictEntry *entry;
405 
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--;
411     }
412 }
413 
414 /**
415  * qdict_is_equal(): Test whether the two QDicts are equal
416  *
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).
420  */
421 bool qdict_is_equal(const QObject *x, const QObject *y)
422 {
423     const QDict *dict_x = qobject_to(QDict, x);
424     const QDict *dict_y = qobject_to(QDict, y);
425     const QDictEntry *e;
426 
427     if (qdict_size(dict_x) != qdict_size(dict_y)) {
428         return false;
429     }
430 
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));
434 
435         if (!qobject_is_equal(obj_x, obj_y)) {
436             return false;
437         }
438     }
439 
440     return true;
441 }
442 
443 /**
444  * qdict_destroy_obj(): Free all the memory allocated by a QDict
445  */
446 void qdict_destroy_obj(QObject *obj)
447 {
448     int i;
449     QDict *qdict;
450 
451     assert(obj != NULL);
452     qdict = qobject_to(QDict, obj);
453 
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;
461         }
462     }
463 
464     g_free(qdict);
465 }
466 
467 /**
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).
471  */
472 void qdict_copy_default(QDict *dst, QDict *src, const char *key)
473 {
474     QObject *val;
475 
476     if (qdict_haskey(dst, key)) {
477         return;
478     }
479 
480     val = qdict_get(src, key);
481     if (val) {
482         qdict_put_obj(dst, key, qobject_ref(val));
483     }
484 }
485 
486 /**
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.
489  */
490 void qdict_set_default_str(QDict *dst, const char *key, const char *val)
491 {
492     if (qdict_haskey(dst, key)) {
493         return;
494     }
495 
496     qdict_put_str(dst, key, val);
497 }
498 
499 static void qdict_flatten_qdict(QDict *qdict, QDict *target,
500                                 const char *prefix);
501 
502 static void qdict_flatten_qlist(QList *qlist, QDict *target, const char *prefix)
503 {
504     QObject *value;
505     const QListEntry *entry;
506     char *new_key;
507     int i;
508 
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);
514 
515     entry = qlist_first(qlist);
516 
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);
520 
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));
528         }
529 
530         g_free(new_key);
531     }
532 }
533 
534 static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix)
535 {
536     QObject *value;
537     const QDictEntry *entry, *next;
538     char *new_key;
539     bool delete;
540 
541     entry = qdict_first(qdict);
542 
543     while (entry != NULL) {
544 
545         next = qdict_next(qdict, entry);
546         value = qdict_entry_value(entry);
547         new_key = NULL;
548         delete = false;
549 
550         if (prefix) {
551             new_key = g_strdup_printf("%s.%s", prefix, entry->key);
552         }
553 
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;
568         }
569 
570         g_free(new_key);
571 
572         if (delete) {
573             qdict_del(qdict, entry->key);
574 
575             /* Restart loop after modifying the iterated QDict */
576             entry = qdict_first(qdict);
577             continue;
578         }
579 
580         entry = next;
581     }
582 }
583 
584 /**
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.
590  */
591 void qdict_flatten(QDict *qdict)
592 {
593     qdict_flatten_qdict(qdict, qdict, NULL);
594 }
595 
596 /* extract all the src QDict entries starting by start into dst */
597 void qdict_extract_subqdict(QDict *src, QDict **dst, const char *start)
598 
599 {
600     const QDictEntry *entry, *next;
601     const char *p;
602 
603     *dst = qdict_new();
604     entry = qdict_first(src);
605 
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);
611         }
612         entry = next;
613     }
614 }
615 
616 static int qdict_count_prefixed_entries(const QDict *src, const char *start)
617 {
618     const QDictEntry *entry;
619     int count = 0;
620 
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;
625             }
626             count++;
627         }
628     }
629 
630     return count;
631 }
632 
633 /**
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)
647  */
648 void qdict_array_split(QDict *src, QList **dst)
649 {
650     unsigned i;
651 
652     *dst = qlist_new();
653 
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;
660 
661         snprintf_ret = snprintf(indexstr, 32, "%u", i);
662         assert(snprintf_ret < 32);
663 
664         subqobj = qdict_get(src, indexstr);
665 
666         snprintf_ret = snprintf(prefix, 32, "%u.", i);
667         assert(snprintf_ret < 32);
668 
669         /* Overflow is the same as positive non-zero results */
670         is_subqdict = qdict_count_prefixed_entries(src, prefix);
671 
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;
676         }
677 
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);
684         }
685 
686         qlist_append_obj(*dst, subqobj ?: QOBJECT(subqdict));
687     }
688 }
689 
690 /**
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
695  *
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.
699  *
700  * e.g.
701  *    'foo.0.bar' -> prefix='foo' and suffix='0.bar'
702  *    'foo..0.bar' -> prefix='foo.0' and suffix='bar'
703  *
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.
708  *
709  * The caller is responsible for freeing the string returned in @prefix
710  * using g_free().
711  */
712 static void qdict_split_flat_key(const char *key, char **prefix,
713                                  const char **suffix)
714 {
715     const char *separator;
716     size_t i, j;
717 
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;
726         }
727         separator = strchr(separator, '.');
728     } while (separator && separator[1] == '.');
729 
730     if (separator) {
731         *prefix = g_strndup(key, separator - key);
732         *suffix = separator + 1;
733     } else {
734         *prefix = g_strdup(key);
735         *suffix = NULL;
736     }
737 
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++;
743         }
744         (*prefix)[j] = (*prefix)[i];
745     }
746     (*prefix)[j] = '\0';
747 }
748 
749 /**
750  * qdict_is_list:
751  * @maybe_list: dict to check if keys represent list elements.
752  *
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.
759  *
760  * Returns: 1 if a valid list, 0 if a dict, -1 on error
761  */
762 static int qdict_is_list(QDict *maybe_list, Error **errp)
763 {
764     const QDictEntry *ent;
765     ssize_t len = 0;
766     ssize_t max = -1;
767     int is_list = -1;
768     int64_t val;
769 
770     for (ent = qdict_first(maybe_list); ent != NULL;
771          ent = qdict_next(maybe_list, ent)) {
772 
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;
780             }
781             len++;
782             if (val > max) {
783                 max = val;
784             }
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;
792             }
793         }
794     }
795 
796     if (is_list == -1) {
797         assert(!qdict_size(maybe_list));
798         is_list = 0;
799     }
800 
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;
811     }
812 
813     return is_list;
814 }
815 
816 /**
817  * qdict_crumple:
818  * @src: the original flat dictionary (only scalar values) to crumple
819  *
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.
823  *
824  * To include a literal '.' in a key name, it must be escaped as '..'
825  *
826  * For example, an input of:
827  *
828  * { 'foo.0.bar': 'one', 'foo.0.wizz': '1',
829  *   'foo.1.bar': 'two', 'foo.1.wizz': '2' }
830  *
831  * will result in an output of:
832  *
833  * {
834  *   'foo': [
835  *      { 'bar': 'one', 'wizz': '1' },
836  *      { 'bar': 'two', 'wizz': '2' }
837  *   ],
838  * }
839  *
840  * The following scenarios in the input dict will result in an
841  * error being returned:
842  *
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"
851  *
852  * Returns: either a QDict or QList for the nested data structure, or NULL
853  * on error
854  */
855 QObject *qdict_crumple(const QDict *src, Error **errp)
856 {
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;
864 
865     two_level = qdict_new();
866 
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;
874         }
875 
876         qdict_split_flat_key(ent->key, &prefix, &suffix);
877 
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;
886                 }
887 
888                 child_dict = qdict_new();
889                 qdict_put_obj(two_level, prefix, QOBJECT(child_dict));
890             }
891 
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;
898             }
899             qdict_put_obj(two_level, prefix, qobject_ref(ent->value));
900         }
901 
902         g_free(prefix);
903         prefix = NULL;
904     }
905 
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;
916             }
917 
918             qdict_put_obj(multi_level, ent->key, child);
919         } else {
920             qdict_put_obj(multi_level, ent->key, qobject_ref(ent->value));
921         }
922     }
923     qobject_unref(two_level);
924     two_level = NULL;
925 
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;
930     }
931 
932     if (is_list) {
933         dst = QOBJECT(qlist_new());
934 
935         for (i = 0; i < qdict_size(multi_level); i++) {
936             char *key = g_strdup_printf("%zu", i);
937 
938             child = qdict_get(multi_level, key);
939             g_free(key);
940 
941             if (!child) {
942                 error_setg(errp, "Missing list index %zu", i);
943                 goto error;
944             }
945 
946             qlist_append_obj(qobject_to(QList, dst), qobject_ref(child));
947         }
948         qobject_unref(multi_level);
949         multi_level = NULL;
950     } else {
951         dst = QOBJECT(multi_level);
952     }
953 
954     return dst;
955 
956  error:
957     g_free(prefix);
958     qobject_unref(multi_level);
959     qobject_unref(two_level);
960     qobject_unref(dst);
961     return NULL;
962 }
963 
964 /**
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.
970  */
971 int qdict_array_entries(QDict *src, const char *subqdict)
972 {
973     const QDictEntry *entry;
974     unsigned i;
975     unsigned entries = 0;
976     size_t subqdict_len = strlen(subqdict);
977 
978     assert(!subqdict_len || subqdict[subqdict_len - 1] == '.');
979 
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);
987 
988         subqdict_entries = qdict_count_prefixed_entries(src, prefix);
989 
990         /* Remove ending "." */
991         prefix[strlen(prefix) - 1] = 0;
992         subqobj = qdict_get(src, prefix);
993 
994         g_free(prefix);
995 
996         if (subqdict_entries < 0) {
997             return subqdict_entries;
998         }
999 
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;
1006         }
1007 
1008         entries += subqdict_entries ? subqdict_entries : 1;
1009     }
1010 
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++;
1015         }
1016     }
1017 
1018     /* Anything left in the sub-QDict that wasn't handled? */
1019     if (qdict_size(src) != entries) {
1020         return -EINVAL;
1021     }
1022 
1023     return i;
1024 }
1025 
1026 /**
1027  * qdict_join(): Absorb the src QDict into the dest QDict, that is, move all
1028  * elements from src to dest.
1029  *
1030  * If an element from src has a key already present in dest, it will not be
1031  * moved unless overwrite is true.
1032  *
1033  * If overwrite is true, the conflicting values in dest will be discarded and
1034  * replaced by the corresponding values from src.
1035  *
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.
1039  */
1040 void qdict_join(QDict *dest, QDict *src, bool overwrite)
1041 {
1042     const QDictEntry *entry, *next;
1043 
1044     entry = qdict_first(src);
1045     while (entry) {
1046         next = qdict_next(src, entry);
1047 
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);
1051         }
1052 
1053         entry = next;
1054     }
1055 }
1056 
1057 /**
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.
1061  *
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.
1065  *
1066  * Returns true for success, false in error cases.
1067  */
1068 bool qdict_rename_keys(QDict *qdict, const QDictRenames *renames, Error **errp)
1069 {
1070     QObject *qobj;
1071 
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;
1078             }
1079 
1080             qobj = qdict_get(qdict, renames->from);
1081             qdict_put_obj(qdict, renames->to, qobject_ref(qobj));
1082             qdict_del(qdict, renames->from);
1083         }
1084 
1085         renames++;
1086     }
1087     return true;
1088 }
1089