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