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