1 /*
2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 *
18 * Author: Ryan Lortie <desrt@desrt.ca>
19 */
20
21 /* Prologue {{{1 */
22
23 #include "config.h"
24
25 #include <glib/gvariant-serialiser.h>
26 #include "gvariant-internal.h"
27 #include <glib/gvariant-core.h>
28 #include <glib/gtestutils.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gslice.h>
31 #include <glib/ghash.h>
32 #include <glib/gmem.h>
33
34 #include <string.h>
35
36
37 /**
38 * SECTION:gvariant
39 * @title: GVariant
40 * @short_description: strongly typed value datatype
41 * @see_also: GVariantType
42 *
43 * #GVariant is a variant datatype; it can contain one or more values
44 * along with information about the type of the values.
45 *
46 * A #GVariant may contain simple types, like an integer, or a boolean value;
47 * or complex types, like an array of two strings, or a dictionary of key
48 * value pairs. A #GVariant is also immutable: once it's been created neither
49 * its type nor its content can be modified further.
50 *
51 * GVariant is useful whenever data needs to be serialized, for example when
52 * sending method parameters in DBus, or when saving settings using GSettings.
53 *
54 * When creating a new #GVariant, you pass the data you want to store in it
55 * along with a string representing the type of data you wish to pass to it.
56 *
57 * For instance, if you want to create a #GVariant holding an integer value you
58 * can use:
59 *
60 * |[<!-- language="C" -->
61 * GVariant *v = g_variant_new ("u", 40);
62 * ]|
63 *
64 * The string "u" in the first argument tells #GVariant that the data passed to
65 * the constructor (40) is going to be an unsigned integer.
66 *
67 * More advanced examples of #GVariant in use can be found in documentation for
68 * [GVariant format strings][gvariant-format-strings-pointers].
69 *
70 * The range of possible values is determined by the type.
71 *
72 * The type system used by #GVariant is #GVariantType.
73 *
74 * #GVariant instances always have a type and a value (which are given
75 * at construction time). The type and value of a #GVariant instance
76 * can never change other than by the #GVariant itself being
77 * destroyed. A #GVariant cannot contain a pointer.
78 *
79 * #GVariant is reference counted using g_variant_ref() and
80 * g_variant_unref(). #GVariant also has floating reference counts --
81 * see g_variant_ref_sink().
82 *
83 * #GVariant is completely threadsafe. A #GVariant instance can be
84 * concurrently accessed in any way from any number of threads without
85 * problems.
86 *
87 * #GVariant is heavily optimised for dealing with data in serialised
88 * form. It works particularly well with data located in memory-mapped
89 * files. It can perform nearly all deserialisation operations in a
90 * small constant time, usually touching only a single memory page.
91 * Serialised #GVariant data can also be sent over the network.
92 *
93 * #GVariant is largely compatible with D-Bus. Almost all types of
94 * #GVariant instances can be sent over D-Bus. See #GVariantType for
95 * exceptions. (However, #GVariant's serialisation format is not the same
96 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
97 * in the gio library, for those.)
98 *
99 * For space-efficiency, the #GVariant serialisation format does not
100 * automatically include the variant's length, type or endianness,
101 * which must either be implied from context (such as knowledge that a
102 * particular file format always contains a little-endian
103 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
104 * or supplied out-of-band (for instance, a length, type and/or endianness
105 * indicator could be placed at the beginning of a file, network message
106 * or network stream).
107 *
108 * A #GVariant's size is limited mainly by any lower level operating
109 * system constraints, such as the number of bits in #gsize. For
110 * example, it is reasonable to have a 2GB file mapped into memory
111 * with #GMappedFile, and call g_variant_new_from_data() on it.
112 *
113 * For convenience to C programmers, #GVariant features powerful
114 * varargs-based value construction and destruction. This feature is
115 * designed to be embedded in other libraries.
116 *
117 * There is a Python-inspired text language for describing #GVariant
118 * values. #GVariant includes a printer for this language and a parser
119 * with type inferencing.
120 *
121 * ## Memory Use
122 *
123 * #GVariant tries to be quite efficient with respect to memory use.
124 * This section gives a rough idea of how much memory is used by the
125 * current implementation. The information here is subject to change
126 * in the future.
127 *
128 * The memory allocated by #GVariant can be grouped into 4 broad
129 * purposes: memory for serialised data, memory for the type
130 * information cache, buffer management memory and memory for the
131 * #GVariant structure itself.
132 *
133 * ## Serialised Data Memory
134 *
135 * This is the memory that is used for storing GVariant data in
136 * serialised form. This is what would be sent over the network or
137 * what would end up on disk, not counting any indicator of the
138 * endianness, or of the length or type of the top-level variant.
139 *
140 * The amount of memory required to store a boolean is 1 byte. 16,
141 * 32 and 64 bit integers and double precision floating point numbers
142 * use their "natural" size. Strings (including object path and
143 * signature strings) are stored with a nul terminator, and as such
144 * use the length of the string plus 1 byte.
145 *
146 * Maybe types use no space at all to represent the null value and
147 * use the same amount of space (sometimes plus one byte) as the
148 * equivalent non-maybe-typed value to represent the non-null case.
149 *
150 * Arrays use the amount of space required to store each of their
151 * members, concatenated. Additionally, if the items stored in an
152 * array are not of a fixed-size (ie: strings, other arrays, etc)
153 * then an additional framing offset is stored for each item. The
154 * size of this offset is either 1, 2 or 4 bytes depending on the
155 * overall size of the container. Additionally, extra padding bytes
156 * are added as required for alignment of child values.
157 *
158 * Tuples (including dictionary entries) use the amount of space
159 * required to store each of their members, concatenated, plus one
160 * framing offset (as per arrays) for each non-fixed-sized item in
161 * the tuple, except for the last one. Additionally, extra padding
162 * bytes are added as required for alignment of child values.
163 *
164 * Variants use the same amount of space as the item inside of the
165 * variant, plus 1 byte, plus the length of the type string for the
166 * item inside the variant.
167 *
168 * As an example, consider a dictionary mapping strings to variants.
169 * In the case that the dictionary is empty, 0 bytes are required for
170 * the serialisation.
171 *
172 * If we add an item "width" that maps to the int32 value of 500 then
173 * we will use 4 byte to store the int32 (so 6 for the variant
174 * containing it) and 6 bytes for the string. The variant must be
175 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
176 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
177 * for the dictionary entry. An additional 1 byte is added to the
178 * array as a framing offset making a total of 15 bytes.
179 *
180 * If we add another entry, "title" that maps to a nullable string
181 * that happens to have a value of null, then we use 0 bytes for the
182 * null value (and 3 bytes for the variant to contain it along with
183 * its type string) plus 6 bytes for the string. Again, we need 2
184 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
185 *
186 * We now require extra padding between the two items in the array.
187 * After the 14 bytes of the first item, that's 2 bytes required.
188 * We now require 2 framing offsets for an extra two
189 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
190 * dictionary.
191 *
192 * ## Type Information Cache
193 *
194 * For each GVariant type that currently exists in the program a type
195 * information structure is kept in the type information cache. The
196 * type information structure is required for rapid deserialisation.
197 *
198 * Continuing with the above example, if a #GVariant exists with the
199 * type "a{sv}" then a type information struct will exist for
200 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
201 * will share the same type information. Additionally, all
202 * single-digit types are stored in read-only static memory and do
203 * not contribute to the writable memory footprint of a program using
204 * #GVariant.
205 *
206 * Aside from the type information structures stored in read-only
207 * memory, there are two forms of type information. One is used for
208 * container types where there is a single element type: arrays and
209 * maybe types. The other is used for container types where there
210 * are multiple element types: tuples and dictionary entries.
211 *
212 * Array type info structures are 6 * sizeof (void *), plus the
213 * memory required to store the type string itself. This means that
214 * on 32-bit systems, the cache entry for "a{sv}" would require 30
215 * bytes of memory (plus malloc overhead).
216 *
217 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
218 * sizeof (void *) for each item in the tuple, plus the memory
219 * required to store the type string itself. A 2-item tuple, for
220 * example, would have a type information structure that consumed
221 * writable memory in the size of 14 * sizeof (void *) (plus type
222 * string) This means that on 32-bit systems, the cache entry for
223 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
224 *
225 * This means that in total, for our "a{sv}" example, 91 bytes of
226 * type information would be allocated.
227 *
228 * The type information cache, additionally, uses a #GHashTable to
229 * store and look up the cached items and stores a pointer to this
230 * hash table in static storage. The hash table is freed when there
231 * are zero items in the type cache.
232 *
233 * Although these sizes may seem large it is important to remember
234 * that a program will probably only have a very small number of
235 * different types of values in it and that only one type information
236 * structure is required for many different values of the same type.
237 *
238 * ## Buffer Management Memory
239 *
240 * #GVariant uses an internal buffer management structure to deal
241 * with the various different possible sources of serialised data
242 * that it uses. The buffer is responsible for ensuring that the
243 * correct call is made when the data is no longer in use by
244 * #GVariant. This may involve a g_free() or a g_slice_free() or
245 * even g_mapped_file_unref().
246 *
247 * One buffer management structure is used for each chunk of
248 * serialised data. The size of the buffer management structure
249 * is 4 * (void *). On 32-bit systems, that's 16 bytes.
250 *
251 * ## GVariant structure
252 *
253 * The size of a #GVariant structure is 6 * (void *). On 32-bit
254 * systems, that's 24 bytes.
255 *
256 * #GVariant structures only exist if they are explicitly created
257 * with API calls. For example, if a #GVariant is constructed out of
258 * serialised data for the example given above (with the dictionary)
259 * then although there are 9 individual values that comprise the
260 * entire dictionary (two keys, two values, two variants containing
261 * the values, two dictionary entries, plus the dictionary itself),
262 * only 1 #GVariant instance exists -- the one referring to the
263 * dictionary.
264 *
265 * If calls are made to start accessing the other values then
266 * #GVariant instances will exist for those values only for as long
267 * as they are in use (ie: until you call g_variant_unref()). The
268 * type information is shared. The serialised data and the buffer
269 * management structure for that serialised data is shared by the
270 * child.
271 *
272 * ## Summary
273 *
274 * To put the entire example together, for our dictionary mapping
275 * strings to variants (with two entries, as given above), we are
276 * using 91 bytes of memory for type information, 29 bytes of memory
277 * for the serialised data, 16 bytes for buffer management and 24
278 * bytes for the #GVariant instance, or a total of 160 bytes, plus
279 * malloc overhead. If we were to use g_variant_get_child_value() to
280 * access the two dictionary entries, we would use an additional 48
281 * bytes. If we were to have other dictionaries of the same type, we
282 * would use more memory for the serialised data and buffer
283 * management for those dictionaries, but the type information would
284 * be shared.
285 */
286
287 /* definition of GVariant structure is in gvariant-core.c */
288
289 /* this is a g_return_val_if_fail() for making
290 * sure a (GVariant *) has the required type.
291 */
292 #define TYPE_CHECK(value, TYPE, val) \
293 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
294 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
295 "g_variant_is_of_type (" #value \
296 ", " #TYPE ")"); \
297 return val; \
298 }
299
300 /* Numeric Type Constructor/Getters {{{1 */
301 /* < private >
302 * g_variant_new_from_trusted:
303 * @type: the #GVariantType
304 * @data: the data to use
305 * @size: the size of @data
306 *
307 * Constructs a new trusted #GVariant instance from the provided data.
308 * This is used to implement g_variant_new_* for all the basic types.
309 *
310 * Note: @data must be backed by memory that is aligned appropriately for the
311 * @type being loaded. Otherwise this function will internally create a copy of
312 * the memory (since GLib 2.60) or (in older versions) fail and exit the
313 * process.
314 *
315 * Returns: a new floating #GVariant
316 */
317 static GVariant *
g_variant_new_from_trusted(const GVariantType * type,gconstpointer data,gsize size)318 g_variant_new_from_trusted (const GVariantType *type,
319 gconstpointer data,
320 gsize size)
321 {
322 GVariant *value;
323 GBytes *bytes;
324
325 bytes = g_bytes_new (data, size);
326 value = g_variant_new_from_bytes (type, bytes, TRUE);
327 g_bytes_unref (bytes);
328
329 return value;
330 }
331
332 /**
333 * g_variant_new_boolean:
334 * @value: a #gboolean value
335 *
336 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
337 *
338 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
339 *
340 * Since: 2.24
341 **/
342 GVariant *
g_variant_new_boolean(gboolean value)343 g_variant_new_boolean (gboolean value)
344 {
345 guchar v = value;
346
347 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
348 }
349
350 /**
351 * g_variant_get_boolean:
352 * @value: a boolean #GVariant instance
353 *
354 * Returns the boolean value of @value.
355 *
356 * It is an error to call this function with a @value of any type
357 * other than %G_VARIANT_TYPE_BOOLEAN.
358 *
359 * Returns: %TRUE or %FALSE
360 *
361 * Since: 2.24
362 **/
363 gboolean
g_variant_get_boolean(GVariant * value)364 g_variant_get_boolean (GVariant *value)
365 {
366 const guchar *data;
367
368 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
369
370 data = g_variant_get_data (value);
371
372 return data != NULL ? *data != 0 : FALSE;
373 }
374
375 /* the constructors and accessors for byte, int{16,32,64}, handles and
376 * doubles all look pretty much exactly the same, so we reduce
377 * copy/pasting here.
378 */
379 #define NUMERIC_TYPE(TYPE, type, ctype) \
380 GVariant *g_variant_new_##type (ctype value) { \
381 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
382 &value, sizeof value); \
383 } \
384 ctype g_variant_get_##type (GVariant *value) { \
385 const ctype *data; \
386 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
387 data = g_variant_get_data (value); \
388 return data != NULL ? *data : 0; \
389 }
390
391
392 /**
393 * g_variant_new_byte:
394 * @value: a #guint8 value
395 *
396 * Creates a new byte #GVariant instance.
397 *
398 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
399 *
400 * Since: 2.24
401 **/
402 /**
403 * g_variant_get_byte:
404 * @value: a byte #GVariant instance
405 *
406 * Returns the byte value of @value.
407 *
408 * It is an error to call this function with a @value of any type
409 * other than %G_VARIANT_TYPE_BYTE.
410 *
411 * Returns: a #guint8
412 *
413 * Since: 2.24
414 **/
NUMERIC_TYPE(BYTE,byte,guint8)415 NUMERIC_TYPE (BYTE, byte, guint8)
416
417 /**
418 * g_variant_new_int16:
419 * @value: a #gint16 value
420 *
421 * Creates a new int16 #GVariant instance.
422 *
423 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
424 *
425 * Since: 2.24
426 **/
427 /**
428 * g_variant_get_int16:
429 * @value: an int16 #GVariant instance
430 *
431 * Returns the 16-bit signed integer value of @value.
432 *
433 * It is an error to call this function with a @value of any type
434 * other than %G_VARIANT_TYPE_INT16.
435 *
436 * Returns: a #gint16
437 *
438 * Since: 2.24
439 **/
440 NUMERIC_TYPE (INT16, int16, gint16)
441
442 /**
443 * g_variant_new_uint16:
444 * @value: a #guint16 value
445 *
446 * Creates a new uint16 #GVariant instance.
447 *
448 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
449 *
450 * Since: 2.24
451 **/
452 /**
453 * g_variant_get_uint16:
454 * @value: a uint16 #GVariant instance
455 *
456 * Returns the 16-bit unsigned integer value of @value.
457 *
458 * It is an error to call this function with a @value of any type
459 * other than %G_VARIANT_TYPE_UINT16.
460 *
461 * Returns: a #guint16
462 *
463 * Since: 2.24
464 **/
465 NUMERIC_TYPE (UINT16, uint16, guint16)
466
467 /**
468 * g_variant_new_int32:
469 * @value: a #gint32 value
470 *
471 * Creates a new int32 #GVariant instance.
472 *
473 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
474 *
475 * Since: 2.24
476 **/
477 /**
478 * g_variant_get_int32:
479 * @value: an int32 #GVariant instance
480 *
481 * Returns the 32-bit signed integer value of @value.
482 *
483 * It is an error to call this function with a @value of any type
484 * other than %G_VARIANT_TYPE_INT32.
485 *
486 * Returns: a #gint32
487 *
488 * Since: 2.24
489 **/
490 NUMERIC_TYPE (INT32, int32, gint32)
491
492 /**
493 * g_variant_new_uint32:
494 * @value: a #guint32 value
495 *
496 * Creates a new uint32 #GVariant instance.
497 *
498 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
499 *
500 * Since: 2.24
501 **/
502 /**
503 * g_variant_get_uint32:
504 * @value: a uint32 #GVariant instance
505 *
506 * Returns the 32-bit unsigned integer value of @value.
507 *
508 * It is an error to call this function with a @value of any type
509 * other than %G_VARIANT_TYPE_UINT32.
510 *
511 * Returns: a #guint32
512 *
513 * Since: 2.24
514 **/
515 NUMERIC_TYPE (UINT32, uint32, guint32)
516
517 /**
518 * g_variant_new_int64:
519 * @value: a #gint64 value
520 *
521 * Creates a new int64 #GVariant instance.
522 *
523 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
524 *
525 * Since: 2.24
526 **/
527 /**
528 * g_variant_get_int64:
529 * @value: an int64 #GVariant instance
530 *
531 * Returns the 64-bit signed integer value of @value.
532 *
533 * It is an error to call this function with a @value of any type
534 * other than %G_VARIANT_TYPE_INT64.
535 *
536 * Returns: a #gint64
537 *
538 * Since: 2.24
539 **/
540 NUMERIC_TYPE (INT64, int64, gint64)
541
542 /**
543 * g_variant_new_uint64:
544 * @value: a #guint64 value
545 *
546 * Creates a new uint64 #GVariant instance.
547 *
548 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
549 *
550 * Since: 2.24
551 **/
552 /**
553 * g_variant_get_uint64:
554 * @value: a uint64 #GVariant instance
555 *
556 * Returns the 64-bit unsigned integer value of @value.
557 *
558 * It is an error to call this function with a @value of any type
559 * other than %G_VARIANT_TYPE_UINT64.
560 *
561 * Returns: a #guint64
562 *
563 * Since: 2.24
564 **/
565 NUMERIC_TYPE (UINT64, uint64, guint64)
566
567 /**
568 * g_variant_new_handle:
569 * @value: a #gint32 value
570 *
571 * Creates a new handle #GVariant instance.
572 *
573 * By convention, handles are indexes into an array of file descriptors
574 * that are sent alongside a D-Bus message. If you're not interacting
575 * with D-Bus, you probably don't need them.
576 *
577 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
578 *
579 * Since: 2.24
580 **/
581 /**
582 * g_variant_get_handle:
583 * @value: a handle #GVariant instance
584 *
585 * Returns the 32-bit signed integer value of @value.
586 *
587 * It is an error to call this function with a @value of any type other
588 * than %G_VARIANT_TYPE_HANDLE.
589 *
590 * By convention, handles are indexes into an array of file descriptors
591 * that are sent alongside a D-Bus message. If you're not interacting
592 * with D-Bus, you probably don't need them.
593 *
594 * Returns: a #gint32
595 *
596 * Since: 2.24
597 **/
598 NUMERIC_TYPE (HANDLE, handle, gint32)
599
600 /**
601 * g_variant_new_double:
602 * @value: a #gdouble floating point value
603 *
604 * Creates a new double #GVariant instance.
605 *
606 * Returns: (transfer none): a floating reference to a new double #GVariant instance
607 *
608 * Since: 2.24
609 **/
610 /**
611 * g_variant_get_double:
612 * @value: a double #GVariant instance
613 *
614 * Returns the double precision floating point value of @value.
615 *
616 * It is an error to call this function with a @value of any type
617 * other than %G_VARIANT_TYPE_DOUBLE.
618 *
619 * Returns: a #gdouble
620 *
621 * Since: 2.24
622 **/
623 NUMERIC_TYPE (DOUBLE, double, gdouble)
624
625 /* Container type Constructor / Deconstructors {{{1 */
626 /**
627 * g_variant_new_maybe:
628 * @child_type: (nullable): the #GVariantType of the child, or %NULL
629 * @child: (nullable): the child value, or %NULL
630 *
631 * Depending on if @child is %NULL, either wraps @child inside of a
632 * maybe container or creates a Nothing instance for the given @type.
633 *
634 * At least one of @child_type and @child must be non-%NULL.
635 * If @child_type is non-%NULL then it must be a definite type.
636 * If they are both non-%NULL then @child_type must be the type
637 * of @child.
638 *
639 * If @child is a floating reference (see g_variant_ref_sink()), the new
640 * instance takes ownership of @child.
641 *
642 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
643 *
644 * Since: 2.24
645 **/
646 GVariant *
647 g_variant_new_maybe (const GVariantType *child_type,
648 GVariant *child)
649 {
650 GVariantType *maybe_type;
651 GVariant *value;
652
653 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
654 (child_type), 0);
655 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
656 g_return_val_if_fail (child_type == NULL || child == NULL ||
657 g_variant_is_of_type (child, child_type),
658 NULL);
659
660 if (child_type == NULL)
661 child_type = g_variant_get_type (child);
662
663 maybe_type = g_variant_type_new_maybe (child_type);
664
665 if (child != NULL)
666 {
667 GVariant **children;
668 gboolean trusted;
669
670 children = g_new (GVariant *, 1);
671 children[0] = g_variant_ref_sink (child);
672 trusted = g_variant_is_trusted (children[0]);
673
674 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
675 }
676 else
677 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
678
679 g_variant_type_free (maybe_type);
680
681 return value;
682 }
683
684 /**
685 * g_variant_get_maybe:
686 * @value: a maybe-typed value
687 *
688 * Given a maybe-typed #GVariant instance, extract its value. If the
689 * value is Nothing, then this function returns %NULL.
690 *
691 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
692 *
693 * Since: 2.24
694 **/
695 GVariant *
g_variant_get_maybe(GVariant * value)696 g_variant_get_maybe (GVariant *value)
697 {
698 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
699
700 if (g_variant_n_children (value))
701 return g_variant_get_child_value (value, 0);
702
703 return NULL;
704 }
705
706 /**
707 * g_variant_new_variant: (constructor)
708 * @value: a #GVariant instance
709 *
710 * Boxes @value. The result is a #GVariant instance representing a
711 * variant containing the original value.
712 *
713 * If @child is a floating reference (see g_variant_ref_sink()), the new
714 * instance takes ownership of @child.
715 *
716 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
717 *
718 * Since: 2.24
719 **/
720 GVariant *
g_variant_new_variant(GVariant * value)721 g_variant_new_variant (GVariant *value)
722 {
723 g_return_val_if_fail (value != NULL, NULL);
724
725 g_variant_ref_sink (value);
726
727 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
728 g_memdup (&value, sizeof value),
729 1, g_variant_is_trusted (value));
730 }
731
732 /**
733 * g_variant_get_variant:
734 * @value: a variant #GVariant instance
735 *
736 * Unboxes @value. The result is the #GVariant instance that was
737 * contained in @value.
738 *
739 * Returns: (transfer full): the item contained in the variant
740 *
741 * Since: 2.24
742 **/
743 GVariant *
g_variant_get_variant(GVariant * value)744 g_variant_get_variant (GVariant *value)
745 {
746 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
747
748 return g_variant_get_child_value (value, 0);
749 }
750
751 /**
752 * g_variant_new_array:
753 * @child_type: (nullable): the element type of the new array
754 * @children: (nullable) (array length=n_children): an array of
755 * #GVariant pointers, the children
756 * @n_children: the length of @children
757 *
758 * Creates a new #GVariant array from @children.
759 *
760 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
761 * child type is determined by inspecting the first element of the
762 * @children array. If @child_type is non-%NULL then it must be a
763 * definite type.
764 *
765 * The items of the array are taken from the @children array. No entry
766 * in the @children array may be %NULL.
767 *
768 * All items in the array must have the same type, which must be the
769 * same as @child_type, if given.
770 *
771 * If the @children are floating references (see g_variant_ref_sink()), the
772 * new instance takes ownership of them as if via g_variant_ref_sink().
773 *
774 * Returns: (transfer none): a floating reference to a new #GVariant array
775 *
776 * Since: 2.24
777 **/
778 GVariant *
g_variant_new_array(const GVariantType * child_type,GVariant * const * children,gsize n_children)779 g_variant_new_array (const GVariantType *child_type,
780 GVariant * const *children,
781 gsize n_children)
782 {
783 GVariantType *array_type;
784 GVariant **my_children;
785 gboolean trusted;
786 GVariant *value;
787 gsize i;
788
789 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
790 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
791 g_return_val_if_fail (child_type == NULL ||
792 g_variant_type_is_definite (child_type), NULL);
793
794 my_children = g_new (GVariant *, n_children);
795 trusted = TRUE;
796
797 if (child_type == NULL)
798 child_type = g_variant_get_type (children[0]);
799 array_type = g_variant_type_new_array (child_type);
800
801 for (i = 0; i < n_children; i++)
802 {
803 TYPE_CHECK (children[i], child_type, NULL);
804 my_children[i] = g_variant_ref_sink (children[i]);
805 trusted &= g_variant_is_trusted (children[i]);
806 }
807
808 value = g_variant_new_from_children (array_type, my_children,
809 n_children, trusted);
810 g_variant_type_free (array_type);
811
812 return value;
813 }
814
815 /*< private >
816 * g_variant_make_tuple_type:
817 * @children: (array length=n_children): an array of GVariant *
818 * @n_children: the length of @children
819 *
820 * Return the type of a tuple containing @children as its items.
821 **/
822 static GVariantType *
g_variant_make_tuple_type(GVariant * const * children,gsize n_children)823 g_variant_make_tuple_type (GVariant * const *children,
824 gsize n_children)
825 {
826 const GVariantType **types;
827 GVariantType *type;
828 gsize i;
829
830 types = g_new (const GVariantType *, n_children);
831
832 for (i = 0; i < n_children; i++)
833 types[i] = g_variant_get_type (children[i]);
834
835 type = g_variant_type_new_tuple (types, n_children);
836 g_free (types);
837
838 return type;
839 }
840
841 /**
842 * g_variant_new_tuple:
843 * @children: (array length=n_children): the items to make the tuple out of
844 * @n_children: the length of @children
845 *
846 * Creates a new tuple #GVariant out of the items in @children. The
847 * type is determined from the types of @children. No entry in the
848 * @children array may be %NULL.
849 *
850 * If @n_children is 0 then the unit tuple is constructed.
851 *
852 * If the @children are floating references (see g_variant_ref_sink()), the
853 * new instance takes ownership of them as if via g_variant_ref_sink().
854 *
855 * Returns: (transfer none): a floating reference to a new #GVariant tuple
856 *
857 * Since: 2.24
858 **/
859 GVariant *
g_variant_new_tuple(GVariant * const * children,gsize n_children)860 g_variant_new_tuple (GVariant * const *children,
861 gsize n_children)
862 {
863 GVariantType *tuple_type;
864 GVariant **my_children;
865 gboolean trusted;
866 GVariant *value;
867 gsize i;
868
869 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
870
871 my_children = g_new (GVariant *, n_children);
872 trusted = TRUE;
873
874 for (i = 0; i < n_children; i++)
875 {
876 my_children[i] = g_variant_ref_sink (children[i]);
877 trusted &= g_variant_is_trusted (children[i]);
878 }
879
880 tuple_type = g_variant_make_tuple_type (children, n_children);
881 value = g_variant_new_from_children (tuple_type, my_children,
882 n_children, trusted);
883 g_variant_type_free (tuple_type);
884
885 return value;
886 }
887
888 /*< private >
889 * g_variant_make_dict_entry_type:
890 * @key: a #GVariant, the key
891 * @val: a #GVariant, the value
892 *
893 * Return the type of a dictionary entry containing @key and @val as its
894 * children.
895 **/
896 static GVariantType *
g_variant_make_dict_entry_type(GVariant * key,GVariant * val)897 g_variant_make_dict_entry_type (GVariant *key,
898 GVariant *val)
899 {
900 return g_variant_type_new_dict_entry (g_variant_get_type (key),
901 g_variant_get_type (val));
902 }
903
904 /**
905 * g_variant_new_dict_entry: (constructor)
906 * @key: a basic #GVariant, the key
907 * @value: a #GVariant, the value
908 *
909 * Creates a new dictionary entry #GVariant. @key and @value must be
910 * non-%NULL. @key must be a value of a basic type (ie: not a container).
911 *
912 * If the @key or @value are floating references (see g_variant_ref_sink()),
913 * the new instance takes ownership of them as if via g_variant_ref_sink().
914 *
915 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
916 *
917 * Since: 2.24
918 **/
919 GVariant *
g_variant_new_dict_entry(GVariant * key,GVariant * value)920 g_variant_new_dict_entry (GVariant *key,
921 GVariant *value)
922 {
923 GVariantType *dict_type;
924 GVariant **children;
925 gboolean trusted;
926
927 g_return_val_if_fail (key != NULL && value != NULL, NULL);
928 g_return_val_if_fail (!g_variant_is_container (key), NULL);
929
930 children = g_new (GVariant *, 2);
931 children[0] = g_variant_ref_sink (key);
932 children[1] = g_variant_ref_sink (value);
933 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
934
935 dict_type = g_variant_make_dict_entry_type (key, value);
936 value = g_variant_new_from_children (dict_type, children, 2, trusted);
937 g_variant_type_free (dict_type);
938
939 return value;
940 }
941
942 /**
943 * g_variant_lookup: (skip)
944 * @dictionary: a dictionary #GVariant
945 * @key: the key to look up in the dictionary
946 * @format_string: a GVariant format string
947 * @...: the arguments to unpack the value into
948 *
949 * Looks up a value in a dictionary #GVariant.
950 *
951 * This function is a wrapper around g_variant_lookup_value() and
952 * g_variant_get(). In the case that %NULL would have been returned,
953 * this function returns %FALSE. Otherwise, it unpacks the returned
954 * value and returns %TRUE.
955 *
956 * @format_string determines the C types that are used for unpacking
957 * the values and also determines if the values are copied or borrowed,
958 * see the section on
959 * [GVariant format strings][gvariant-format-strings-pointers].
960 *
961 * This function is currently implemented with a linear scan. If you
962 * plan to do many lookups then #GVariantDict may be more efficient.
963 *
964 * Returns: %TRUE if a value was unpacked
965 *
966 * Since: 2.28
967 */
968 gboolean
g_variant_lookup(GVariant * dictionary,const gchar * key,const gchar * format_string,...)969 g_variant_lookup (GVariant *dictionary,
970 const gchar *key,
971 const gchar *format_string,
972 ...)
973 {
974 GVariantType *type;
975 GVariant *value;
976
977 /* flatten */
978 g_variant_get_data (dictionary);
979
980 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
981 value = g_variant_lookup_value (dictionary, key, type);
982 g_variant_type_free (type);
983
984 if (value)
985 {
986 va_list ap;
987
988 va_start (ap, format_string);
989 g_variant_get_va (value, format_string, NULL, &ap);
990 g_variant_unref (value);
991 va_end (ap);
992
993 return TRUE;
994 }
995
996 else
997 return FALSE;
998 }
999
1000 /**
1001 * g_variant_lookup_value:
1002 * @dictionary: a dictionary #GVariant
1003 * @key: the key to look up in the dictionary
1004 * @expected_type: (nullable): a #GVariantType, or %NULL
1005 *
1006 * Looks up a value in a dictionary #GVariant.
1007 *
1008 * This function works with dictionaries of the type a{s*} (and equally
1009 * well with type a{o*}, but we only further discuss the string case
1010 * for sake of clarity).
1011 *
1012 * In the event that @dictionary has the type a{sv}, the @expected_type
1013 * string specifies what type of value is expected to be inside of the
1014 * variant. If the value inside the variant has a different type then
1015 * %NULL is returned. In the event that @dictionary has a value type other
1016 * than v then @expected_type must directly match the value type and it is
1017 * used to unpack the value directly or an error occurs.
1018 *
1019 * In either case, if @key is not found in @dictionary, %NULL is returned.
1020 *
1021 * If the key is found and the value has the correct type, it is
1022 * returned. If @expected_type was specified then any non-%NULL return
1023 * value will have this type.
1024 *
1025 * This function is currently implemented with a linear scan. If you
1026 * plan to do many lookups then #GVariantDict may be more efficient.
1027 *
1028 * Returns: (transfer full): the value of the dictionary key, or %NULL
1029 *
1030 * Since: 2.28
1031 */
1032 GVariant *
g_variant_lookup_value(GVariant * dictionary,const gchar * key,const GVariantType * expected_type)1033 g_variant_lookup_value (GVariant *dictionary,
1034 const gchar *key,
1035 const GVariantType *expected_type)
1036 {
1037 GVariantIter iter;
1038 GVariant *entry;
1039 GVariant *value;
1040
1041 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1042 G_VARIANT_TYPE ("a{s*}")) ||
1043 g_variant_is_of_type (dictionary,
1044 G_VARIANT_TYPE ("a{o*}")),
1045 NULL);
1046
1047 g_variant_iter_init (&iter, dictionary);
1048
1049 while ((entry = g_variant_iter_next_value (&iter)))
1050 {
1051 GVariant *entry_key;
1052 gboolean matches;
1053
1054 entry_key = g_variant_get_child_value (entry, 0);
1055 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1056 g_variant_unref (entry_key);
1057
1058 if (matches)
1059 break;
1060
1061 g_variant_unref (entry);
1062 }
1063
1064 if (entry == NULL)
1065 return NULL;
1066
1067 value = g_variant_get_child_value (entry, 1);
1068 g_variant_unref (entry);
1069
1070 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1071 {
1072 GVariant *tmp;
1073
1074 tmp = g_variant_get_variant (value);
1075 g_variant_unref (value);
1076
1077 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1078 {
1079 g_variant_unref (tmp);
1080 tmp = NULL;
1081 }
1082
1083 value = tmp;
1084 }
1085
1086 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1087 g_variant_is_of_type (value, expected_type), NULL);
1088
1089 return value;
1090 }
1091
1092 /**
1093 * g_variant_get_fixed_array:
1094 * @value: a #GVariant array with fixed-sized elements
1095 * @n_elements: (out): a pointer to the location to store the number of items
1096 * @element_size: the size of each element
1097 *
1098 * Provides access to the serialised data for an array of fixed-sized
1099 * items.
1100 *
1101 * @value must be an array with fixed-sized elements. Numeric types are
1102 * fixed-size, as are tuples containing only other fixed-sized types.
1103 *
1104 * @element_size must be the size of a single element in the array,
1105 * as given by the section on
1106 * [serialized data memory][gvariant-serialised-data-memory].
1107 *
1108 * In particular, arrays of these fixed-sized types can be interpreted
1109 * as an array of the given C type, with @element_size set to the size
1110 * the appropriate type:
1111 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1112 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1113 * - %G_VARIANT_TYPE_BYTE: #guint8
1114 * - %G_VARIANT_TYPE_HANDLE: #guint32
1115 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1116 *
1117 * For example, if calling this function for an array of 32-bit integers,
1118 * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1119 * of a double-check that the form of the serialised data matches the caller's
1120 * expectation.
1121 *
1122 * @n_elements, which must be non-%NULL, is set equal to the number of
1123 * items in the array.
1124 *
1125 * Returns: (array length=n_elements) (transfer none): a pointer to
1126 * the fixed array
1127 *
1128 * Since: 2.24
1129 **/
1130 gconstpointer
g_variant_get_fixed_array(GVariant * value,gsize * n_elements,gsize element_size)1131 g_variant_get_fixed_array (GVariant *value,
1132 gsize *n_elements,
1133 gsize element_size)
1134 {
1135 GVariantTypeInfo *array_info;
1136 gsize array_element_size;
1137 gconstpointer data;
1138 gsize size;
1139
1140 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1141
1142 g_return_val_if_fail (n_elements != NULL, NULL);
1143 g_return_val_if_fail (element_size > 0, NULL);
1144
1145 array_info = g_variant_get_type_info (value);
1146 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1147
1148 g_return_val_if_fail (array_element_size, NULL);
1149
1150 if G_UNLIKELY (array_element_size != element_size)
1151 {
1152 if (array_element_size)
1153 g_critical ("g_variant_get_fixed_array: assertion "
1154 "'g_variant_array_has_fixed_size (value, element_size)' "
1155 "failed: array size %"G_GSIZE_FORMAT" does not match "
1156 "given element_size %"G_GSIZE_FORMAT".",
1157 array_element_size, element_size);
1158 else
1159 g_critical ("g_variant_get_fixed_array: assertion "
1160 "'g_variant_array_has_fixed_size (value, element_size)' "
1161 "failed: array does not have fixed size.");
1162 }
1163
1164 data = g_variant_get_data (value);
1165 size = g_variant_get_size (value);
1166
1167 if (size % element_size)
1168 *n_elements = 0;
1169 else
1170 *n_elements = size / element_size;
1171
1172 if (*n_elements)
1173 return data;
1174
1175 return NULL;
1176 }
1177
1178 /**
1179 * g_variant_new_fixed_array:
1180 * @element_type: the #GVariantType of each element
1181 * @elements: a pointer to the fixed array of contiguous elements
1182 * @n_elements: the number of elements
1183 * @element_size: the size of each element
1184 *
1185 * Constructs a new array #GVariant instance, where the elements are
1186 * of @element_type type.
1187 *
1188 * @elements must be an array with fixed-sized elements. Numeric types are
1189 * fixed-size as are tuples containing only other fixed-sized types.
1190 *
1191 * @element_size must be the size of a single element in the array.
1192 * For example, if calling this function for an array of 32-bit integers,
1193 * you might say sizeof(gint32). This value isn't used except for the purpose
1194 * of a double-check that the form of the serialised data matches the caller's
1195 * expectation.
1196 *
1197 * @n_elements must be the length of the @elements array.
1198 *
1199 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1200 *
1201 * Since: 2.32
1202 **/
1203 GVariant *
g_variant_new_fixed_array(const GVariantType * element_type,gconstpointer elements,gsize n_elements,gsize element_size)1204 g_variant_new_fixed_array (const GVariantType *element_type,
1205 gconstpointer elements,
1206 gsize n_elements,
1207 gsize element_size)
1208 {
1209 GVariantType *array_type;
1210 gsize array_element_size;
1211 GVariantTypeInfo *array_info;
1212 GVariant *value;
1213 gpointer data;
1214
1215 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1216 g_return_val_if_fail (element_size > 0, NULL);
1217
1218 array_type = g_variant_type_new_array (element_type);
1219 array_info = g_variant_type_info_get (array_type);
1220 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1221 if G_UNLIKELY (array_element_size != element_size)
1222 {
1223 if (array_element_size)
1224 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1225 " does not match given element_size %" G_GSIZE_FORMAT ".",
1226 array_element_size, element_size);
1227 else
1228 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1229 return NULL;
1230 }
1231
1232 data = g_memdup (elements, n_elements * element_size);
1233 value = g_variant_new_from_data (array_type, data,
1234 n_elements * element_size,
1235 FALSE, g_free, data);
1236
1237 g_variant_type_free (array_type);
1238 g_variant_type_info_unref (array_info);
1239
1240 return value;
1241 }
1242
1243 /* String type constructor/getters/validation {{{1 */
1244 /**
1245 * g_variant_new_string:
1246 * @string: a normal UTF-8 nul-terminated string
1247 *
1248 * Creates a string #GVariant with the contents of @string.
1249 *
1250 * @string must be valid UTF-8, and must not be %NULL. To encode
1251 * potentially-%NULL strings, use g_variant_new() with `ms` as the
1252 * [format string][gvariant-format-strings-maybe-types].
1253 *
1254 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1255 *
1256 * Since: 2.24
1257 **/
1258 GVariant *
g_variant_new_string(const gchar * string)1259 g_variant_new_string (const gchar *string)
1260 {
1261 g_return_val_if_fail (string != NULL, NULL);
1262 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1263
1264 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1265 string, strlen (string) + 1);
1266 }
1267
1268 /**
1269 * g_variant_new_take_string: (skip)
1270 * @string: a normal UTF-8 nul-terminated string
1271 *
1272 * Creates a string #GVariant with the contents of @string.
1273 *
1274 * @string must be valid UTF-8, and must not be %NULL. To encode
1275 * potentially-%NULL strings, use this with g_variant_new_maybe().
1276 *
1277 * This function consumes @string. g_free() will be called on @string
1278 * when it is no longer required.
1279 *
1280 * You must not modify or access @string in any other way after passing
1281 * it to this function. It is even possible that @string is immediately
1282 * freed.
1283 *
1284 * Returns: (transfer none): a floating reference to a new string
1285 * #GVariant instance
1286 *
1287 * Since: 2.38
1288 **/
1289 GVariant *
g_variant_new_take_string(gchar * string)1290 g_variant_new_take_string (gchar *string)
1291 {
1292 GVariant *value;
1293 GBytes *bytes;
1294
1295 g_return_val_if_fail (string != NULL, NULL);
1296 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1297
1298 bytes = g_bytes_new_take (string, strlen (string) + 1);
1299 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1300 g_bytes_unref (bytes);
1301
1302 return value;
1303 }
1304
1305 /**
1306 * g_variant_new_printf: (skip)
1307 * @format_string: a printf-style format string
1308 * @...: arguments for @format_string
1309 *
1310 * Creates a string-type GVariant using printf formatting.
1311 *
1312 * This is similar to calling g_strdup_printf() and then
1313 * g_variant_new_string() but it saves a temporary variable and an
1314 * unnecessary copy.
1315 *
1316 * Returns: (transfer none): a floating reference to a new string
1317 * #GVariant instance
1318 *
1319 * Since: 2.38
1320 **/
1321 GVariant *
g_variant_new_printf(const gchar * format_string,...)1322 g_variant_new_printf (const gchar *format_string,
1323 ...)
1324 {
1325 GVariant *value;
1326 GBytes *bytes;
1327 gchar *string;
1328 va_list ap;
1329
1330 g_return_val_if_fail (format_string != NULL, NULL);
1331
1332 va_start (ap, format_string);
1333 string = g_strdup_vprintf (format_string, ap);
1334 va_end (ap);
1335
1336 bytes = g_bytes_new_take (string, strlen (string) + 1);
1337 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1338 g_bytes_unref (bytes);
1339
1340 return value;
1341 }
1342
1343 /**
1344 * g_variant_new_object_path:
1345 * @object_path: a normal C nul-terminated string
1346 *
1347 * Creates a D-Bus object path #GVariant with the contents of @string.
1348 * @string must be a valid D-Bus object path. Use
1349 * g_variant_is_object_path() if you're not sure.
1350 *
1351 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1352 *
1353 * Since: 2.24
1354 **/
1355 GVariant *
g_variant_new_object_path(const gchar * object_path)1356 g_variant_new_object_path (const gchar *object_path)
1357 {
1358 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1359
1360 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1361 object_path, strlen (object_path) + 1);
1362 }
1363
1364 /**
1365 * g_variant_is_object_path:
1366 * @string: a normal C nul-terminated string
1367 *
1368 * Determines if a given string is a valid D-Bus object path. You
1369 * should ensure that a string is a valid D-Bus object path before
1370 * passing it to g_variant_new_object_path().
1371 *
1372 * A valid object path starts with `/` followed by zero or more
1373 * sequences of characters separated by `/` characters. Each sequence
1374 * must contain only the characters `[A-Z][a-z][0-9]_`. No sequence
1375 * (including the one following the final `/` character) may be empty.
1376 *
1377 * Returns: %TRUE if @string is a D-Bus object path
1378 *
1379 * Since: 2.24
1380 **/
1381 gboolean
g_variant_is_object_path(const gchar * string)1382 g_variant_is_object_path (const gchar *string)
1383 {
1384 g_return_val_if_fail (string != NULL, FALSE);
1385
1386 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1387 }
1388
1389 /**
1390 * g_variant_new_signature:
1391 * @signature: a normal C nul-terminated string
1392 *
1393 * Creates a D-Bus type signature #GVariant with the contents of
1394 * @string. @string must be a valid D-Bus type signature. Use
1395 * g_variant_is_signature() if you're not sure.
1396 *
1397 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1398 *
1399 * Since: 2.24
1400 **/
1401 GVariant *
g_variant_new_signature(const gchar * signature)1402 g_variant_new_signature (const gchar *signature)
1403 {
1404 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1405
1406 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1407 signature, strlen (signature) + 1);
1408 }
1409
1410 /**
1411 * g_variant_is_signature:
1412 * @string: a normal C nul-terminated string
1413 *
1414 * Determines if a given string is a valid D-Bus type signature. You
1415 * should ensure that a string is a valid D-Bus type signature before
1416 * passing it to g_variant_new_signature().
1417 *
1418 * D-Bus type signatures consist of zero or more definite #GVariantType
1419 * strings in sequence.
1420 *
1421 * Returns: %TRUE if @string is a D-Bus type signature
1422 *
1423 * Since: 2.24
1424 **/
1425 gboolean
g_variant_is_signature(const gchar * string)1426 g_variant_is_signature (const gchar *string)
1427 {
1428 g_return_val_if_fail (string != NULL, FALSE);
1429
1430 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1431 }
1432
1433 /**
1434 * g_variant_get_string:
1435 * @value: a string #GVariant instance
1436 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1437 * to store the length
1438 *
1439 * Returns the string value of a #GVariant instance with a string
1440 * type. This includes the types %G_VARIANT_TYPE_STRING,
1441 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1442 *
1443 * The string will always be UTF-8 encoded, and will never be %NULL.
1444 *
1445 * If @length is non-%NULL then the length of the string (in bytes) is
1446 * returned there. For trusted values, this information is already
1447 * known. For untrusted values, a strlen() will be performed.
1448 *
1449 * It is an error to call this function with a @value of any type
1450 * other than those three.
1451 *
1452 * The return value remains valid as long as @value exists.
1453 *
1454 * Returns: (transfer none): the constant string, UTF-8 encoded
1455 *
1456 * Since: 2.24
1457 **/
1458 const gchar *
g_variant_get_string(GVariant * value,gsize * length)1459 g_variant_get_string (GVariant *value,
1460 gsize *length)
1461 {
1462 gconstpointer data;
1463 gsize size;
1464
1465 g_return_val_if_fail (value != NULL, NULL);
1466 g_return_val_if_fail (
1467 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1468 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1469 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1470
1471 data = g_variant_get_data (value);
1472 size = g_variant_get_size (value);
1473
1474 if (!g_variant_is_trusted (value))
1475 {
1476 switch (g_variant_classify (value))
1477 {
1478 case G_VARIANT_CLASS_STRING:
1479 if (g_variant_serialiser_is_string (data, size))
1480 break;
1481
1482 data = "";
1483 size = 1;
1484 break;
1485
1486 case G_VARIANT_CLASS_OBJECT_PATH:
1487 if (g_variant_serialiser_is_object_path (data, size))
1488 break;
1489
1490 data = "/";
1491 size = 2;
1492 break;
1493
1494 case G_VARIANT_CLASS_SIGNATURE:
1495 if (g_variant_serialiser_is_signature (data, size))
1496 break;
1497
1498 data = "";
1499 size = 1;
1500 break;
1501
1502 default:
1503 g_assert_not_reached ();
1504 }
1505 }
1506
1507 if (length)
1508 *length = size - 1;
1509
1510 return data;
1511 }
1512
1513 /**
1514 * g_variant_dup_string:
1515 * @value: a string #GVariant instance
1516 * @length: (out): a pointer to a #gsize, to store the length
1517 *
1518 * Similar to g_variant_get_string() except that instead of returning
1519 * a constant string, the string is duplicated.
1520 *
1521 * The string will always be UTF-8 encoded.
1522 *
1523 * The return value must be freed using g_free().
1524 *
1525 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1526 *
1527 * Since: 2.24
1528 **/
1529 gchar *
g_variant_dup_string(GVariant * value,gsize * length)1530 g_variant_dup_string (GVariant *value,
1531 gsize *length)
1532 {
1533 return g_strdup (g_variant_get_string (value, length));
1534 }
1535
1536 /**
1537 * g_variant_new_strv:
1538 * @strv: (array length=length) (element-type utf8): an array of strings
1539 * @length: the length of @strv, or -1
1540 *
1541 * Constructs an array of strings #GVariant from the given array of
1542 * strings.
1543 *
1544 * If @length is -1 then @strv is %NULL-terminated.
1545 *
1546 * Returns: (transfer none): a new floating #GVariant instance
1547 *
1548 * Since: 2.24
1549 **/
1550 GVariant *
g_variant_new_strv(const gchar * const * strv,gssize length)1551 g_variant_new_strv (const gchar * const *strv,
1552 gssize length)
1553 {
1554 GVariant **strings;
1555 gsize i, length_unsigned;
1556
1557 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1558
1559 if (length < 0)
1560 length = g_strv_length ((gchar **) strv);
1561 length_unsigned = length;
1562
1563 strings = g_new (GVariant *, length_unsigned);
1564 for (i = 0; i < length_unsigned; i++)
1565 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1566
1567 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1568 strings, length_unsigned, TRUE);
1569 }
1570
1571 /**
1572 * g_variant_get_strv:
1573 * @value: an array of strings #GVariant
1574 * @length: (out) (optional): the length of the result, or %NULL
1575 *
1576 * Gets the contents of an array of strings #GVariant. This call
1577 * makes a shallow copy; the return result should be released with
1578 * g_free(), but the individual strings must not be modified.
1579 *
1580 * If @length is non-%NULL then the number of elements in the result
1581 * is stored there. In any case, the resulting array will be
1582 * %NULL-terminated.
1583 *
1584 * For an empty array, @length will be set to 0 and a pointer to a
1585 * %NULL pointer will be returned.
1586 *
1587 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1588 *
1589 * Since: 2.24
1590 **/
1591 const gchar **
g_variant_get_strv(GVariant * value,gsize * length)1592 g_variant_get_strv (GVariant *value,
1593 gsize *length)
1594 {
1595 const gchar **strv;
1596 gsize n;
1597 gsize i;
1598
1599 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1600
1601 g_variant_get_data (value);
1602 n = g_variant_n_children (value);
1603 strv = g_new (const gchar *, n + 1);
1604
1605 for (i = 0; i < n; i++)
1606 {
1607 GVariant *string;
1608
1609 string = g_variant_get_child_value (value, i);
1610 strv[i] = g_variant_get_string (string, NULL);
1611 g_variant_unref (string);
1612 }
1613 strv[i] = NULL;
1614
1615 if (length)
1616 *length = n;
1617
1618 return strv;
1619 }
1620
1621 /**
1622 * g_variant_dup_strv:
1623 * @value: an array of strings #GVariant
1624 * @length: (out) (optional): the length of the result, or %NULL
1625 *
1626 * Gets the contents of an array of strings #GVariant. This call
1627 * makes a deep copy; the return result should be released with
1628 * g_strfreev().
1629 *
1630 * If @length is non-%NULL then the number of elements in the result
1631 * is stored there. In any case, the resulting array will be
1632 * %NULL-terminated.
1633 *
1634 * For an empty array, @length will be set to 0 and a pointer to a
1635 * %NULL pointer will be returned.
1636 *
1637 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1638 *
1639 * Since: 2.24
1640 **/
1641 gchar **
g_variant_dup_strv(GVariant * value,gsize * length)1642 g_variant_dup_strv (GVariant *value,
1643 gsize *length)
1644 {
1645 gchar **strv;
1646 gsize n;
1647 gsize i;
1648
1649 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1650
1651 n = g_variant_n_children (value);
1652 strv = g_new (gchar *, n + 1);
1653
1654 for (i = 0; i < n; i++)
1655 {
1656 GVariant *string;
1657
1658 string = g_variant_get_child_value (value, i);
1659 strv[i] = g_variant_dup_string (string, NULL);
1660 g_variant_unref (string);
1661 }
1662 strv[i] = NULL;
1663
1664 if (length)
1665 *length = n;
1666
1667 return strv;
1668 }
1669
1670 /**
1671 * g_variant_new_objv:
1672 * @strv: (array length=length) (element-type utf8): an array of strings
1673 * @length: the length of @strv, or -1
1674 *
1675 * Constructs an array of object paths #GVariant from the given array of
1676 * strings.
1677 *
1678 * Each string must be a valid #GVariant object path; see
1679 * g_variant_is_object_path().
1680 *
1681 * If @length is -1 then @strv is %NULL-terminated.
1682 *
1683 * Returns: (transfer none): a new floating #GVariant instance
1684 *
1685 * Since: 2.30
1686 **/
1687 GVariant *
g_variant_new_objv(const gchar * const * strv,gssize length)1688 g_variant_new_objv (const gchar * const *strv,
1689 gssize length)
1690 {
1691 GVariant **strings;
1692 gsize i, length_unsigned;
1693
1694 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1695
1696 if (length < 0)
1697 length = g_strv_length ((gchar **) strv);
1698 length_unsigned = length;
1699
1700 strings = g_new (GVariant *, length_unsigned);
1701 for (i = 0; i < length_unsigned; i++)
1702 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1703
1704 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1705 strings, length_unsigned, TRUE);
1706 }
1707
1708 /**
1709 * g_variant_get_objv:
1710 * @value: an array of object paths #GVariant
1711 * @length: (out) (optional): the length of the result, or %NULL
1712 *
1713 * Gets the contents of an array of object paths #GVariant. This call
1714 * makes a shallow copy; the return result should be released with
1715 * g_free(), but the individual strings must not be modified.
1716 *
1717 * If @length is non-%NULL then the number of elements in the result
1718 * is stored there. In any case, the resulting array will be
1719 * %NULL-terminated.
1720 *
1721 * For an empty array, @length will be set to 0 and a pointer to a
1722 * %NULL pointer will be returned.
1723 *
1724 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1725 *
1726 * Since: 2.30
1727 **/
1728 const gchar **
g_variant_get_objv(GVariant * value,gsize * length)1729 g_variant_get_objv (GVariant *value,
1730 gsize *length)
1731 {
1732 const gchar **strv;
1733 gsize n;
1734 gsize i;
1735
1736 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1737
1738 g_variant_get_data (value);
1739 n = g_variant_n_children (value);
1740 strv = g_new (const gchar *, n + 1);
1741
1742 for (i = 0; i < n; i++)
1743 {
1744 GVariant *string;
1745
1746 string = g_variant_get_child_value (value, i);
1747 strv[i] = g_variant_get_string (string, NULL);
1748 g_variant_unref (string);
1749 }
1750 strv[i] = NULL;
1751
1752 if (length)
1753 *length = n;
1754
1755 return strv;
1756 }
1757
1758 /**
1759 * g_variant_dup_objv:
1760 * @value: an array of object paths #GVariant
1761 * @length: (out) (optional): the length of the result, or %NULL
1762 *
1763 * Gets the contents of an array of object paths #GVariant. This call
1764 * makes a deep copy; the return result should be released with
1765 * g_strfreev().
1766 *
1767 * If @length is non-%NULL then the number of elements in the result
1768 * is stored there. In any case, the resulting array will be
1769 * %NULL-terminated.
1770 *
1771 * For an empty array, @length will be set to 0 and a pointer to a
1772 * %NULL pointer will be returned.
1773 *
1774 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1775 *
1776 * Since: 2.30
1777 **/
1778 gchar **
g_variant_dup_objv(GVariant * value,gsize * length)1779 g_variant_dup_objv (GVariant *value,
1780 gsize *length)
1781 {
1782 gchar **strv;
1783 gsize n;
1784 gsize i;
1785
1786 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1787
1788 n = g_variant_n_children (value);
1789 strv = g_new (gchar *, n + 1);
1790
1791 for (i = 0; i < n; i++)
1792 {
1793 GVariant *string;
1794
1795 string = g_variant_get_child_value (value, i);
1796 strv[i] = g_variant_dup_string (string, NULL);
1797 g_variant_unref (string);
1798 }
1799 strv[i] = NULL;
1800
1801 if (length)
1802 *length = n;
1803
1804 return strv;
1805 }
1806
1807
1808 /**
1809 * g_variant_new_bytestring:
1810 * @string: (array zero-terminated=1) (element-type guint8): a normal
1811 * nul-terminated string in no particular encoding
1812 *
1813 * Creates an array-of-bytes #GVariant with the contents of @string.
1814 * This function is just like g_variant_new_string() except that the
1815 * string need not be valid UTF-8.
1816 *
1817 * The nul terminator character at the end of the string is stored in
1818 * the array.
1819 *
1820 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1821 *
1822 * Since: 2.26
1823 **/
1824 GVariant *
g_variant_new_bytestring(const gchar * string)1825 g_variant_new_bytestring (const gchar *string)
1826 {
1827 g_return_val_if_fail (string != NULL, NULL);
1828
1829 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1830 string, strlen (string) + 1);
1831 }
1832
1833 /**
1834 * g_variant_get_bytestring:
1835 * @value: an array-of-bytes #GVariant instance
1836 *
1837 * Returns the string value of a #GVariant instance with an
1838 * array-of-bytes type. The string has no particular encoding.
1839 *
1840 * If the array does not end with a nul terminator character, the empty
1841 * string is returned. For this reason, you can always trust that a
1842 * non-%NULL nul-terminated string will be returned by this function.
1843 *
1844 * If the array contains a nul terminator character somewhere other than
1845 * the last byte then the returned string is the string, up to the first
1846 * such nul character.
1847 *
1848 * g_variant_get_fixed_array() should be used instead if the array contains
1849 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1850 *
1851 * It is an error to call this function with a @value that is not an
1852 * array of bytes.
1853 *
1854 * The return value remains valid as long as @value exists.
1855 *
1856 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1857 * the constant string
1858 *
1859 * Since: 2.26
1860 **/
1861 const gchar *
g_variant_get_bytestring(GVariant * value)1862 g_variant_get_bytestring (GVariant *value)
1863 {
1864 const gchar *string;
1865 gsize size;
1866
1867 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1868
1869 /* Won't be NULL since this is an array type */
1870 string = g_variant_get_data (value);
1871 size = g_variant_get_size (value);
1872
1873 if (size && string[size - 1] == '\0')
1874 return string;
1875 else
1876 return "";
1877 }
1878
1879 /**
1880 * g_variant_dup_bytestring:
1881 * @value: an array-of-bytes #GVariant instance
1882 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1883 * the length (not including the nul terminator)
1884 *
1885 * Similar to g_variant_get_bytestring() except that instead of
1886 * returning a constant string, the string is duplicated.
1887 *
1888 * The return value must be freed using g_free().
1889 *
1890 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1891 * a newly allocated string
1892 *
1893 * Since: 2.26
1894 **/
1895 gchar *
g_variant_dup_bytestring(GVariant * value,gsize * length)1896 g_variant_dup_bytestring (GVariant *value,
1897 gsize *length)
1898 {
1899 const gchar *original = g_variant_get_bytestring (value);
1900 gsize size;
1901
1902 /* don't crash in case get_bytestring() had an assert failure */
1903 if (original == NULL)
1904 return NULL;
1905
1906 size = strlen (original);
1907
1908 if (length)
1909 *length = size;
1910
1911 return g_memdup (original, size + 1);
1912 }
1913
1914 /**
1915 * g_variant_new_bytestring_array:
1916 * @strv: (array length=length): an array of strings
1917 * @length: the length of @strv, or -1
1918 *
1919 * Constructs an array of bytestring #GVariant from the given array of
1920 * strings.
1921 *
1922 * If @length is -1 then @strv is %NULL-terminated.
1923 *
1924 * Returns: (transfer none): a new floating #GVariant instance
1925 *
1926 * Since: 2.26
1927 **/
1928 GVariant *
g_variant_new_bytestring_array(const gchar * const * strv,gssize length)1929 g_variant_new_bytestring_array (const gchar * const *strv,
1930 gssize length)
1931 {
1932 GVariant **strings;
1933 gsize i, length_unsigned;
1934
1935 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1936
1937 if (length < 0)
1938 length = g_strv_length ((gchar **) strv);
1939 length_unsigned = length;
1940
1941 strings = g_new (GVariant *, length_unsigned);
1942 for (i = 0; i < length_unsigned; i++)
1943 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1944
1945 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1946 strings, length_unsigned, TRUE);
1947 }
1948
1949 /**
1950 * g_variant_get_bytestring_array:
1951 * @value: an array of array of bytes #GVariant ('aay')
1952 * @length: (out) (optional): the length of the result, or %NULL
1953 *
1954 * Gets the contents of an array of array of bytes #GVariant. This call
1955 * makes a shallow copy; the return result should be released with
1956 * g_free(), but the individual strings must not be modified.
1957 *
1958 * If @length is non-%NULL then the number of elements in the result is
1959 * stored there. In any case, the resulting array will be
1960 * %NULL-terminated.
1961 *
1962 * For an empty array, @length will be set to 0 and a pointer to a
1963 * %NULL pointer will be returned.
1964 *
1965 * Returns: (array length=length) (transfer container): an array of constant strings
1966 *
1967 * Since: 2.26
1968 **/
1969 const gchar **
g_variant_get_bytestring_array(GVariant * value,gsize * length)1970 g_variant_get_bytestring_array (GVariant *value,
1971 gsize *length)
1972 {
1973 const gchar **strv;
1974 gsize n;
1975 gsize i;
1976
1977 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1978
1979 g_variant_get_data (value);
1980 n = g_variant_n_children (value);
1981 strv = g_new (const gchar *, n + 1);
1982
1983 for (i = 0; i < n; i++)
1984 {
1985 GVariant *string;
1986
1987 string = g_variant_get_child_value (value, i);
1988 strv[i] = g_variant_get_bytestring (string);
1989 g_variant_unref (string);
1990 }
1991 strv[i] = NULL;
1992
1993 if (length)
1994 *length = n;
1995
1996 return strv;
1997 }
1998
1999 /**
2000 * g_variant_dup_bytestring_array:
2001 * @value: an array of array of bytes #GVariant ('aay')
2002 * @length: (out) (optional): the length of the result, or %NULL
2003 *
2004 * Gets the contents of an array of array of bytes #GVariant. This call
2005 * makes a deep copy; the return result should be released with
2006 * g_strfreev().
2007 *
2008 * If @length is non-%NULL then the number of elements in the result is
2009 * stored there. In any case, the resulting array will be
2010 * %NULL-terminated.
2011 *
2012 * For an empty array, @length will be set to 0 and a pointer to a
2013 * %NULL pointer will be returned.
2014 *
2015 * Returns: (array length=length) (transfer full): an array of strings
2016 *
2017 * Since: 2.26
2018 **/
2019 gchar **
g_variant_dup_bytestring_array(GVariant * value,gsize * length)2020 g_variant_dup_bytestring_array (GVariant *value,
2021 gsize *length)
2022 {
2023 gchar **strv;
2024 gsize n;
2025 gsize i;
2026
2027 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2028
2029 g_variant_get_data (value);
2030 n = g_variant_n_children (value);
2031 strv = g_new (gchar *, n + 1);
2032
2033 for (i = 0; i < n; i++)
2034 {
2035 GVariant *string;
2036
2037 string = g_variant_get_child_value (value, i);
2038 strv[i] = g_variant_dup_bytestring (string, NULL);
2039 g_variant_unref (string);
2040 }
2041 strv[i] = NULL;
2042
2043 if (length)
2044 *length = n;
2045
2046 return strv;
2047 }
2048
2049 /* Type checking and querying {{{1 */
2050 /**
2051 * g_variant_get_type:
2052 * @value: a #GVariant
2053 *
2054 * Determines the type of @value.
2055 *
2056 * The return value is valid for the lifetime of @value and must not
2057 * be freed.
2058 *
2059 * Returns: a #GVariantType
2060 *
2061 * Since: 2.24
2062 **/
2063 const GVariantType *
g_variant_get_type(GVariant * value)2064 g_variant_get_type (GVariant *value)
2065 {
2066 GVariantTypeInfo *type_info;
2067
2068 g_return_val_if_fail (value != NULL, NULL);
2069
2070 type_info = g_variant_get_type_info (value);
2071
2072 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2073 }
2074
2075 /**
2076 * g_variant_get_type_string:
2077 * @value: a #GVariant
2078 *
2079 * Returns the type string of @value. Unlike the result of calling
2080 * g_variant_type_peek_string(), this string is nul-terminated. This
2081 * string belongs to #GVariant and must not be freed.
2082 *
2083 * Returns: the type string for the type of @value
2084 *
2085 * Since: 2.24
2086 **/
2087 const gchar *
g_variant_get_type_string(GVariant * value)2088 g_variant_get_type_string (GVariant *value)
2089 {
2090 GVariantTypeInfo *type_info;
2091
2092 g_return_val_if_fail (value != NULL, NULL);
2093
2094 type_info = g_variant_get_type_info (value);
2095
2096 return g_variant_type_info_get_type_string (type_info);
2097 }
2098
2099 /**
2100 * g_variant_is_of_type:
2101 * @value: a #GVariant instance
2102 * @type: a #GVariantType
2103 *
2104 * Checks if a value has a type matching the provided type.
2105 *
2106 * Returns: %TRUE if the type of @value matches @type
2107 *
2108 * Since: 2.24
2109 **/
2110 gboolean
g_variant_is_of_type(GVariant * value,const GVariantType * type)2111 g_variant_is_of_type (GVariant *value,
2112 const GVariantType *type)
2113 {
2114 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2115 }
2116
2117 /**
2118 * g_variant_is_container:
2119 * @value: a #GVariant instance
2120 *
2121 * Checks if @value is a container.
2122 *
2123 * Returns: %TRUE if @value is a container
2124 *
2125 * Since: 2.24
2126 */
2127 gboolean
g_variant_is_container(GVariant * value)2128 g_variant_is_container (GVariant *value)
2129 {
2130 return g_variant_type_is_container (g_variant_get_type (value));
2131 }
2132
2133
2134 /**
2135 * g_variant_classify:
2136 * @value: a #GVariant
2137 *
2138 * Classifies @value according to its top-level type.
2139 *
2140 * Returns: the #GVariantClass of @value
2141 *
2142 * Since: 2.24
2143 **/
2144 /**
2145 * GVariantClass:
2146 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2147 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2148 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2149 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2150 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2151 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2152 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2153 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2154 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2155 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2156 * point value.
2157 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2158 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2159 * string.
2160 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2161 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2162 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2163 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2164 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2165 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2166 *
2167 * The range of possible top-level types of #GVariant instances.
2168 *
2169 * Since: 2.24
2170 **/
2171 GVariantClass
g_variant_classify(GVariant * value)2172 g_variant_classify (GVariant *value)
2173 {
2174 g_return_val_if_fail (value != NULL, 0);
2175
2176 return *g_variant_get_type_string (value);
2177 }
2178
2179 /* Pretty printer {{{1 */
2180 /* This function is not introspectable because if @string is NULL,
2181 @returns is (transfer full), otherwise it is (transfer none), which
2182 is not supported by GObjectIntrospection */
2183 /**
2184 * g_variant_print_string: (skip)
2185 * @value: a #GVariant
2186 * @string: (nullable) (default NULL): a #GString, or %NULL
2187 * @type_annotate: %TRUE if type information should be included in
2188 * the output
2189 *
2190 * Behaves as g_variant_print(), but operates on a #GString.
2191 *
2192 * If @string is non-%NULL then it is appended to and returned. Else,
2193 * a new empty #GString is allocated and it is returned.
2194 *
2195 * Returns: a #GString containing the string
2196 *
2197 * Since: 2.24
2198 **/
2199 GString *
g_variant_print_string(GVariant * value,GString * string,gboolean type_annotate)2200 g_variant_print_string (GVariant *value,
2201 GString *string,
2202 gboolean type_annotate)
2203 {
2204 if G_UNLIKELY (string == NULL)
2205 string = g_string_new (NULL);
2206
2207 switch (g_variant_classify (value))
2208 {
2209 case G_VARIANT_CLASS_MAYBE:
2210 if (type_annotate)
2211 g_string_append_printf (string, "@%s ",
2212 g_variant_get_type_string (value));
2213
2214 if (g_variant_n_children (value))
2215 {
2216 gchar *printed_child;
2217 GVariant *element;
2218
2219 /* Nested maybes:
2220 *
2221 * Consider the case of the type "mmi". In this case we could
2222 * write "just just 4", but "4" alone is totally unambiguous,
2223 * so we try to drop "just" where possible.
2224 *
2225 * We have to be careful not to always drop "just", though,
2226 * since "nothing" needs to be distinguishable from "just
2227 * nothing". The case where we need to ensure we keep the
2228 * "just" is actually exactly the case where we have a nested
2229 * Nothing.
2230 *
2231 * Instead of searching for that nested Nothing, we just print
2232 * the contained value into a separate string and see if we
2233 * end up with "nothing" at the end of it. If so, we need to
2234 * add "just" at our level.
2235 */
2236 element = g_variant_get_child_value (value, 0);
2237 printed_child = g_variant_print (element, FALSE);
2238 g_variant_unref (element);
2239
2240 if (g_str_has_suffix (printed_child, "nothing"))
2241 g_string_append (string, "just ");
2242 g_string_append (string, printed_child);
2243 g_free (printed_child);
2244 }
2245 else
2246 g_string_append (string, "nothing");
2247
2248 break;
2249
2250 case G_VARIANT_CLASS_ARRAY:
2251 /* it's an array so the first character of the type string is 'a'
2252 *
2253 * if the first two characters are 'ay' then it's a bytestring.
2254 * under certain conditions we print those as strings.
2255 */
2256 if (g_variant_get_type_string (value)[1] == 'y')
2257 {
2258 const gchar *str;
2259 gsize size;
2260 gsize i;
2261
2262 /* first determine if it is a byte string.
2263 * that's when there's a single nul character: at the end.
2264 */
2265 str = g_variant_get_data (value);
2266 size = g_variant_get_size (value);
2267
2268 for (i = 0; i < size; i++)
2269 if (str[i] == '\0')
2270 break;
2271
2272 /* first nul byte is the last byte -> it's a byte string. */
2273 if (i == size - 1)
2274 {
2275 gchar *escaped = g_strescape (str, NULL);
2276
2277 /* use double quotes only if a ' is in the string */
2278 if (strchr (str, '\''))
2279 g_string_append_printf (string, "b\"%s\"", escaped);
2280 else
2281 g_string_append_printf (string, "b'%s'", escaped);
2282
2283 g_free (escaped);
2284 break;
2285 }
2286
2287 else
2288 {
2289 /* fall through and handle normally... */
2290 }
2291 }
2292
2293 /*
2294 * if the first two characters are 'a{' then it's an array of
2295 * dictionary entries (ie: a dictionary) so we print that
2296 * differently.
2297 */
2298 if (g_variant_get_type_string (value)[1] == '{')
2299 /* dictionary */
2300 {
2301 const gchar *comma = "";
2302 gsize n, i;
2303
2304 if ((n = g_variant_n_children (value)) == 0)
2305 {
2306 if (type_annotate)
2307 g_string_append_printf (string, "@%s ",
2308 g_variant_get_type_string (value));
2309 g_string_append (string, "{}");
2310 break;
2311 }
2312
2313 g_string_append_c (string, '{');
2314 for (i = 0; i < n; i++)
2315 {
2316 GVariant *entry, *key, *val;
2317
2318 g_string_append (string, comma);
2319 comma = ", ";
2320
2321 entry = g_variant_get_child_value (value, i);
2322 key = g_variant_get_child_value (entry, 0);
2323 val = g_variant_get_child_value (entry, 1);
2324 g_variant_unref (entry);
2325
2326 g_variant_print_string (key, string, type_annotate);
2327 g_variant_unref (key);
2328 g_string_append (string, ": ");
2329 g_variant_print_string (val, string, type_annotate);
2330 g_variant_unref (val);
2331 type_annotate = FALSE;
2332 }
2333 g_string_append_c (string, '}');
2334 }
2335 else
2336 /* normal (non-dictionary) array */
2337 {
2338 const gchar *comma = "";
2339 gsize n, i;
2340
2341 if ((n = g_variant_n_children (value)) == 0)
2342 {
2343 if (type_annotate)
2344 g_string_append_printf (string, "@%s ",
2345 g_variant_get_type_string (value));
2346 g_string_append (string, "[]");
2347 break;
2348 }
2349
2350 g_string_append_c (string, '[');
2351 for (i = 0; i < n; i++)
2352 {
2353 GVariant *element;
2354
2355 g_string_append (string, comma);
2356 comma = ", ";
2357
2358 element = g_variant_get_child_value (value, i);
2359
2360 g_variant_print_string (element, string, type_annotate);
2361 g_variant_unref (element);
2362 type_annotate = FALSE;
2363 }
2364 g_string_append_c (string, ']');
2365 }
2366
2367 break;
2368
2369 case G_VARIANT_CLASS_TUPLE:
2370 {
2371 gsize n, i;
2372
2373 n = g_variant_n_children (value);
2374
2375 g_string_append_c (string, '(');
2376 for (i = 0; i < n; i++)
2377 {
2378 GVariant *element;
2379
2380 element = g_variant_get_child_value (value, i);
2381 g_variant_print_string (element, string, type_annotate);
2382 g_string_append (string, ", ");
2383 g_variant_unref (element);
2384 }
2385
2386 /* for >1 item: remove final ", "
2387 * for 1 item: remove final " ", but leave the ","
2388 * for 0 items: there is only "(", so remove nothing
2389 */
2390 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2391 g_string_append_c (string, ')');
2392 }
2393 break;
2394
2395 case G_VARIANT_CLASS_DICT_ENTRY:
2396 {
2397 GVariant *element;
2398
2399 g_string_append_c (string, '{');
2400
2401 element = g_variant_get_child_value (value, 0);
2402 g_variant_print_string (element, string, type_annotate);
2403 g_variant_unref (element);
2404
2405 g_string_append (string, ", ");
2406
2407 element = g_variant_get_child_value (value, 1);
2408 g_variant_print_string (element, string, type_annotate);
2409 g_variant_unref (element);
2410
2411 g_string_append_c (string, '}');
2412 }
2413 break;
2414
2415 case G_VARIANT_CLASS_VARIANT:
2416 {
2417 GVariant *child = g_variant_get_variant (value);
2418
2419 /* Always annotate types in nested variants, because they are
2420 * (by nature) of variable type.
2421 */
2422 g_string_append_c (string, '<');
2423 g_variant_print_string (child, string, TRUE);
2424 g_string_append_c (string, '>');
2425
2426 g_variant_unref (child);
2427 }
2428 break;
2429
2430 case G_VARIANT_CLASS_BOOLEAN:
2431 if (g_variant_get_boolean (value))
2432 g_string_append (string, "true");
2433 else
2434 g_string_append (string, "false");
2435 break;
2436
2437 case G_VARIANT_CLASS_STRING:
2438 {
2439 const gchar *str = g_variant_get_string (value, NULL);
2440 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2441
2442 g_string_append_c (string, quote);
2443
2444 while (*str)
2445 {
2446 gunichar c = g_utf8_get_char (str);
2447
2448 if (c == quote || c == '\\')
2449 g_string_append_c (string, '\\');
2450
2451 if (g_unichar_isprint (c))
2452 g_string_append_unichar (string, c);
2453
2454 else
2455 {
2456 g_string_append_c (string, '\\');
2457 if (c < 0x10000)
2458 switch (c)
2459 {
2460 case '\a':
2461 g_string_append_c (string, 'a');
2462 break;
2463
2464 case '\b':
2465 g_string_append_c (string, 'b');
2466 break;
2467
2468 case '\f':
2469 g_string_append_c (string, 'f');
2470 break;
2471
2472 case '\n':
2473 g_string_append_c (string, 'n');
2474 break;
2475
2476 case '\r':
2477 g_string_append_c (string, 'r');
2478 break;
2479
2480 case '\t':
2481 g_string_append_c (string, 't');
2482 break;
2483
2484 case '\v':
2485 g_string_append_c (string, 'v');
2486 break;
2487
2488 default:
2489 g_string_append_printf (string, "u%04x", c);
2490 break;
2491 }
2492 else
2493 g_string_append_printf (string, "U%08x", c);
2494 }
2495
2496 str = g_utf8_next_char (str);
2497 }
2498
2499 g_string_append_c (string, quote);
2500 }
2501 break;
2502
2503 case G_VARIANT_CLASS_BYTE:
2504 if (type_annotate)
2505 g_string_append (string, "byte ");
2506 g_string_append_printf (string, "0x%02x",
2507 g_variant_get_byte (value));
2508 break;
2509
2510 case G_VARIANT_CLASS_INT16:
2511 if (type_annotate)
2512 g_string_append (string, "int16 ");
2513 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2514 g_variant_get_int16 (value));
2515 break;
2516
2517 case G_VARIANT_CLASS_UINT16:
2518 if (type_annotate)
2519 g_string_append (string, "uint16 ");
2520 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2521 g_variant_get_uint16 (value));
2522 break;
2523
2524 case G_VARIANT_CLASS_INT32:
2525 /* Never annotate this type because it is the default for numbers
2526 * (and this is a *pretty* printer)
2527 */
2528 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2529 g_variant_get_int32 (value));
2530 break;
2531
2532 case G_VARIANT_CLASS_HANDLE:
2533 if (type_annotate)
2534 g_string_append (string, "handle ");
2535 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2536 g_variant_get_handle (value));
2537 break;
2538
2539 case G_VARIANT_CLASS_UINT32:
2540 if (type_annotate)
2541 g_string_append (string, "uint32 ");
2542 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2543 g_variant_get_uint32 (value));
2544 break;
2545
2546 case G_VARIANT_CLASS_INT64:
2547 if (type_annotate)
2548 g_string_append (string, "int64 ");
2549 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2550 g_variant_get_int64 (value));
2551 break;
2552
2553 case G_VARIANT_CLASS_UINT64:
2554 if (type_annotate)
2555 g_string_append (string, "uint64 ");
2556 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2557 g_variant_get_uint64 (value));
2558 break;
2559
2560 case G_VARIANT_CLASS_DOUBLE:
2561 {
2562 gchar buffer[100];
2563 gint i;
2564
2565 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2566
2567 for (i = 0; buffer[i]; i++)
2568 if (buffer[i] == '.' || buffer[i] == 'e' ||
2569 buffer[i] == 'n' || buffer[i] == 'N')
2570 break;
2571
2572 /* if there is no '.' or 'e' in the float then add one */
2573 if (buffer[i] == '\0')
2574 {
2575 buffer[i++] = '.';
2576 buffer[i++] = '0';
2577 buffer[i++] = '\0';
2578 }
2579
2580 g_string_append (string, buffer);
2581 }
2582 break;
2583
2584 case G_VARIANT_CLASS_OBJECT_PATH:
2585 if (type_annotate)
2586 g_string_append (string, "objectpath ");
2587 g_string_append_printf (string, "\'%s\'",
2588 g_variant_get_string (value, NULL));
2589 break;
2590
2591 case G_VARIANT_CLASS_SIGNATURE:
2592 if (type_annotate)
2593 g_string_append (string, "signature ");
2594 g_string_append_printf (string, "\'%s\'",
2595 g_variant_get_string (value, NULL));
2596 break;
2597
2598 default:
2599 g_assert_not_reached ();
2600 }
2601
2602 return string;
2603 }
2604
2605 /**
2606 * g_variant_print:
2607 * @value: a #GVariant
2608 * @type_annotate: %TRUE if type information should be included in
2609 * the output
2610 *
2611 * Pretty-prints @value in the format understood by g_variant_parse().
2612 *
2613 * The format is described [here][gvariant-text].
2614 *
2615 * If @type_annotate is %TRUE, then type information is included in
2616 * the output.
2617 *
2618 * Returns: (transfer full): a newly-allocated string holding the result.
2619 *
2620 * Since: 2.24
2621 */
2622 gchar *
g_variant_print(GVariant * value,gboolean type_annotate)2623 g_variant_print (GVariant *value,
2624 gboolean type_annotate)
2625 {
2626 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2627 FALSE);
2628 }
2629
2630 /* Hash, Equal, Compare {{{1 */
2631 /**
2632 * g_variant_hash:
2633 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2634 *
2635 * Generates a hash value for a #GVariant instance.
2636 *
2637 * The output of this function is guaranteed to be the same for a given
2638 * value only per-process. It may change between different processor
2639 * architectures or even different versions of GLib. Do not use this
2640 * function as a basis for building protocols or file formats.
2641 *
2642 * The type of @value is #gconstpointer only to allow use of this
2643 * function with #GHashTable. @value must be a #GVariant.
2644 *
2645 * Returns: a hash value corresponding to @value
2646 *
2647 * Since: 2.24
2648 **/
2649 guint
g_variant_hash(gconstpointer value_)2650 g_variant_hash (gconstpointer value_)
2651 {
2652 GVariant *value = (GVariant *) value_;
2653
2654 switch (g_variant_classify (value))
2655 {
2656 case G_VARIANT_CLASS_STRING:
2657 case G_VARIANT_CLASS_OBJECT_PATH:
2658 case G_VARIANT_CLASS_SIGNATURE:
2659 return g_str_hash (g_variant_get_string (value, NULL));
2660
2661 case G_VARIANT_CLASS_BOOLEAN:
2662 /* this is a very odd thing to hash... */
2663 return g_variant_get_boolean (value);
2664
2665 case G_VARIANT_CLASS_BYTE:
2666 return g_variant_get_byte (value);
2667
2668 case G_VARIANT_CLASS_INT16:
2669 case G_VARIANT_CLASS_UINT16:
2670 {
2671 const guint16 *ptr;
2672
2673 ptr = g_variant_get_data (value);
2674
2675 if (ptr)
2676 return *ptr;
2677 else
2678 return 0;
2679 }
2680
2681 case G_VARIANT_CLASS_INT32:
2682 case G_VARIANT_CLASS_UINT32:
2683 case G_VARIANT_CLASS_HANDLE:
2684 {
2685 const guint *ptr;
2686
2687 ptr = g_variant_get_data (value);
2688
2689 if (ptr)
2690 return *ptr;
2691 else
2692 return 0;
2693 }
2694
2695 case G_VARIANT_CLASS_INT64:
2696 case G_VARIANT_CLASS_UINT64:
2697 case G_VARIANT_CLASS_DOUBLE:
2698 /* need a separate case for these guys because otherwise
2699 * performance could be quite bad on big endian systems
2700 */
2701 {
2702 const guint *ptr;
2703
2704 ptr = g_variant_get_data (value);
2705
2706 if (ptr)
2707 return ptr[0] + ptr[1];
2708 else
2709 return 0;
2710 }
2711
2712 default:
2713 g_return_val_if_fail (!g_variant_is_container (value), 0);
2714 g_assert_not_reached ();
2715 }
2716 }
2717
2718 /**
2719 * g_variant_equal:
2720 * @one: (type GVariant): a #GVariant instance
2721 * @two: (type GVariant): a #GVariant instance
2722 *
2723 * Checks if @one and @two have the same type and value.
2724 *
2725 * The types of @one and @two are #gconstpointer only to allow use of
2726 * this function with #GHashTable. They must each be a #GVariant.
2727 *
2728 * Returns: %TRUE if @one and @two are equal
2729 *
2730 * Since: 2.24
2731 **/
2732 gboolean
g_variant_equal(gconstpointer one,gconstpointer two)2733 g_variant_equal (gconstpointer one,
2734 gconstpointer two)
2735 {
2736 gboolean equal;
2737
2738 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2739
2740 if (g_variant_get_type_info ((GVariant *) one) !=
2741 g_variant_get_type_info ((GVariant *) two))
2742 return FALSE;
2743
2744 /* if both values are trusted to be in their canonical serialised form
2745 * then a simple memcmp() of their serialised data will answer the
2746 * question.
2747 *
2748 * if not, then this might generate a false negative (since it is
2749 * possible for two different byte sequences to represent the same
2750 * value). for now we solve this by pretty-printing both values and
2751 * comparing the result.
2752 */
2753 if (g_variant_is_trusted ((GVariant *) one) &&
2754 g_variant_is_trusted ((GVariant *) two))
2755 {
2756 gconstpointer data_one, data_two;
2757 gsize size_one, size_two;
2758
2759 size_one = g_variant_get_size ((GVariant *) one);
2760 size_two = g_variant_get_size ((GVariant *) two);
2761
2762 if (size_one != size_two)
2763 return FALSE;
2764
2765 data_one = g_variant_get_data ((GVariant *) one);
2766 data_two = g_variant_get_data ((GVariant *) two);
2767
2768 equal = memcmp (data_one, data_two, size_one) == 0;
2769 }
2770 else
2771 {
2772 gchar *strone, *strtwo;
2773
2774 strone = g_variant_print ((GVariant *) one, FALSE);
2775 strtwo = g_variant_print ((GVariant *) two, FALSE);
2776 equal = strcmp (strone, strtwo) == 0;
2777 g_free (strone);
2778 g_free (strtwo);
2779 }
2780
2781 return equal;
2782 }
2783
2784 /**
2785 * g_variant_compare:
2786 * @one: (type GVariant): a basic-typed #GVariant instance
2787 * @two: (type GVariant): a #GVariant instance of the same type
2788 *
2789 * Compares @one and @two.
2790 *
2791 * The types of @one and @two are #gconstpointer only to allow use of
2792 * this function with #GTree, #GPtrArray, etc. They must each be a
2793 * #GVariant.
2794 *
2795 * Comparison is only defined for basic types (ie: booleans, numbers,
2796 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2797 * ordered in the usual way. Strings are in ASCII lexographical order.
2798 *
2799 * It is a programmer error to attempt to compare container values or
2800 * two values that have types that are not exactly equal. For example,
2801 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2802 * integer. Also note that this function is not particularly
2803 * well-behaved when it comes to comparison of doubles; in particular,
2804 * the handling of incomparable values (ie: NaN) is undefined.
2805 *
2806 * If you only require an equality comparison, g_variant_equal() is more
2807 * general.
2808 *
2809 * Returns: negative value if a < b;
2810 * zero if a = b;
2811 * positive value if a > b.
2812 *
2813 * Since: 2.26
2814 **/
2815 gint
g_variant_compare(gconstpointer one,gconstpointer two)2816 g_variant_compare (gconstpointer one,
2817 gconstpointer two)
2818 {
2819 GVariant *a = (GVariant *) one;
2820 GVariant *b = (GVariant *) two;
2821
2822 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2823
2824 switch (g_variant_classify (a))
2825 {
2826 case G_VARIANT_CLASS_BOOLEAN:
2827 return g_variant_get_boolean (a) -
2828 g_variant_get_boolean (b);
2829
2830 case G_VARIANT_CLASS_BYTE:
2831 return ((gint) g_variant_get_byte (a)) -
2832 ((gint) g_variant_get_byte (b));
2833
2834 case G_VARIANT_CLASS_INT16:
2835 return ((gint) g_variant_get_int16 (a)) -
2836 ((gint) g_variant_get_int16 (b));
2837
2838 case G_VARIANT_CLASS_UINT16:
2839 return ((gint) g_variant_get_uint16 (a)) -
2840 ((gint) g_variant_get_uint16 (b));
2841
2842 case G_VARIANT_CLASS_INT32:
2843 {
2844 gint32 a_val = g_variant_get_int32 (a);
2845 gint32 b_val = g_variant_get_int32 (b);
2846
2847 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2848 }
2849
2850 case G_VARIANT_CLASS_UINT32:
2851 {
2852 guint32 a_val = g_variant_get_uint32 (a);
2853 guint32 b_val = g_variant_get_uint32 (b);
2854
2855 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2856 }
2857
2858 case G_VARIANT_CLASS_INT64:
2859 {
2860 gint64 a_val = g_variant_get_int64 (a);
2861 gint64 b_val = g_variant_get_int64 (b);
2862
2863 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2864 }
2865
2866 case G_VARIANT_CLASS_UINT64:
2867 {
2868 guint64 a_val = g_variant_get_uint64 (a);
2869 guint64 b_val = g_variant_get_uint64 (b);
2870
2871 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2872 }
2873
2874 case G_VARIANT_CLASS_DOUBLE:
2875 {
2876 gdouble a_val = g_variant_get_double (a);
2877 gdouble b_val = g_variant_get_double (b);
2878
2879 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2880 }
2881
2882 case G_VARIANT_CLASS_STRING:
2883 case G_VARIANT_CLASS_OBJECT_PATH:
2884 case G_VARIANT_CLASS_SIGNATURE:
2885 return strcmp (g_variant_get_string (a, NULL),
2886 g_variant_get_string (b, NULL));
2887
2888 default:
2889 g_return_val_if_fail (!g_variant_is_container (a), 0);
2890 g_assert_not_reached ();
2891 }
2892 }
2893
2894 /* GVariantIter {{{1 */
2895 /**
2896 * GVariantIter: (skip)
2897 *
2898 * #GVariantIter is an opaque data structure and can only be accessed
2899 * using the following functions.
2900 **/
2901 struct stack_iter
2902 {
2903 GVariant *value;
2904 gssize n, i;
2905
2906 const gchar *loop_format;
2907
2908 gsize padding[3];
2909 gsize magic;
2910 };
2911
2912 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2913
2914 struct heap_iter
2915 {
2916 struct stack_iter iter;
2917
2918 GVariant *value_ref;
2919 gsize magic;
2920 };
2921
2922 #define GVSI(i) ((struct stack_iter *) (i))
2923 #define GVHI(i) ((struct heap_iter *) (i))
2924 #define GVSI_MAGIC ((gsize) 3579507750u)
2925 #define GVHI_MAGIC ((gsize) 1450270775u)
2926 #define is_valid_iter(i) (i != NULL && \
2927 GVSI(i)->magic == GVSI_MAGIC)
2928 #define is_valid_heap_iter(i) (is_valid_iter(i) && \
2929 GVHI(i)->magic == GVHI_MAGIC)
2930
2931 /**
2932 * g_variant_iter_new:
2933 * @value: a container #GVariant
2934 *
2935 * Creates a heap-allocated #GVariantIter for iterating over the items
2936 * in @value.
2937 *
2938 * Use g_variant_iter_free() to free the return value when you no longer
2939 * need it.
2940 *
2941 * A reference is taken to @value and will be released only when
2942 * g_variant_iter_free() is called.
2943 *
2944 * Returns: (transfer full): a new heap-allocated #GVariantIter
2945 *
2946 * Since: 2.24
2947 **/
2948 GVariantIter *
g_variant_iter_new(GVariant * value)2949 g_variant_iter_new (GVariant *value)
2950 {
2951 GVariantIter *iter;
2952
2953 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2954 GVHI(iter)->value_ref = g_variant_ref (value);
2955 GVHI(iter)->magic = GVHI_MAGIC;
2956
2957 g_variant_iter_init (iter, value);
2958
2959 return iter;
2960 }
2961
2962 /**
2963 * g_variant_iter_init: (skip)
2964 * @iter: a pointer to a #GVariantIter
2965 * @value: a container #GVariant
2966 *
2967 * Initialises (without allocating) a #GVariantIter. @iter may be
2968 * completely uninitialised prior to this call; its old value is
2969 * ignored.
2970 *
2971 * The iterator remains valid for as long as @value exists, and need not
2972 * be freed in any way.
2973 *
2974 * Returns: the number of items in @value
2975 *
2976 * Since: 2.24
2977 **/
2978 gsize
g_variant_iter_init(GVariantIter * iter,GVariant * value)2979 g_variant_iter_init (GVariantIter *iter,
2980 GVariant *value)
2981 {
2982 GVSI(iter)->magic = GVSI_MAGIC;
2983 GVSI(iter)->value = value;
2984 GVSI(iter)->n = g_variant_n_children (value);
2985 GVSI(iter)->i = -1;
2986 GVSI(iter)->loop_format = NULL;
2987
2988 return GVSI(iter)->n;
2989 }
2990
2991 /**
2992 * g_variant_iter_copy:
2993 * @iter: a #GVariantIter
2994 *
2995 * Creates a new heap-allocated #GVariantIter to iterate over the
2996 * container that was being iterated over by @iter. Iteration begins on
2997 * the new iterator from the current position of the old iterator but
2998 * the two copies are independent past that point.
2999 *
3000 * Use g_variant_iter_free() to free the return value when you no longer
3001 * need it.
3002 *
3003 * A reference is taken to the container that @iter is iterating over
3004 * and will be releated only when g_variant_iter_free() is called.
3005 *
3006 * Returns: (transfer full): a new heap-allocated #GVariantIter
3007 *
3008 * Since: 2.24
3009 **/
3010 GVariantIter *
g_variant_iter_copy(GVariantIter * iter)3011 g_variant_iter_copy (GVariantIter *iter)
3012 {
3013 GVariantIter *copy;
3014
3015 g_return_val_if_fail (is_valid_iter (iter), 0);
3016
3017 copy = g_variant_iter_new (GVSI(iter)->value);
3018 GVSI(copy)->i = GVSI(iter)->i;
3019
3020 return copy;
3021 }
3022
3023 /**
3024 * g_variant_iter_n_children:
3025 * @iter: a #GVariantIter
3026 *
3027 * Queries the number of child items in the container that we are
3028 * iterating over. This is the total number of items -- not the number
3029 * of items remaining.
3030 *
3031 * This function might be useful for preallocation of arrays.
3032 *
3033 * Returns: the number of children in the container
3034 *
3035 * Since: 2.24
3036 **/
3037 gsize
g_variant_iter_n_children(GVariantIter * iter)3038 g_variant_iter_n_children (GVariantIter *iter)
3039 {
3040 g_return_val_if_fail (is_valid_iter (iter), 0);
3041
3042 return GVSI(iter)->n;
3043 }
3044
3045 /**
3046 * g_variant_iter_free:
3047 * @iter: (transfer full): a heap-allocated #GVariantIter
3048 *
3049 * Frees a heap-allocated #GVariantIter. Only call this function on
3050 * iterators that were returned by g_variant_iter_new() or
3051 * g_variant_iter_copy().
3052 *
3053 * Since: 2.24
3054 **/
3055 void
g_variant_iter_free(GVariantIter * iter)3056 g_variant_iter_free (GVariantIter *iter)
3057 {
3058 g_return_if_fail (is_valid_heap_iter (iter));
3059
3060 g_variant_unref (GVHI(iter)->value_ref);
3061 GVHI(iter)->magic = 0;
3062
3063 g_slice_free (struct heap_iter, GVHI(iter));
3064 }
3065
3066 /**
3067 * g_variant_iter_next_value:
3068 * @iter: a #GVariantIter
3069 *
3070 * Gets the next item in the container. If no more items remain then
3071 * %NULL is returned.
3072 *
3073 * Use g_variant_unref() to drop your reference on the return value when
3074 * you no longer need it.
3075 *
3076 * Here is an example for iterating with g_variant_iter_next_value():
3077 * |[<!-- language="C" -->
3078 * // recursively iterate a container
3079 * void
3080 * iterate_container_recursive (GVariant *container)
3081 * {
3082 * GVariantIter iter;
3083 * GVariant *child;
3084 *
3085 * g_variant_iter_init (&iter, container);
3086 * while ((child = g_variant_iter_next_value (&iter)))
3087 * {
3088 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3089 *
3090 * if (g_variant_is_container (child))
3091 * iterate_container_recursive (child);
3092 *
3093 * g_variant_unref (child);
3094 * }
3095 * }
3096 * ]|
3097 *
3098 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3099 *
3100 * Since: 2.24
3101 **/
3102 GVariant *
g_variant_iter_next_value(GVariantIter * iter)3103 g_variant_iter_next_value (GVariantIter *iter)
3104 {
3105 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3106
3107 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3108 {
3109 g_critical ("g_variant_iter_next_value: must not be called again "
3110 "after NULL has already been returned.");
3111 return NULL;
3112 }
3113
3114 GVSI(iter)->i++;
3115
3116 if (GVSI(iter)->i < GVSI(iter)->n)
3117 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3118
3119 return NULL;
3120 }
3121
3122 /* GVariantBuilder {{{1 */
3123 /**
3124 * GVariantBuilder:
3125 *
3126 * A utility type for constructing container-type #GVariant instances.
3127 *
3128 * This is an opaque structure and may only be accessed using the
3129 * following functions.
3130 *
3131 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3132 * access it from more than one thread.
3133 **/
3134
3135 struct stack_builder
3136 {
3137 GVariantBuilder *parent;
3138 GVariantType *type;
3139
3140 /* type constraint explicitly specified by 'type'.
3141 * for tuple types, this moves along as we add more items.
3142 */
3143 const GVariantType *expected_type;
3144
3145 /* type constraint implied by previous array item.
3146 */
3147 const GVariantType *prev_item_type;
3148
3149 /* constraints on the number of children. max = -1 for unlimited. */
3150 gsize min_items;
3151 gsize max_items;
3152
3153 /* dynamically-growing pointer array */
3154 GVariant **children;
3155 gsize allocated_children;
3156 gsize offset;
3157
3158 /* set to '1' if all items in the container will have the same type
3159 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3160 */
3161 guint uniform_item_types : 1;
3162
3163 /* set to '1' initially and changed to '0' if an untrusted value is
3164 * added
3165 */
3166 guint trusted : 1;
3167
3168 gsize magic;
3169 };
3170
3171 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3172
3173 struct heap_builder
3174 {
3175 GVariantBuilder builder;
3176 gsize magic;
3177
3178 gint ref_count;
3179 };
3180
3181 #define GVSB(b) ((struct stack_builder *) (b))
3182 #define GVHB(b) ((struct heap_builder *) (b))
3183 #define GVSB_MAGIC ((gsize) 1033660112u)
3184 #define GVSB_MAGIC_PARTIAL ((gsize) 2942751021u)
3185 #define GVHB_MAGIC ((gsize) 3087242682u)
3186 #define is_valid_builder(b) (b != NULL && \
3187 GVSB(b)->magic == GVSB_MAGIC)
3188 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3189
3190 /* Just to make sure that by adding a union to GVariantBuilder, we
3191 * didn't accidentally change ABI. */
3192 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3193
3194 static gboolean
ensure_valid_builder(GVariantBuilder * builder)3195 ensure_valid_builder (GVariantBuilder *builder)
3196 {
3197 if (is_valid_builder (builder))
3198 return TRUE;
3199 if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3200 {
3201 static GVariantBuilder cleared_builder;
3202
3203 /* Make sure that only first two fields were set and the rest is
3204 * zeroed to avoid messing up the builder that had parent
3205 * address equal to GVSB_MAGIC_PARTIAL. */
3206 if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3207 return FALSE;
3208
3209 g_variant_builder_init (builder, builder->u.s.type);
3210 }
3211 return is_valid_builder (builder);
3212 }
3213
3214 /**
3215 * g_variant_builder_new:
3216 * @type: a container type
3217 *
3218 * Allocates and initialises a new #GVariantBuilder.
3219 *
3220 * You should call g_variant_builder_unref() on the return value when it
3221 * is no longer needed. The memory will not be automatically freed by
3222 * any other call.
3223 *
3224 * In most cases it is easier to place a #GVariantBuilder directly on
3225 * the stack of the calling function and initialise it with
3226 * g_variant_builder_init().
3227 *
3228 * Returns: (transfer full): a #GVariantBuilder
3229 *
3230 * Since: 2.24
3231 **/
3232 GVariantBuilder *
g_variant_builder_new(const GVariantType * type)3233 g_variant_builder_new (const GVariantType *type)
3234 {
3235 GVariantBuilder *builder;
3236
3237 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3238 g_variant_builder_init (builder, type);
3239 GVHB(builder)->magic = GVHB_MAGIC;
3240 GVHB(builder)->ref_count = 1;
3241
3242 return builder;
3243 }
3244
3245 /**
3246 * g_variant_builder_unref:
3247 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3248 *
3249 * Decreases the reference count on @builder.
3250 *
3251 * In the event that there are no more references, releases all memory
3252 * associated with the #GVariantBuilder.
3253 *
3254 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3255 * things will happen.
3256 *
3257 * Since: 2.24
3258 **/
3259 void
g_variant_builder_unref(GVariantBuilder * builder)3260 g_variant_builder_unref (GVariantBuilder *builder)
3261 {
3262 g_return_if_fail (is_valid_heap_builder (builder));
3263
3264 if (--GVHB(builder)->ref_count)
3265 return;
3266
3267 g_variant_builder_clear (builder);
3268 GVHB(builder)->magic = 0;
3269
3270 g_slice_free (struct heap_builder, GVHB(builder));
3271 }
3272
3273 /**
3274 * g_variant_builder_ref:
3275 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3276 *
3277 * Increases the reference count on @builder.
3278 *
3279 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3280 * things will happen.
3281 *
3282 * Returns: (transfer full): a new reference to @builder
3283 *
3284 * Since: 2.24
3285 **/
3286 GVariantBuilder *
g_variant_builder_ref(GVariantBuilder * builder)3287 g_variant_builder_ref (GVariantBuilder *builder)
3288 {
3289 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3290
3291 GVHB(builder)->ref_count++;
3292
3293 return builder;
3294 }
3295
3296 /**
3297 * g_variant_builder_clear: (skip)
3298 * @builder: a #GVariantBuilder
3299 *
3300 * Releases all memory associated with a #GVariantBuilder without
3301 * freeing the #GVariantBuilder structure itself.
3302 *
3303 * It typically only makes sense to do this on a stack-allocated
3304 * #GVariantBuilder if you want to abort building the value part-way
3305 * through. This function need not be called if you call
3306 * g_variant_builder_end() and it also doesn't need to be called on
3307 * builders allocated with g_variant_builder_new() (see
3308 * g_variant_builder_unref() for that).
3309 *
3310 * This function leaves the #GVariantBuilder structure set to all-zeros.
3311 * It is valid to call this function on either an initialised
3312 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3313 * to call this function on uninitialised memory.
3314 *
3315 * Since: 2.24
3316 **/
3317 void
g_variant_builder_clear(GVariantBuilder * builder)3318 g_variant_builder_clear (GVariantBuilder *builder)
3319 {
3320 gsize i;
3321
3322 if (GVSB(builder)->magic == 0)
3323 /* all-zeros or partial case */
3324 return;
3325
3326 g_return_if_fail (ensure_valid_builder (builder));
3327
3328 g_variant_type_free (GVSB(builder)->type);
3329
3330 for (i = 0; i < GVSB(builder)->offset; i++)
3331 g_variant_unref (GVSB(builder)->children[i]);
3332
3333 g_free (GVSB(builder)->children);
3334
3335 if (GVSB(builder)->parent)
3336 {
3337 g_variant_builder_clear (GVSB(builder)->parent);
3338 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3339 }
3340
3341 memset (builder, 0, sizeof (GVariantBuilder));
3342 }
3343
3344 /**
3345 * g_variant_builder_init: (skip)
3346 * @builder: a #GVariantBuilder
3347 * @type: a container type
3348 *
3349 * Initialises a #GVariantBuilder structure.
3350 *
3351 * @type must be non-%NULL. It specifies the type of container to
3352 * construct. It can be an indefinite type such as
3353 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3354 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3355 * constructed.
3356 *
3357 * After the builder is initialised, values are added using
3358 * g_variant_builder_add_value() or g_variant_builder_add().
3359 *
3360 * After all the child values are added, g_variant_builder_end() frees
3361 * the memory associated with the builder and returns the #GVariant that
3362 * was created.
3363 *
3364 * This function completely ignores the previous contents of @builder.
3365 * On one hand this means that it is valid to pass in completely
3366 * uninitialised memory. On the other hand, this means that if you are
3367 * initialising over top of an existing #GVariantBuilder you need to
3368 * first call g_variant_builder_clear() in order to avoid leaking
3369 * memory.
3370 *
3371 * You must not call g_variant_builder_ref() or
3372 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3373 * with this function. If you ever pass a reference to a
3374 * #GVariantBuilder outside of the control of your own code then you
3375 * should assume that the person receiving that reference may try to use
3376 * reference counting; you should use g_variant_builder_new() instead of
3377 * this function.
3378 *
3379 * Since: 2.24
3380 **/
3381 void
g_variant_builder_init(GVariantBuilder * builder,const GVariantType * type)3382 g_variant_builder_init (GVariantBuilder *builder,
3383 const GVariantType *type)
3384 {
3385 g_return_if_fail (type != NULL);
3386 g_return_if_fail (g_variant_type_is_container (type));
3387
3388 memset (builder, 0, sizeof (GVariantBuilder));
3389
3390 GVSB(builder)->type = g_variant_type_copy (type);
3391 GVSB(builder)->magic = GVSB_MAGIC;
3392 GVSB(builder)->trusted = TRUE;
3393
3394 switch (*(const gchar *) type)
3395 {
3396 case G_VARIANT_CLASS_VARIANT:
3397 GVSB(builder)->uniform_item_types = TRUE;
3398 GVSB(builder)->allocated_children = 1;
3399 GVSB(builder)->expected_type = NULL;
3400 GVSB(builder)->min_items = 1;
3401 GVSB(builder)->max_items = 1;
3402 break;
3403
3404 case G_VARIANT_CLASS_ARRAY:
3405 GVSB(builder)->uniform_item_types = TRUE;
3406 GVSB(builder)->allocated_children = 8;
3407 GVSB(builder)->expected_type =
3408 g_variant_type_element (GVSB(builder)->type);
3409 GVSB(builder)->min_items = 0;
3410 GVSB(builder)->max_items = -1;
3411 break;
3412
3413 case G_VARIANT_CLASS_MAYBE:
3414 GVSB(builder)->uniform_item_types = TRUE;
3415 GVSB(builder)->allocated_children = 1;
3416 GVSB(builder)->expected_type =
3417 g_variant_type_element (GVSB(builder)->type);
3418 GVSB(builder)->min_items = 0;
3419 GVSB(builder)->max_items = 1;
3420 break;
3421
3422 case G_VARIANT_CLASS_DICT_ENTRY:
3423 GVSB(builder)->uniform_item_types = FALSE;
3424 GVSB(builder)->allocated_children = 2;
3425 GVSB(builder)->expected_type =
3426 g_variant_type_key (GVSB(builder)->type);
3427 GVSB(builder)->min_items = 2;
3428 GVSB(builder)->max_items = 2;
3429 break;
3430
3431 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3432 GVSB(builder)->uniform_item_types = FALSE;
3433 GVSB(builder)->allocated_children = 8;
3434 GVSB(builder)->expected_type = NULL;
3435 GVSB(builder)->min_items = 0;
3436 GVSB(builder)->max_items = -1;
3437 break;
3438
3439 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3440 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3441 GVSB(builder)->expected_type =
3442 g_variant_type_first (GVSB(builder)->type);
3443 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3444 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3445 GVSB(builder)->uniform_item_types = FALSE;
3446 break;
3447
3448 default:
3449 g_assert_not_reached ();
3450 }
3451
3452 GVSB(builder)->children = g_new (GVariant *,
3453 GVSB(builder)->allocated_children);
3454 }
3455
3456 static void
g_variant_builder_make_room(struct stack_builder * builder)3457 g_variant_builder_make_room (struct stack_builder *builder)
3458 {
3459 if (builder->offset == builder->allocated_children)
3460 {
3461 builder->allocated_children *= 2;
3462 builder->children = g_renew (GVariant *, builder->children,
3463 builder->allocated_children);
3464 }
3465 }
3466
3467 /**
3468 * g_variant_builder_add_value:
3469 * @builder: a #GVariantBuilder
3470 * @value: a #GVariant
3471 *
3472 * Adds @value to @builder.
3473 *
3474 * It is an error to call this function in any way that would create an
3475 * inconsistent value to be constructed. Some examples of this are
3476 * putting different types of items into an array, putting the wrong
3477 * types or number of items in a tuple, putting more than one value into
3478 * a variant, etc.
3479 *
3480 * If @value is a floating reference (see g_variant_ref_sink()),
3481 * the @builder instance takes ownership of @value.
3482 *
3483 * Since: 2.24
3484 **/
3485 void
g_variant_builder_add_value(GVariantBuilder * builder,GVariant * value)3486 g_variant_builder_add_value (GVariantBuilder *builder,
3487 GVariant *value)
3488 {
3489 g_return_if_fail (ensure_valid_builder (builder));
3490 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3491 g_return_if_fail (!GVSB(builder)->expected_type ||
3492 g_variant_is_of_type (value,
3493 GVSB(builder)->expected_type));
3494 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3495 g_variant_is_of_type (value,
3496 GVSB(builder)->prev_item_type));
3497
3498 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3499
3500 if (!GVSB(builder)->uniform_item_types)
3501 {
3502 /* advance our expected type pointers */
3503 if (GVSB(builder)->expected_type)
3504 GVSB(builder)->expected_type =
3505 g_variant_type_next (GVSB(builder)->expected_type);
3506
3507 if (GVSB(builder)->prev_item_type)
3508 GVSB(builder)->prev_item_type =
3509 g_variant_type_next (GVSB(builder)->prev_item_type);
3510 }
3511 else
3512 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3513
3514 g_variant_builder_make_room (GVSB(builder));
3515
3516 GVSB(builder)->children[GVSB(builder)->offset++] =
3517 g_variant_ref_sink (value);
3518 }
3519
3520 /**
3521 * g_variant_builder_open:
3522 * @builder: a #GVariantBuilder
3523 * @type: the #GVariantType of the container
3524 *
3525 * Opens a subcontainer inside the given @builder. When done adding
3526 * items to the subcontainer, g_variant_builder_close() must be called. @type
3527 * is the type of the container: so to build a tuple of several values, @type
3528 * must include the tuple itself.
3529 *
3530 * It is an error to call this function in any way that would cause an
3531 * inconsistent value to be constructed (ie: adding too many values or
3532 * a value of an incorrect type).
3533 *
3534 * Example of building a nested variant:
3535 * |[<!-- language="C" -->
3536 * GVariantBuilder builder;
3537 * guint32 some_number = get_number ();
3538 * g_autoptr (GHashTable) some_dict = get_dict ();
3539 * GHashTableIter iter;
3540 * const gchar *key;
3541 * const GVariant *value;
3542 * g_autoptr (GVariant) output = NULL;
3543 *
3544 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3545 * g_variant_builder_add (&builder, "u", some_number);
3546 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3547 *
3548 * g_hash_table_iter_init (&iter, some_dict);
3549 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3550 * {
3551 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3552 * g_variant_builder_add (&builder, "s", key);
3553 * g_variant_builder_add (&builder, "v", value);
3554 * g_variant_builder_close (&builder);
3555 * }
3556 *
3557 * g_variant_builder_close (&builder);
3558 *
3559 * output = g_variant_builder_end (&builder);
3560 * ]|
3561 *
3562 * Since: 2.24
3563 **/
3564 void
g_variant_builder_open(GVariantBuilder * builder,const GVariantType * type)3565 g_variant_builder_open (GVariantBuilder *builder,
3566 const GVariantType *type)
3567 {
3568 GVariantBuilder *parent;
3569
3570 g_return_if_fail (ensure_valid_builder (builder));
3571 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3572 g_return_if_fail (!GVSB(builder)->expected_type ||
3573 g_variant_type_is_subtype_of (type,
3574 GVSB(builder)->expected_type));
3575 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3576 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3577 type));
3578
3579 parent = g_slice_dup (GVariantBuilder, builder);
3580 g_variant_builder_init (builder, type);
3581 GVSB(builder)->parent = parent;
3582
3583 /* push the prev_item_type down into the subcontainer */
3584 if (GVSB(parent)->prev_item_type)
3585 {
3586 if (!GVSB(builder)->uniform_item_types)
3587 /* tuples and dict entries */
3588 GVSB(builder)->prev_item_type =
3589 g_variant_type_first (GVSB(parent)->prev_item_type);
3590
3591 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3592 /* maybes and arrays */
3593 GVSB(builder)->prev_item_type =
3594 g_variant_type_element (GVSB(parent)->prev_item_type);
3595 }
3596 }
3597
3598 /**
3599 * g_variant_builder_close:
3600 * @builder: a #GVariantBuilder
3601 *
3602 * Closes the subcontainer inside the given @builder that was opened by
3603 * the most recent call to g_variant_builder_open().
3604 *
3605 * It is an error to call this function in any way that would create an
3606 * inconsistent value to be constructed (ie: too few values added to the
3607 * subcontainer).
3608 *
3609 * Since: 2.24
3610 **/
3611 void
g_variant_builder_close(GVariantBuilder * builder)3612 g_variant_builder_close (GVariantBuilder *builder)
3613 {
3614 GVariantBuilder *parent;
3615
3616 g_return_if_fail (ensure_valid_builder (builder));
3617 g_return_if_fail (GVSB(builder)->parent != NULL);
3618
3619 parent = GVSB(builder)->parent;
3620 GVSB(builder)->parent = NULL;
3621
3622 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3623 *builder = *parent;
3624
3625 g_slice_free (GVariantBuilder, parent);
3626 }
3627
3628 /*< private >
3629 * g_variant_make_maybe_type:
3630 * @element: a #GVariant
3631 *
3632 * Return the type of a maybe containing @element.
3633 */
3634 static GVariantType *
g_variant_make_maybe_type(GVariant * element)3635 g_variant_make_maybe_type (GVariant *element)
3636 {
3637 return g_variant_type_new_maybe (g_variant_get_type (element));
3638 }
3639
3640 /*< private >
3641 * g_variant_make_array_type:
3642 * @element: a #GVariant
3643 *
3644 * Return the type of an array containing @element.
3645 */
3646 static GVariantType *
g_variant_make_array_type(GVariant * element)3647 g_variant_make_array_type (GVariant *element)
3648 {
3649 return g_variant_type_new_array (g_variant_get_type (element));
3650 }
3651
3652 /**
3653 * g_variant_builder_end:
3654 * @builder: a #GVariantBuilder
3655 *
3656 * Ends the builder process and returns the constructed value.
3657 *
3658 * It is not permissible to use @builder in any way after this call
3659 * except for reference counting operations (in the case of a
3660 * heap-allocated #GVariantBuilder) or by reinitialising it with
3661 * g_variant_builder_init() (in the case of stack-allocated). This
3662 * means that for the stack-allocated builders there is no need to
3663 * call g_variant_builder_clear() after the call to
3664 * g_variant_builder_end().
3665 *
3666 * It is an error to call this function in any way that would create an
3667 * inconsistent value to be constructed (ie: insufficient number of
3668 * items added to a container with a specific number of children
3669 * required). It is also an error to call this function if the builder
3670 * was created with an indefinite array or maybe type and no children
3671 * have been added; in this case it is impossible to infer the type of
3672 * the empty array.
3673 *
3674 * Returns: (transfer none): a new, floating, #GVariant
3675 *
3676 * Since: 2.24
3677 **/
3678 GVariant *
g_variant_builder_end(GVariantBuilder * builder)3679 g_variant_builder_end (GVariantBuilder *builder)
3680 {
3681 GVariantType *my_type;
3682 GVariant *value;
3683
3684 g_return_val_if_fail (ensure_valid_builder (builder), NULL);
3685 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3686 NULL);
3687 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3688 GVSB(builder)->prev_item_type != NULL ||
3689 g_variant_type_is_definite (GVSB(builder)->type),
3690 NULL);
3691
3692 if (g_variant_type_is_definite (GVSB(builder)->type))
3693 my_type = g_variant_type_copy (GVSB(builder)->type);
3694
3695 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3696 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3697
3698 else if (g_variant_type_is_array (GVSB(builder)->type))
3699 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3700
3701 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3702 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3703 GVSB(builder)->offset);
3704
3705 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3706 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3707 GVSB(builder)->children[1]);
3708 else
3709 g_assert_not_reached ();
3710
3711 value = g_variant_new_from_children (my_type,
3712 g_renew (GVariant *,
3713 GVSB(builder)->children,
3714 GVSB(builder)->offset),
3715 GVSB(builder)->offset,
3716 GVSB(builder)->trusted);
3717 GVSB(builder)->children = NULL;
3718 GVSB(builder)->offset = 0;
3719
3720 g_variant_builder_clear (builder);
3721 g_variant_type_free (my_type);
3722
3723 return value;
3724 }
3725
3726 /* GVariantDict {{{1 */
3727
3728 /**
3729 * GVariantDict:
3730 *
3731 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3732 *
3733 * It can be used for doing a sequence of dictionary lookups in an
3734 * efficient way on an existing #GVariant dictionary or it can be used
3735 * to construct new dictionaries with a hashtable-like interface. It
3736 * can also be used for taking existing dictionaries and modifying them
3737 * in order to create new ones.
3738 *
3739 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3740 * dictionaries.
3741 *
3742 * It is possible to use #GVariantDict allocated on the stack or on the
3743 * heap. When using a stack-allocated #GVariantDict, you begin with a
3744 * call to g_variant_dict_init() and free the resources with a call to
3745 * g_variant_dict_clear().
3746 *
3747 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3748 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3749 * and g_variant_dict_unref().
3750 *
3751 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3752 * dictionary-type #GVariant. When used with stack-allocated instances,
3753 * this also implicitly frees all associated memory, but for
3754 * heap-allocated instances, you must still call g_variant_dict_unref()
3755 * afterwards.
3756 *
3757 * You will typically want to use a heap-allocated #GVariantDict when
3758 * you expose it as part of an API. For most other uses, the
3759 * stack-allocated form will be more convenient.
3760 *
3761 * Consider the following two examples that do the same thing in each
3762 * style: take an existing dictionary and look up the "count" uint32
3763 * key, adding 1 to it if it is found, or returning an error if the
3764 * key is not found. Each returns the new dictionary as a floating
3765 * #GVariant.
3766 *
3767 * ## Using a stack-allocated GVariantDict
3768 *
3769 * |[<!-- language="C" -->
3770 * GVariant *
3771 * add_to_count (GVariant *orig,
3772 * GError **error)
3773 * {
3774 * GVariantDict dict;
3775 * guint32 count;
3776 *
3777 * g_variant_dict_init (&dict, orig);
3778 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3779 * {
3780 * g_set_error (...);
3781 * g_variant_dict_clear (&dict);
3782 * return NULL;
3783 * }
3784 *
3785 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3786 *
3787 * return g_variant_dict_end (&dict);
3788 * }
3789 * ]|
3790 *
3791 * ## Using heap-allocated GVariantDict
3792 *
3793 * |[<!-- language="C" -->
3794 * GVariant *
3795 * add_to_count (GVariant *orig,
3796 * GError **error)
3797 * {
3798 * GVariantDict *dict;
3799 * GVariant *result;
3800 * guint32 count;
3801 *
3802 * dict = g_variant_dict_new (orig);
3803 *
3804 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3805 * {
3806 * g_variant_dict_insert (dict, "count", "u", count + 1);
3807 * result = g_variant_dict_end (dict);
3808 * }
3809 * else
3810 * {
3811 * g_set_error (...);
3812 * result = NULL;
3813 * }
3814 *
3815 * g_variant_dict_unref (dict);
3816 *
3817 * return result;
3818 * }
3819 * ]|
3820 *
3821 * Since: 2.40
3822 **/
3823 struct stack_dict
3824 {
3825 GHashTable *values;
3826 gsize magic;
3827 };
3828
3829 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3830
3831 struct heap_dict
3832 {
3833 struct stack_dict dict;
3834 gint ref_count;
3835 gsize magic;
3836 };
3837
3838 #define GVSD(d) ((struct stack_dict *) (d))
3839 #define GVHD(d) ((struct heap_dict *) (d))
3840 #define GVSD_MAGIC ((gsize) 2579507750u)
3841 #define GVSD_MAGIC_PARTIAL ((gsize) 3488698669u)
3842 #define GVHD_MAGIC ((gsize) 2450270775u)
3843 #define is_valid_dict(d) (d != NULL && \
3844 GVSD(d)->magic == GVSD_MAGIC)
3845 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3846
3847 /* Just to make sure that by adding a union to GVariantDict, we didn't
3848 * accidentally change ABI. */
3849 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3850
3851 static gboolean
ensure_valid_dict(GVariantDict * dict)3852 ensure_valid_dict (GVariantDict *dict)
3853 {
3854 if (is_valid_dict (dict))
3855 return TRUE;
3856 if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3857 {
3858 static GVariantDict cleared_dict;
3859
3860 /* Make sure that only first two fields were set and the rest is
3861 * zeroed to avoid messing up the builder that had parent
3862 * address equal to GVSB_MAGIC_PARTIAL. */
3863 if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3864 return FALSE;
3865
3866 g_variant_dict_init (dict, dict->u.s.asv);
3867 }
3868 return is_valid_dict (dict);
3869 }
3870
3871 /**
3872 * g_variant_dict_new:
3873 * @from_asv: (nullable): the #GVariant with which to initialise the
3874 * dictionary
3875 *
3876 * Allocates and initialises a new #GVariantDict.
3877 *
3878 * You should call g_variant_dict_unref() on the return value when it
3879 * is no longer needed. The memory will not be automatically freed by
3880 * any other call.
3881 *
3882 * In some cases it may be easier to place a #GVariantDict directly on
3883 * the stack of the calling function and initialise it with
3884 * g_variant_dict_init(). This is particularly useful when you are
3885 * using #GVariantDict to construct a #GVariant.
3886 *
3887 * Returns: (transfer full): a #GVariantDict
3888 *
3889 * Since: 2.40
3890 **/
3891 GVariantDict *
g_variant_dict_new(GVariant * from_asv)3892 g_variant_dict_new (GVariant *from_asv)
3893 {
3894 GVariantDict *dict;
3895
3896 dict = g_slice_alloc (sizeof (struct heap_dict));
3897 g_variant_dict_init (dict, from_asv);
3898 GVHD(dict)->magic = GVHD_MAGIC;
3899 GVHD(dict)->ref_count = 1;
3900
3901 return dict;
3902 }
3903
3904 /**
3905 * g_variant_dict_init: (skip)
3906 * @dict: a #GVariantDict
3907 * @from_asv: (nullable): the initial value for @dict
3908 *
3909 * Initialises a #GVariantDict structure.
3910 *
3911 * If @from_asv is given, it is used to initialise the dictionary.
3912 *
3913 * This function completely ignores the previous contents of @dict. On
3914 * one hand this means that it is valid to pass in completely
3915 * uninitialised memory. On the other hand, this means that if you are
3916 * initialising over top of an existing #GVariantDict you need to first
3917 * call g_variant_dict_clear() in order to avoid leaking memory.
3918 *
3919 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3920 * #GVariantDict that was initialised with this function. If you ever
3921 * pass a reference to a #GVariantDict outside of the control of your
3922 * own code then you should assume that the person receiving that
3923 * reference may try to use reference counting; you should use
3924 * g_variant_dict_new() instead of this function.
3925 *
3926 * Since: 2.40
3927 **/
3928 void
g_variant_dict_init(GVariantDict * dict,GVariant * from_asv)3929 g_variant_dict_init (GVariantDict *dict,
3930 GVariant *from_asv)
3931 {
3932 GVariantIter iter;
3933 gchar *key;
3934 GVariant *value;
3935
3936 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3937 GVSD(dict)->magic = GVSD_MAGIC;
3938
3939 if (from_asv)
3940 {
3941 g_variant_iter_init (&iter, from_asv);
3942 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3943 g_hash_table_insert (GVSD(dict)->values, key, value);
3944 }
3945 }
3946
3947 /**
3948 * g_variant_dict_lookup:
3949 * @dict: a #GVariantDict
3950 * @key: the key to look up in the dictionary
3951 * @format_string: a GVariant format string
3952 * @...: the arguments to unpack the value into
3953 *
3954 * Looks up a value in a #GVariantDict.
3955 *
3956 * This function is a wrapper around g_variant_dict_lookup_value() and
3957 * g_variant_get(). In the case that %NULL would have been returned,
3958 * this function returns %FALSE. Otherwise, it unpacks the returned
3959 * value and returns %TRUE.
3960 *
3961 * @format_string determines the C types that are used for unpacking the
3962 * values and also determines if the values are copied or borrowed, see the
3963 * section on [GVariant format strings][gvariant-format-strings-pointers].
3964 *
3965 * Returns: %TRUE if a value was unpacked
3966 *
3967 * Since: 2.40
3968 **/
3969 gboolean
g_variant_dict_lookup(GVariantDict * dict,const gchar * key,const gchar * format_string,...)3970 g_variant_dict_lookup (GVariantDict *dict,
3971 const gchar *key,
3972 const gchar *format_string,
3973 ...)
3974 {
3975 GVariant *value;
3976 va_list ap;
3977
3978 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
3979 g_return_val_if_fail (key != NULL, FALSE);
3980 g_return_val_if_fail (format_string != NULL, FALSE);
3981
3982 value = g_hash_table_lookup (GVSD(dict)->values, key);
3983
3984 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3985 return FALSE;
3986
3987 va_start (ap, format_string);
3988 g_variant_get_va (value, format_string, NULL, &ap);
3989 va_end (ap);
3990
3991 return TRUE;
3992 }
3993
3994 /**
3995 * g_variant_dict_lookup_value:
3996 * @dict: a #GVariantDict
3997 * @key: the key to look up in the dictionary
3998 * @expected_type: (nullable): a #GVariantType, or %NULL
3999 *
4000 * Looks up a value in a #GVariantDict.
4001 *
4002 * If @key is not found in @dictionary, %NULL is returned.
4003 *
4004 * The @expected_type string specifies what type of value is expected.
4005 * If the value associated with @key has a different type then %NULL is
4006 * returned.
4007 *
4008 * If the key is found and the value has the correct type, it is
4009 * returned. If @expected_type was specified then any non-%NULL return
4010 * value will have this type.
4011 *
4012 * Returns: (transfer full): the value of the dictionary key, or %NULL
4013 *
4014 * Since: 2.40
4015 **/
4016 GVariant *
g_variant_dict_lookup_value(GVariantDict * dict,const gchar * key,const GVariantType * expected_type)4017 g_variant_dict_lookup_value (GVariantDict *dict,
4018 const gchar *key,
4019 const GVariantType *expected_type)
4020 {
4021 GVariant *result;
4022
4023 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4024 g_return_val_if_fail (key != NULL, NULL);
4025
4026 result = g_hash_table_lookup (GVSD(dict)->values, key);
4027
4028 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4029 return g_variant_ref (result);
4030
4031 return NULL;
4032 }
4033
4034 /**
4035 * g_variant_dict_contains:
4036 * @dict: a #GVariantDict
4037 * @key: the key to look up in the dictionary
4038 *
4039 * Checks if @key exists in @dict.
4040 *
4041 * Returns: %TRUE if @key is in @dict
4042 *
4043 * Since: 2.40
4044 **/
4045 gboolean
g_variant_dict_contains(GVariantDict * dict,const gchar * key)4046 g_variant_dict_contains (GVariantDict *dict,
4047 const gchar *key)
4048 {
4049 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4050 g_return_val_if_fail (key != NULL, FALSE);
4051
4052 return g_hash_table_contains (GVSD(dict)->values, key);
4053 }
4054
4055 /**
4056 * g_variant_dict_insert:
4057 * @dict: a #GVariantDict
4058 * @key: the key to insert a value for
4059 * @format_string: a #GVariant varargs format string
4060 * @...: arguments, as per @format_string
4061 *
4062 * Inserts a value into a #GVariantDict.
4063 *
4064 * This call is a convenience wrapper that is exactly equivalent to
4065 * calling g_variant_new() followed by g_variant_dict_insert_value().
4066 *
4067 * Since: 2.40
4068 **/
4069 void
g_variant_dict_insert(GVariantDict * dict,const gchar * key,const gchar * format_string,...)4070 g_variant_dict_insert (GVariantDict *dict,
4071 const gchar *key,
4072 const gchar *format_string,
4073 ...)
4074 {
4075 va_list ap;
4076
4077 g_return_if_fail (ensure_valid_dict (dict));
4078 g_return_if_fail (key != NULL);
4079 g_return_if_fail (format_string != NULL);
4080
4081 va_start (ap, format_string);
4082 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4083 va_end (ap);
4084 }
4085
4086 /**
4087 * g_variant_dict_insert_value:
4088 * @dict: a #GVariantDict
4089 * @key: the key to insert a value for
4090 * @value: the value to insert
4091 *
4092 * Inserts (or replaces) a key in a #GVariantDict.
4093 *
4094 * @value is consumed if it is floating.
4095 *
4096 * Since: 2.40
4097 **/
4098 void
g_variant_dict_insert_value(GVariantDict * dict,const gchar * key,GVariant * value)4099 g_variant_dict_insert_value (GVariantDict *dict,
4100 const gchar *key,
4101 GVariant *value)
4102 {
4103 g_return_if_fail (ensure_valid_dict (dict));
4104 g_return_if_fail (key != NULL);
4105 g_return_if_fail (value != NULL);
4106
4107 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4108 }
4109
4110 /**
4111 * g_variant_dict_remove:
4112 * @dict: a #GVariantDict
4113 * @key: the key to remove
4114 *
4115 * Removes a key and its associated value from a #GVariantDict.
4116 *
4117 * Returns: %TRUE if the key was found and removed
4118 *
4119 * Since: 2.40
4120 **/
4121 gboolean
g_variant_dict_remove(GVariantDict * dict,const gchar * key)4122 g_variant_dict_remove (GVariantDict *dict,
4123 const gchar *key)
4124 {
4125 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4126 g_return_val_if_fail (key != NULL, FALSE);
4127
4128 return g_hash_table_remove (GVSD(dict)->values, key);
4129 }
4130
4131 /**
4132 * g_variant_dict_clear:
4133 * @dict: a #GVariantDict
4134 *
4135 * Releases all memory associated with a #GVariantDict without freeing
4136 * the #GVariantDict structure itself.
4137 *
4138 * It typically only makes sense to do this on a stack-allocated
4139 * #GVariantDict if you want to abort building the value part-way
4140 * through. This function need not be called if you call
4141 * g_variant_dict_end() and it also doesn't need to be called on dicts
4142 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4143 * that).
4144 *
4145 * It is valid to call this function on either an initialised
4146 * #GVariantDict or one that was previously cleared by an earlier call
4147 * to g_variant_dict_clear() but it is not valid to call this function
4148 * on uninitialised memory.
4149 *
4150 * Since: 2.40
4151 **/
4152 void
g_variant_dict_clear(GVariantDict * dict)4153 g_variant_dict_clear (GVariantDict *dict)
4154 {
4155 if (GVSD(dict)->magic == 0)
4156 /* all-zeros case */
4157 return;
4158
4159 g_return_if_fail (ensure_valid_dict (dict));
4160
4161 g_hash_table_unref (GVSD(dict)->values);
4162 GVSD(dict)->values = NULL;
4163
4164 GVSD(dict)->magic = 0;
4165 }
4166
4167 /**
4168 * g_variant_dict_end:
4169 * @dict: a #GVariantDict
4170 *
4171 * Returns the current value of @dict as a #GVariant of type
4172 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4173 *
4174 * It is not permissible to use @dict in any way after this call except
4175 * for reference counting operations (in the case of a heap-allocated
4176 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4177 * the case of stack-allocated).
4178 *
4179 * Returns: (transfer none): a new, floating, #GVariant
4180 *
4181 * Since: 2.40
4182 **/
4183 GVariant *
g_variant_dict_end(GVariantDict * dict)4184 g_variant_dict_end (GVariantDict *dict)
4185 {
4186 GVariantBuilder builder;
4187 GHashTableIter iter;
4188 gpointer key, value;
4189
4190 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4191
4192 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4193
4194 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4195 while (g_hash_table_iter_next (&iter, &key, &value))
4196 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4197
4198 g_variant_dict_clear (dict);
4199
4200 return g_variant_builder_end (&builder);
4201 }
4202
4203 /**
4204 * g_variant_dict_ref:
4205 * @dict: a heap-allocated #GVariantDict
4206 *
4207 * Increases the reference count on @dict.
4208 *
4209 * Don't call this on stack-allocated #GVariantDict instances or bad
4210 * things will happen.
4211 *
4212 * Returns: (transfer full): a new reference to @dict
4213 *
4214 * Since: 2.40
4215 **/
4216 GVariantDict *
g_variant_dict_ref(GVariantDict * dict)4217 g_variant_dict_ref (GVariantDict *dict)
4218 {
4219 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4220
4221 GVHD(dict)->ref_count++;
4222
4223 return dict;
4224 }
4225
4226 /**
4227 * g_variant_dict_unref:
4228 * @dict: (transfer full): a heap-allocated #GVariantDict
4229 *
4230 * Decreases the reference count on @dict.
4231 *
4232 * In the event that there are no more references, releases all memory
4233 * associated with the #GVariantDict.
4234 *
4235 * Don't call this on stack-allocated #GVariantDict instances or bad
4236 * things will happen.
4237 *
4238 * Since: 2.40
4239 **/
4240 void
g_variant_dict_unref(GVariantDict * dict)4241 g_variant_dict_unref (GVariantDict *dict)
4242 {
4243 g_return_if_fail (is_valid_heap_dict (dict));
4244
4245 if (--GVHD(dict)->ref_count == 0)
4246 {
4247 g_variant_dict_clear (dict);
4248 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4249 }
4250 }
4251
4252
4253 /* Format strings {{{1 */
4254 /*< private >
4255 * g_variant_format_string_scan:
4256 * @string: a string that may be prefixed with a format string
4257 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4258 * or %NULL
4259 * @endptr: (nullable) (default NULL): location to store the end pointer,
4260 * or %NULL
4261 *
4262 * Checks the string pointed to by @string for starting with a properly
4263 * formed #GVariant varargs format string. If no valid format string is
4264 * found then %FALSE is returned.
4265 *
4266 * If @string does start with a valid format string then %TRUE is
4267 * returned. If @endptr is non-%NULL then it is updated to point to the
4268 * first character after the format string.
4269 *
4270 * If @limit is non-%NULL then @limit (and any character after it) will
4271 * not be accessed and the effect is otherwise equivalent to if the
4272 * character at @limit were nul.
4273 *
4274 * See the section on [GVariant format strings][gvariant-format-strings].
4275 *
4276 * Returns: %TRUE if there was a valid format string
4277 *
4278 * Since: 2.24
4279 */
4280 gboolean
g_variant_format_string_scan(const gchar * string,const gchar * limit,const gchar ** endptr)4281 g_variant_format_string_scan (const gchar *string,
4282 const gchar *limit,
4283 const gchar **endptr)
4284 {
4285 #define next_char() (string == limit ? '\0' : *string++)
4286 #define peek_char() (string == limit ? '\0' : *string)
4287 char c;
4288
4289 switch (next_char())
4290 {
4291 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4292 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4293 case 'g': case 'v': case '*': case '?': case 'r':
4294 break;
4295
4296 case 'm':
4297 return g_variant_format_string_scan (string, limit, endptr);
4298
4299 case 'a':
4300 case '@':
4301 return g_variant_type_string_scan (string, limit, endptr);
4302
4303 case '(':
4304 while (peek_char() != ')')
4305 if (!g_variant_format_string_scan (string, limit, &string))
4306 return FALSE;
4307
4308 next_char(); /* consume ')' */
4309 break;
4310
4311 case '{':
4312 c = next_char();
4313
4314 if (c == '&')
4315 {
4316 c = next_char ();
4317
4318 if (c != 's' && c != 'o' && c != 'g')
4319 return FALSE;
4320 }
4321 else
4322 {
4323 if (c == '@')
4324 c = next_char ();
4325
4326 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4327 * The terminating null character is considered to be
4328 * part of the string.
4329 */
4330 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4331 return FALSE;
4332 }
4333
4334 if (!g_variant_format_string_scan (string, limit, &string))
4335 return FALSE;
4336
4337 if (next_char() != '}')
4338 return FALSE;
4339
4340 break;
4341
4342 case '^':
4343 if ((c = next_char()) == 'a')
4344 {
4345 if ((c = next_char()) == '&')
4346 {
4347 if ((c = next_char()) == 'a')
4348 {
4349 if ((c = next_char()) == 'y')
4350 break; /* '^a&ay' */
4351 }
4352
4353 else if (c == 's' || c == 'o')
4354 break; /* '^a&s', '^a&o' */
4355 }
4356
4357 else if (c == 'a')
4358 {
4359 if ((c = next_char()) == 'y')
4360 break; /* '^aay' */
4361 }
4362
4363 else if (c == 's' || c == 'o')
4364 break; /* '^as', '^ao' */
4365
4366 else if (c == 'y')
4367 break; /* '^ay' */
4368 }
4369 else if (c == '&')
4370 {
4371 if ((c = next_char()) == 'a')
4372 {
4373 if ((c = next_char()) == 'y')
4374 break; /* '^&ay' */
4375 }
4376 }
4377
4378 return FALSE;
4379
4380 case '&':
4381 c = next_char();
4382
4383 if (c != 's' && c != 'o' && c != 'g')
4384 return FALSE;
4385
4386 break;
4387
4388 default:
4389 return FALSE;
4390 }
4391
4392 if (endptr != NULL)
4393 *endptr = string;
4394
4395 #undef next_char
4396 #undef peek_char
4397
4398 return TRUE;
4399 }
4400
4401 /**
4402 * g_variant_check_format_string:
4403 * @value: a #GVariant
4404 * @format_string: a valid #GVariant format string
4405 * @copy_only: %TRUE to ensure the format string makes deep copies
4406 *
4407 * Checks if calling g_variant_get() with @format_string on @value would
4408 * be valid from a type-compatibility standpoint. @format_string is
4409 * assumed to be a valid format string (from a syntactic standpoint).
4410 *
4411 * If @copy_only is %TRUE then this function additionally checks that it
4412 * would be safe to call g_variant_unref() on @value immediately after
4413 * the call to g_variant_get() without invalidating the result. This is
4414 * only possible if deep copies are made (ie: there are no pointers to
4415 * the data inside of the soon-to-be-freed #GVariant instance). If this
4416 * check fails then a g_critical() is printed and %FALSE is returned.
4417 *
4418 * This function is meant to be used by functions that wish to provide
4419 * varargs accessors to #GVariant values of uncertain values (eg:
4420 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4421 *
4422 * Returns: %TRUE if @format_string is safe to use
4423 *
4424 * Since: 2.34
4425 */
4426 gboolean
g_variant_check_format_string(GVariant * value,const gchar * format_string,gboolean copy_only)4427 g_variant_check_format_string (GVariant *value,
4428 const gchar *format_string,
4429 gboolean copy_only)
4430 {
4431 const gchar *original_format = format_string;
4432 const gchar *type_string;
4433
4434 /* Interesting factoid: assuming a format string is valid, it can be
4435 * converted to a type string by removing all '@' '&' and '^'
4436 * characters.
4437 *
4438 * Instead of doing that, we can just skip those characters when
4439 * comparing it to the type string of @value.
4440 *
4441 * For the copy-only case we can just drop the '&' from the list of
4442 * characters to skip over. A '&' will never appear in a type string
4443 * so we know that it won't be possible to return %TRUE if it is in a
4444 * format string.
4445 */
4446 type_string = g_variant_get_type_string (value);
4447
4448 while (*type_string || *format_string)
4449 {
4450 gchar format = *format_string++;
4451
4452 switch (format)
4453 {
4454 case '&':
4455 if G_UNLIKELY (copy_only)
4456 {
4457 /* for the love of all that is good, please don't mark this string for translation... */
4458 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4459 "interface to validate the passed format string for type safety. The passed format "
4460 "(%s) contains a '&' character which would result in a pointer being returned to the "
4461 "data inside of a GVariant instance that may no longer exist by the time the function "
4462 "returns. Modify your code to use a format string without '&'.", original_format);
4463 return FALSE;
4464 }
4465
4466 /* fall through */
4467 case '^':
4468 case '@':
4469 /* ignore these 2 (or 3) */
4470 continue;
4471
4472 case '?':
4473 /* attempt to consume one of 'bynqiuxthdsog' */
4474 {
4475 char s = *type_string++;
4476
4477 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4478 return FALSE;
4479 }
4480 continue;
4481
4482 case 'r':
4483 /* ensure it's a tuple */
4484 if (*type_string != '(')
4485 return FALSE;
4486
4487 /* fall through */
4488 case '*':
4489 /* consume a full type string for the '*' or 'r' */
4490 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4491 return FALSE;
4492
4493 continue;
4494
4495 default:
4496 /* attempt to consume exactly one character equal to the format */
4497 if (format != *type_string++)
4498 return FALSE;
4499 }
4500 }
4501
4502 return TRUE;
4503 }
4504
4505 /*< private >
4506 * g_variant_format_string_scan_type:
4507 * @string: a string that may be prefixed with a format string
4508 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4509 * or %NULL
4510 * @endptr: (nullable) (default NULL): location to store the end pointer,
4511 * or %NULL
4512 *
4513 * If @string starts with a valid format string then this function will
4514 * return the type that the format string corresponds to. Otherwise
4515 * this function returns %NULL.
4516 *
4517 * Use g_variant_type_free() to free the return value when you no longer
4518 * need it.
4519 *
4520 * This function is otherwise exactly like
4521 * g_variant_format_string_scan().
4522 *
4523 * Returns: (nullable): a #GVariantType if there was a valid format string
4524 *
4525 * Since: 2.24
4526 */
4527 GVariantType *
g_variant_format_string_scan_type(const gchar * string,const gchar * limit,const gchar ** endptr)4528 g_variant_format_string_scan_type (const gchar *string,
4529 const gchar *limit,
4530 const gchar **endptr)
4531 {
4532 const gchar *my_end;
4533 gchar *dest;
4534 gchar *new;
4535
4536 if (endptr == NULL)
4537 endptr = &my_end;
4538
4539 if (!g_variant_format_string_scan (string, limit, endptr))
4540 return NULL;
4541
4542 dest = new = g_malloc (*endptr - string + 1);
4543 while (string != *endptr)
4544 {
4545 if (*string != '@' && *string != '&' && *string != '^')
4546 *dest++ = *string;
4547 string++;
4548 }
4549 *dest = '\0';
4550
4551 return (GVariantType *) G_VARIANT_TYPE (new);
4552 }
4553
4554 static gboolean
valid_format_string(const gchar * format_string,gboolean single,GVariant * value)4555 valid_format_string (const gchar *format_string,
4556 gboolean single,
4557 GVariant *value)
4558 {
4559 const gchar *endptr;
4560 GVariantType *type;
4561
4562 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4563
4564 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4565 {
4566 if (single)
4567 g_critical ("'%s' is not a valid GVariant format string",
4568 format_string);
4569 else
4570 g_critical ("'%s' does not have a valid GVariant format "
4571 "string as a prefix", format_string);
4572
4573 if (type != NULL)
4574 g_variant_type_free (type);
4575
4576 return FALSE;
4577 }
4578
4579 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4580 {
4581 gchar *fragment;
4582 gchar *typestr;
4583
4584 fragment = g_strndup (format_string, endptr - format_string);
4585 typestr = g_variant_type_dup_string (type);
4586
4587 g_critical ("the GVariant format string '%s' has a type of "
4588 "'%s' but the given value has a type of '%s'",
4589 fragment, typestr, g_variant_get_type_string (value));
4590
4591 g_variant_type_free (type);
4592 g_free (fragment);
4593 g_free (typestr);
4594
4595 return FALSE;
4596 }
4597
4598 g_variant_type_free (type);
4599
4600 return TRUE;
4601 }
4602
4603 /* Variable Arguments {{{1 */
4604 /* We consider 2 main classes of format strings:
4605 *
4606 * - recursive format strings
4607 * these are ones that result in recursion and the collection of
4608 * possibly more than one argument. Maybe types, tuples,
4609 * dictionary entries.
4610 *
4611 * - leaf format string
4612 * these result in the collection of a single argument.
4613 *
4614 * Leaf format strings are further subdivided into two categories:
4615 *
4616 * - single non-null pointer ("nnp")
4617 * these either collect or return a single non-null pointer.
4618 *
4619 * - other
4620 * these collect or return something else (bool, number, etc).
4621 *
4622 * Based on the above, the varargs handling code is split into 4 main parts:
4623 *
4624 * - nnp handling code
4625 * - leaf handling code (which may invoke nnp code)
4626 * - generic handling code (may be recursive, may invoke leaf code)
4627 * - user-facing API (which invokes the generic code)
4628 *
4629 * Each section implements some of the following functions:
4630 *
4631 * - skip:
4632 * collect the arguments for the format string as if
4633 * g_variant_new() had been called, but do nothing with them. used
4634 * for skipping over arguments when constructing a Nothing maybe
4635 * type.
4636 *
4637 * - new:
4638 * create a GVariant *
4639 *
4640 * - get:
4641 * unpack a GVariant *
4642 *
4643 * - free (nnp only):
4644 * free a previously allocated item
4645 */
4646
4647 static gboolean
g_variant_format_string_is_leaf(const gchar * str)4648 g_variant_format_string_is_leaf (const gchar *str)
4649 {
4650 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4651 }
4652
4653 static gboolean
g_variant_format_string_is_nnp(const gchar * str)4654 g_variant_format_string_is_nnp (const gchar *str)
4655 {
4656 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4657 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4658 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4659 }
4660
4661 /* Single non-null pointer ("nnp") {{{2 */
4662 static void
g_variant_valist_free_nnp(const gchar * str,gpointer ptr)4663 g_variant_valist_free_nnp (const gchar *str,
4664 gpointer ptr)
4665 {
4666 switch (*str)
4667 {
4668 case 'a':
4669 g_variant_iter_free (ptr);
4670 break;
4671
4672 case '^':
4673 if (g_str_has_suffix (str, "y"))
4674 {
4675 if (str[2] != 'a') /* '^a&ay', '^ay' */
4676 g_free (ptr);
4677 else if (str[1] == 'a') /* '^aay' */
4678 g_strfreev (ptr);
4679 break; /* '^&ay' */
4680 }
4681 else if (str[2] != '&') /* '^as', '^ao' */
4682 g_strfreev (ptr);
4683 else /* '^a&s', '^a&o' */
4684 g_free (ptr);
4685 break;
4686
4687 case 's':
4688 case 'o':
4689 case 'g':
4690 g_free (ptr);
4691 break;
4692
4693 case '@':
4694 case '*':
4695 case '?':
4696 case 'v':
4697 g_variant_unref (ptr);
4698 break;
4699
4700 case '&':
4701 break;
4702
4703 default:
4704 g_assert_not_reached ();
4705 }
4706 }
4707
4708 static gchar
g_variant_scan_convenience(const gchar ** str,gboolean * constant,guint * arrays)4709 g_variant_scan_convenience (const gchar **str,
4710 gboolean *constant,
4711 guint *arrays)
4712 {
4713 *constant = FALSE;
4714 *arrays = 0;
4715
4716 for (;;)
4717 {
4718 char c = *(*str)++;
4719
4720 if (c == '&')
4721 *constant = TRUE;
4722
4723 else if (c == 'a')
4724 (*arrays)++;
4725
4726 else
4727 return c;
4728 }
4729 }
4730
4731 static GVariant *
g_variant_valist_new_nnp(const gchar ** str,gpointer ptr)4732 g_variant_valist_new_nnp (const gchar **str,
4733 gpointer ptr)
4734 {
4735 if (**str == '&')
4736 (*str)++;
4737
4738 switch (*(*str)++)
4739 {
4740 case 'a':
4741 if (ptr != NULL)
4742 {
4743 const GVariantType *type;
4744 GVariant *value;
4745
4746 value = g_variant_builder_end (ptr);
4747 type = g_variant_get_type (value);
4748
4749 if G_UNLIKELY (!g_variant_type_is_array (type))
4750 g_error ("g_variant_new: expected array GVariantBuilder but "
4751 "the built value has type '%s'",
4752 g_variant_get_type_string (value));
4753
4754 type = g_variant_type_element (type);
4755
4756 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4757 {
4758 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4759 g_error ("g_variant_new: expected GVariantBuilder array element "
4760 "type '%s' but the built value has element type '%s'",
4761 type_string, g_variant_get_type_string (value) + 1);
4762 g_free (type_string);
4763 }
4764
4765 g_variant_type_string_scan (*str, NULL, str);
4766
4767 return value;
4768 }
4769 else
4770
4771 /* special case: NULL pointer for empty array */
4772 {
4773 const GVariantType *type = (GVariantType *) *str;
4774
4775 g_variant_type_string_scan (*str, NULL, str);
4776
4777 if G_UNLIKELY (!g_variant_type_is_definite (type))
4778 g_error ("g_variant_new: NULL pointer given with indefinite "
4779 "array type; unable to determine which type of empty "
4780 "array to construct.");
4781
4782 return g_variant_new_array (type, NULL, 0);
4783 }
4784
4785 case 's':
4786 {
4787 GVariant *value;
4788
4789 value = g_variant_new_string (ptr);
4790
4791 if (value == NULL)
4792 value = g_variant_new_string ("[Invalid UTF-8]");
4793
4794 return value;
4795 }
4796
4797 case 'o':
4798 return g_variant_new_object_path (ptr);
4799
4800 case 'g':
4801 return g_variant_new_signature (ptr);
4802
4803 case '^':
4804 {
4805 gboolean constant;
4806 guint arrays;
4807 gchar type;
4808
4809 type = g_variant_scan_convenience (str, &constant, &arrays);
4810
4811 if (type == 's')
4812 return g_variant_new_strv (ptr, -1);
4813
4814 if (type == 'o')
4815 return g_variant_new_objv (ptr, -1);
4816
4817 if (arrays > 1)
4818 return g_variant_new_bytestring_array (ptr, -1);
4819
4820 return g_variant_new_bytestring (ptr);
4821 }
4822
4823 case '@':
4824 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4825 {
4826 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4827 g_error ("g_variant_new: expected GVariant of type '%s' but "
4828 "received value has type '%s'",
4829 type_string, g_variant_get_type_string (ptr));
4830 g_free (type_string);
4831 }
4832
4833 g_variant_type_string_scan (*str, NULL, str);
4834
4835 return ptr;
4836
4837 case '*':
4838 return ptr;
4839
4840 case '?':
4841 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4842 g_error ("g_variant_new: format string '?' expects basic-typed "
4843 "GVariant, but received value has type '%s'",
4844 g_variant_get_type_string (ptr));
4845
4846 return ptr;
4847
4848 case 'r':
4849 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4850 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4851 "GVariant, but received value has type '%s'",
4852 g_variant_get_type_string (ptr));
4853
4854 return ptr;
4855
4856 case 'v':
4857 return g_variant_new_variant (ptr);
4858
4859 default:
4860 g_assert_not_reached ();
4861 }
4862 }
4863
4864 static gpointer
g_variant_valist_get_nnp(const gchar ** str,GVariant * value)4865 g_variant_valist_get_nnp (const gchar **str,
4866 GVariant *value)
4867 {
4868 switch (*(*str)++)
4869 {
4870 case 'a':
4871 g_variant_type_string_scan (*str, NULL, str);
4872 return g_variant_iter_new (value);
4873
4874 case '&':
4875 (*str)++;
4876 return (gchar *) g_variant_get_string (value, NULL);
4877
4878 case 's':
4879 case 'o':
4880 case 'g':
4881 return g_variant_dup_string (value, NULL);
4882
4883 case '^':
4884 {
4885 gboolean constant;
4886 guint arrays;
4887 gchar type;
4888
4889 type = g_variant_scan_convenience (str, &constant, &arrays);
4890
4891 if (type == 's')
4892 {
4893 if (constant)
4894 return g_variant_get_strv (value, NULL);
4895 else
4896 return g_variant_dup_strv (value, NULL);
4897 }
4898
4899 else if (type == 'o')
4900 {
4901 if (constant)
4902 return g_variant_get_objv (value, NULL);
4903 else
4904 return g_variant_dup_objv (value, NULL);
4905 }
4906
4907 else if (arrays > 1)
4908 {
4909 if (constant)
4910 return g_variant_get_bytestring_array (value, NULL);
4911 else
4912 return g_variant_dup_bytestring_array (value, NULL);
4913 }
4914
4915 else
4916 {
4917 if (constant)
4918 return (gchar *) g_variant_get_bytestring (value);
4919 else
4920 return g_variant_dup_bytestring (value, NULL);
4921 }
4922 }
4923
4924 case '@':
4925 g_variant_type_string_scan (*str, NULL, str);
4926 /* fall through */
4927
4928 case '*':
4929 case '?':
4930 case 'r':
4931 return g_variant_ref (value);
4932
4933 case 'v':
4934 return g_variant_get_variant (value);
4935
4936 default:
4937 g_assert_not_reached ();
4938 }
4939 }
4940
4941 /* Leaves {{{2 */
4942 static void
g_variant_valist_skip_leaf(const gchar ** str,va_list * app)4943 g_variant_valist_skip_leaf (const gchar **str,
4944 va_list *app)
4945 {
4946 if (g_variant_format_string_is_nnp (*str))
4947 {
4948 g_variant_format_string_scan (*str, NULL, str);
4949 va_arg (*app, gpointer);
4950 return;
4951 }
4952
4953 switch (*(*str)++)
4954 {
4955 case 'b':
4956 case 'y':
4957 case 'n':
4958 case 'q':
4959 case 'i':
4960 case 'u':
4961 case 'h':
4962 va_arg (*app, int);
4963 return;
4964
4965 case 'x':
4966 case 't':
4967 va_arg (*app, guint64);
4968 return;
4969
4970 case 'd':
4971 va_arg (*app, gdouble);
4972 return;
4973
4974 default:
4975 g_assert_not_reached ();
4976 }
4977 }
4978
4979 static GVariant *
g_variant_valist_new_leaf(const gchar ** str,va_list * app)4980 g_variant_valist_new_leaf (const gchar **str,
4981 va_list *app)
4982 {
4983 if (g_variant_format_string_is_nnp (*str))
4984 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4985
4986 switch (*(*str)++)
4987 {
4988 case 'b':
4989 return g_variant_new_boolean (va_arg (*app, gboolean));
4990
4991 case 'y':
4992 return g_variant_new_byte (va_arg (*app, guint));
4993
4994 case 'n':
4995 return g_variant_new_int16 (va_arg (*app, gint));
4996
4997 case 'q':
4998 return g_variant_new_uint16 (va_arg (*app, guint));
4999
5000 case 'i':
5001 return g_variant_new_int32 (va_arg (*app, gint));
5002
5003 case 'u':
5004 return g_variant_new_uint32 (va_arg (*app, guint));
5005
5006 case 'x':
5007 return g_variant_new_int64 (va_arg (*app, gint64));
5008
5009 case 't':
5010 return g_variant_new_uint64 (va_arg (*app, guint64));
5011
5012 case 'h':
5013 return g_variant_new_handle (va_arg (*app, gint));
5014
5015 case 'd':
5016 return g_variant_new_double (va_arg (*app, gdouble));
5017
5018 default:
5019 g_assert_not_reached ();
5020 }
5021 }
5022
5023 /* The code below assumes this */
5024 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5025 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5026
5027 static void
g_variant_valist_get_leaf(const gchar ** str,GVariant * value,gboolean free,va_list * app)5028 g_variant_valist_get_leaf (const gchar **str,
5029 GVariant *value,
5030 gboolean free,
5031 va_list *app)
5032 {
5033 gpointer ptr = va_arg (*app, gpointer);
5034
5035 if (ptr == NULL)
5036 {
5037 g_variant_format_string_scan (*str, NULL, str);
5038 return;
5039 }
5040
5041 if (g_variant_format_string_is_nnp (*str))
5042 {
5043 gpointer *nnp = (gpointer *) ptr;
5044
5045 if (free && *nnp != NULL)
5046 g_variant_valist_free_nnp (*str, *nnp);
5047
5048 *nnp = NULL;
5049
5050 if (value != NULL)
5051 *nnp = g_variant_valist_get_nnp (str, value);
5052 else
5053 g_variant_format_string_scan (*str, NULL, str);
5054
5055 return;
5056 }
5057
5058 if (value != NULL)
5059 {
5060 switch (*(*str)++)
5061 {
5062 case 'b':
5063 *(gboolean *) ptr = g_variant_get_boolean (value);
5064 return;
5065
5066 case 'y':
5067 *(guint8 *) ptr = g_variant_get_byte (value);
5068 return;
5069
5070 case 'n':
5071 *(gint16 *) ptr = g_variant_get_int16 (value);
5072 return;
5073
5074 case 'q':
5075 *(guint16 *) ptr = g_variant_get_uint16 (value);
5076 return;
5077
5078 case 'i':
5079 *(gint32 *) ptr = g_variant_get_int32 (value);
5080 return;
5081
5082 case 'u':
5083 *(guint32 *) ptr = g_variant_get_uint32 (value);
5084 return;
5085
5086 case 'x':
5087 *(gint64 *) ptr = g_variant_get_int64 (value);
5088 return;
5089
5090 case 't':
5091 *(guint64 *) ptr = g_variant_get_uint64 (value);
5092 return;
5093
5094 case 'h':
5095 *(gint32 *) ptr = g_variant_get_handle (value);
5096 return;
5097
5098 case 'd':
5099 *(gdouble *) ptr = g_variant_get_double (value);
5100 return;
5101 }
5102 }
5103 else
5104 {
5105 switch (*(*str)++)
5106 {
5107 case 'y':
5108 *(guint8 *) ptr = 0;
5109 return;
5110
5111 case 'n':
5112 case 'q':
5113 *(guint16 *) ptr = 0;
5114 return;
5115
5116 case 'i':
5117 case 'u':
5118 case 'h':
5119 case 'b':
5120 *(guint32 *) ptr = 0;
5121 return;
5122
5123 case 'x':
5124 case 't':
5125 case 'd':
5126 *(guint64 *) ptr = 0;
5127 return;
5128 }
5129 }
5130
5131 g_assert_not_reached ();
5132 }
5133
5134 /* Generic (recursive) {{{2 */
5135 static void
g_variant_valist_skip(const gchar ** str,va_list * app)5136 g_variant_valist_skip (const gchar **str,
5137 va_list *app)
5138 {
5139 if (g_variant_format_string_is_leaf (*str))
5140 g_variant_valist_skip_leaf (str, app);
5141
5142 else if (**str == 'm') /* maybe */
5143 {
5144 (*str)++;
5145
5146 if (!g_variant_format_string_is_nnp (*str))
5147 va_arg (*app, gboolean);
5148
5149 g_variant_valist_skip (str, app);
5150 }
5151 else /* tuple, dictionary entry */
5152 {
5153 g_assert (**str == '(' || **str == '{');
5154 (*str)++;
5155 while (**str != ')' && **str != '}')
5156 g_variant_valist_skip (str, app);
5157 (*str)++;
5158 }
5159 }
5160
5161 static GVariant *
g_variant_valist_new(const gchar ** str,va_list * app)5162 g_variant_valist_new (const gchar **str,
5163 va_list *app)
5164 {
5165 if (g_variant_format_string_is_leaf (*str))
5166 return g_variant_valist_new_leaf (str, app);
5167
5168 if (**str == 'm') /* maybe */
5169 {
5170 GVariantType *type = NULL;
5171 GVariant *value = NULL;
5172
5173 (*str)++;
5174
5175 if (g_variant_format_string_is_nnp (*str))
5176 {
5177 gpointer nnp = va_arg (*app, gpointer);
5178
5179 if (nnp != NULL)
5180 value = g_variant_valist_new_nnp (str, nnp);
5181 else
5182 type = g_variant_format_string_scan_type (*str, NULL, str);
5183 }
5184 else
5185 {
5186 gboolean just = va_arg (*app, gboolean);
5187
5188 if (just)
5189 value = g_variant_valist_new (str, app);
5190 else
5191 {
5192 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5193 g_variant_valist_skip (str, app);
5194 }
5195 }
5196
5197 value = g_variant_new_maybe (type, value);
5198
5199 if (type != NULL)
5200 g_variant_type_free (type);
5201
5202 return value;
5203 }
5204 else /* tuple, dictionary entry */
5205 {
5206 GVariantBuilder b;
5207
5208 if (**str == '(')
5209 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5210 else
5211 {
5212 g_assert (**str == '{');
5213 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5214 }
5215
5216 (*str)++; /* '(' */
5217 while (**str != ')' && **str != '}')
5218 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5219 (*str)++; /* ')' */
5220
5221 return g_variant_builder_end (&b);
5222 }
5223 }
5224
5225 static void
g_variant_valist_get(const gchar ** str,GVariant * value,gboolean free,va_list * app)5226 g_variant_valist_get (const gchar **str,
5227 GVariant *value,
5228 gboolean free,
5229 va_list *app)
5230 {
5231 if (g_variant_format_string_is_leaf (*str))
5232 g_variant_valist_get_leaf (str, value, free, app);
5233
5234 else if (**str == 'm')
5235 {
5236 (*str)++;
5237
5238 if (value != NULL)
5239 value = g_variant_get_maybe (value);
5240
5241 if (!g_variant_format_string_is_nnp (*str))
5242 {
5243 gboolean *ptr = va_arg (*app, gboolean *);
5244
5245 if (ptr != NULL)
5246 *ptr = value != NULL;
5247 }
5248
5249 g_variant_valist_get (str, value, free, app);
5250
5251 if (value != NULL)
5252 g_variant_unref (value);
5253 }
5254
5255 else /* tuple, dictionary entry */
5256 {
5257 gint index = 0;
5258
5259 g_assert (**str == '(' || **str == '{');
5260
5261 (*str)++;
5262 while (**str != ')' && **str != '}')
5263 {
5264 if (value != NULL)
5265 {
5266 GVariant *child = g_variant_get_child_value (value, index++);
5267 g_variant_valist_get (str, child, free, app);
5268 g_variant_unref (child);
5269 }
5270 else
5271 g_variant_valist_get (str, NULL, free, app);
5272 }
5273 (*str)++;
5274 }
5275 }
5276
5277 /* User-facing API {{{2 */
5278 /**
5279 * g_variant_new: (skip)
5280 * @format_string: a #GVariant format string
5281 * @...: arguments, as per @format_string
5282 *
5283 * Creates a new #GVariant instance.
5284 *
5285 * Think of this function as an analogue to g_strdup_printf().
5286 *
5287 * The type of the created instance and the arguments that are expected
5288 * by this function are determined by @format_string. See the section on
5289 * [GVariant format strings][gvariant-format-strings]. Please note that
5290 * the syntax of the format string is very likely to be extended in the
5291 * future.
5292 *
5293 * The first character of the format string must not be '*' '?' '@' or
5294 * 'r'; in essence, a new #GVariant must always be constructed by this
5295 * function (and not merely passed through it unmodified).
5296 *
5297 * Note that the arguments must be of the correct width for their types
5298 * specified in @format_string. This can be achieved by casting them. See
5299 * the [GVariant varargs documentation][gvariant-varargs].
5300 *
5301 * |[<!-- language="C" -->
5302 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5303 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5304 * GVariant *new_variant;
5305 *
5306 * new_variant = g_variant_new ("(t^as)",
5307 * // This cast is required.
5308 * (guint64) some_flags,
5309 * some_strings);
5310 * ]|
5311 *
5312 * Returns: a new floating #GVariant instance
5313 *
5314 * Since: 2.24
5315 **/
5316 GVariant *
g_variant_new(const gchar * format_string,...)5317 g_variant_new (const gchar *format_string,
5318 ...)
5319 {
5320 GVariant *value;
5321 va_list ap;
5322
5323 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5324 format_string[0] != '?' && format_string[0] != '@' &&
5325 format_string[0] != '*' && format_string[0] != 'r',
5326 NULL);
5327
5328 va_start (ap, format_string);
5329 value = g_variant_new_va (format_string, NULL, &ap);
5330 va_end (ap);
5331
5332 return value;
5333 }
5334
5335 /**
5336 * g_variant_new_va: (skip)
5337 * @format_string: a string that is prefixed with a format string
5338 * @endptr: (nullable) (default NULL): location to store the end pointer,
5339 * or %NULL
5340 * @app: a pointer to a #va_list
5341 *
5342 * This function is intended to be used by libraries based on
5343 * #GVariant that want to provide g_variant_new()-like functionality
5344 * to their users.
5345 *
5346 * The API is more general than g_variant_new() to allow a wider range
5347 * of possible uses.
5348 *
5349 * @format_string must still point to a valid format string, but it only
5350 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5351 * non-%NULL then it is updated to point to the first character past the
5352 * end of the format string.
5353 *
5354 * @app is a pointer to a #va_list. The arguments, according to
5355 * @format_string, are collected from this #va_list and the list is left
5356 * pointing to the argument following the last.
5357 *
5358 * Note that the arguments in @app must be of the correct width for their
5359 * types specified in @format_string when collected into the #va_list.
5360 * See the [GVariant varargs documentation][gvariant-varargs].
5361 *
5362 * These two generalisations allow mixing of multiple calls to
5363 * g_variant_new_va() and g_variant_get_va() within a single actual
5364 * varargs call by the user.
5365 *
5366 * The return value will be floating if it was a newly created GVariant
5367 * instance (for example, if the format string was "(ii)"). In the case
5368 * that the format_string was '*', '?', 'r', or a format starting with
5369 * '@' then the collected #GVariant pointer will be returned unmodified,
5370 * without adding any additional references.
5371 *
5372 * In order to behave correctly in all cases it is necessary for the
5373 * calling function to g_variant_ref_sink() the return result before
5374 * returning control to the user that originally provided the pointer.
5375 * At this point, the caller will have their own full reference to the
5376 * result. This can also be done by adding the result to a container,
5377 * or by passing it to another g_variant_new() call.
5378 *
5379 * Returns: a new, usually floating, #GVariant
5380 *
5381 * Since: 2.24
5382 **/
5383 GVariant *
g_variant_new_va(const gchar * format_string,const gchar ** endptr,va_list * app)5384 g_variant_new_va (const gchar *format_string,
5385 const gchar **endptr,
5386 va_list *app)
5387 {
5388 GVariant *value;
5389
5390 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5391 NULL);
5392 g_return_val_if_fail (app != NULL, NULL);
5393
5394 value = g_variant_valist_new (&format_string, app);
5395
5396 if (endptr != NULL)
5397 *endptr = format_string;
5398
5399 return value;
5400 }
5401
5402 /**
5403 * g_variant_get: (skip)
5404 * @value: a #GVariant instance
5405 * @format_string: a #GVariant format string
5406 * @...: arguments, as per @format_string
5407 *
5408 * Deconstructs a #GVariant instance.
5409 *
5410 * Think of this function as an analogue to scanf().
5411 *
5412 * The arguments that are expected by this function are entirely
5413 * determined by @format_string. @format_string also restricts the
5414 * permissible types of @value. It is an error to give a value with
5415 * an incompatible type. See the section on
5416 * [GVariant format strings][gvariant-format-strings].
5417 * Please note that the syntax of the format string is very likely to be
5418 * extended in the future.
5419 *
5420 * @format_string determines the C types that are used for unpacking
5421 * the values and also determines if the values are copied or borrowed,
5422 * see the section on
5423 * [GVariant format strings][gvariant-format-strings-pointers].
5424 *
5425 * Since: 2.24
5426 **/
5427 void
g_variant_get(GVariant * value,const gchar * format_string,...)5428 g_variant_get (GVariant *value,
5429 const gchar *format_string,
5430 ...)
5431 {
5432 va_list ap;
5433
5434 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5435
5436 /* if any direct-pointer-access formats are in use, flatten first */
5437 if (strchr (format_string, '&'))
5438 g_variant_get_data (value);
5439
5440 va_start (ap, format_string);
5441 g_variant_get_va (value, format_string, NULL, &ap);
5442 va_end (ap);
5443 }
5444
5445 /**
5446 * g_variant_get_va: (skip)
5447 * @value: a #GVariant
5448 * @format_string: a string that is prefixed with a format string
5449 * @endptr: (nullable) (default NULL): location to store the end pointer,
5450 * or %NULL
5451 * @app: a pointer to a #va_list
5452 *
5453 * This function is intended to be used by libraries based on #GVariant
5454 * that want to provide g_variant_get()-like functionality to their
5455 * users.
5456 *
5457 * The API is more general than g_variant_get() to allow a wider range
5458 * of possible uses.
5459 *
5460 * @format_string must still point to a valid format string, but it only
5461 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5462 * non-%NULL then it is updated to point to the first character past the
5463 * end of the format string.
5464 *
5465 * @app is a pointer to a #va_list. The arguments, according to
5466 * @format_string, are collected from this #va_list and the list is left
5467 * pointing to the argument following the last.
5468 *
5469 * These two generalisations allow mixing of multiple calls to
5470 * g_variant_new_va() and g_variant_get_va() within a single actual
5471 * varargs call by the user.
5472 *
5473 * @format_string determines the C types that are used for unpacking
5474 * the values and also determines if the values are copied or borrowed,
5475 * see the section on
5476 * [GVariant format strings][gvariant-format-strings-pointers].
5477 *
5478 * Since: 2.24
5479 **/
5480 void
g_variant_get_va(GVariant * value,const gchar * format_string,const gchar ** endptr,va_list * app)5481 g_variant_get_va (GVariant *value,
5482 const gchar *format_string,
5483 const gchar **endptr,
5484 va_list *app)
5485 {
5486 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5487 g_return_if_fail (value != NULL);
5488 g_return_if_fail (app != NULL);
5489
5490 /* if any direct-pointer-access formats are in use, flatten first */
5491 if (strchr (format_string, '&'))
5492 g_variant_get_data (value);
5493
5494 g_variant_valist_get (&format_string, value, FALSE, app);
5495
5496 if (endptr != NULL)
5497 *endptr = format_string;
5498 }
5499
5500 /* Varargs-enabled Utility Functions {{{1 */
5501
5502 /**
5503 * g_variant_builder_add: (skip)
5504 * @builder: a #GVariantBuilder
5505 * @format_string: a #GVariant varargs format string
5506 * @...: arguments, as per @format_string
5507 *
5508 * Adds to a #GVariantBuilder.
5509 *
5510 * This call is a convenience wrapper that is exactly equivalent to
5511 * calling g_variant_new() followed by g_variant_builder_add_value().
5512 *
5513 * Note that the arguments must be of the correct width for their types
5514 * specified in @format_string. This can be achieved by casting them. See
5515 * the [GVariant varargs documentation][gvariant-varargs].
5516 *
5517 * This function might be used as follows:
5518 *
5519 * |[<!-- language="C" -->
5520 * GVariant *
5521 * make_pointless_dictionary (void)
5522 * {
5523 * GVariantBuilder builder;
5524 * int i;
5525 *
5526 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5527 * for (i = 0; i < 16; i++)
5528 * {
5529 * gchar buf[3];
5530 *
5531 * sprintf (buf, "%d", i);
5532 * g_variant_builder_add (&builder, "{is}", i, buf);
5533 * }
5534 *
5535 * return g_variant_builder_end (&builder);
5536 * }
5537 * ]|
5538 *
5539 * Since: 2.24
5540 */
5541 void
g_variant_builder_add(GVariantBuilder * builder,const gchar * format_string,...)5542 g_variant_builder_add (GVariantBuilder *builder,
5543 const gchar *format_string,
5544 ...)
5545 {
5546 GVariant *variant;
5547 va_list ap;
5548
5549 va_start (ap, format_string);
5550 variant = g_variant_new_va (format_string, NULL, &ap);
5551 va_end (ap);
5552
5553 g_variant_builder_add_value (builder, variant);
5554 }
5555
5556 /**
5557 * g_variant_get_child: (skip)
5558 * @value: a container #GVariant
5559 * @index_: the index of the child to deconstruct
5560 * @format_string: a #GVariant format string
5561 * @...: arguments, as per @format_string
5562 *
5563 * Reads a child item out of a container #GVariant instance and
5564 * deconstructs it according to @format_string. This call is
5565 * essentially a combination of g_variant_get_child_value() and
5566 * g_variant_get().
5567 *
5568 * @format_string determines the C types that are used for unpacking
5569 * the values and also determines if the values are copied or borrowed,
5570 * see the section on
5571 * [GVariant format strings][gvariant-format-strings-pointers].
5572 *
5573 * Since: 2.24
5574 **/
5575 void
g_variant_get_child(GVariant * value,gsize index_,const gchar * format_string,...)5576 g_variant_get_child (GVariant *value,
5577 gsize index_,
5578 const gchar *format_string,
5579 ...)
5580 {
5581 GVariant *child;
5582 va_list ap;
5583
5584 /* if any direct-pointer-access formats are in use, flatten first */
5585 if (strchr (format_string, '&'))
5586 g_variant_get_data (value);
5587
5588 child = g_variant_get_child_value (value, index_);
5589 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5590
5591 va_start (ap, format_string);
5592 g_variant_get_va (child, format_string, NULL, &ap);
5593 va_end (ap);
5594
5595 g_variant_unref (child);
5596 }
5597
5598 /**
5599 * g_variant_iter_next: (skip)
5600 * @iter: a #GVariantIter
5601 * @format_string: a GVariant format string
5602 * @...: the arguments to unpack the value into
5603 *
5604 * Gets the next item in the container and unpacks it into the variable
5605 * argument list according to @format_string, returning %TRUE.
5606 *
5607 * If no more items remain then %FALSE is returned.
5608 *
5609 * All of the pointers given on the variable arguments list of this
5610 * function are assumed to point at uninitialised memory. It is the
5611 * responsibility of the caller to free all of the values returned by
5612 * the unpacking process.
5613 *
5614 * Here is an example for memory management with g_variant_iter_next():
5615 * |[<!-- language="C" -->
5616 * // Iterates a dictionary of type 'a{sv}'
5617 * void
5618 * iterate_dictionary (GVariant *dictionary)
5619 * {
5620 * GVariantIter iter;
5621 * GVariant *value;
5622 * gchar *key;
5623 *
5624 * g_variant_iter_init (&iter, dictionary);
5625 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5626 * {
5627 * g_print ("Item '%s' has type '%s'\n", key,
5628 * g_variant_get_type_string (value));
5629 *
5630 * // must free data for ourselves
5631 * g_variant_unref (value);
5632 * g_free (key);
5633 * }
5634 * }
5635 * ]|
5636 *
5637 * For a solution that is likely to be more convenient to C programmers
5638 * when dealing with loops, see g_variant_iter_loop().
5639 *
5640 * @format_string determines the C types that are used for unpacking
5641 * the values and also determines if the values are copied or borrowed.
5642 *
5643 * See the section on
5644 * [GVariant format strings][gvariant-format-strings-pointers].
5645 *
5646 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5647 *
5648 * Since: 2.24
5649 **/
5650 gboolean
g_variant_iter_next(GVariantIter * iter,const gchar * format_string,...)5651 g_variant_iter_next (GVariantIter *iter,
5652 const gchar *format_string,
5653 ...)
5654 {
5655 GVariant *value;
5656
5657 value = g_variant_iter_next_value (iter);
5658
5659 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5660 FALSE);
5661
5662 if (value != NULL)
5663 {
5664 va_list ap;
5665
5666 va_start (ap, format_string);
5667 g_variant_valist_get (&format_string, value, FALSE, &ap);
5668 va_end (ap);
5669
5670 g_variant_unref (value);
5671 }
5672
5673 return value != NULL;
5674 }
5675
5676 /**
5677 * g_variant_iter_loop: (skip)
5678 * @iter: a #GVariantIter
5679 * @format_string: a GVariant format string
5680 * @...: the arguments to unpack the value into
5681 *
5682 * Gets the next item in the container and unpacks it into the variable
5683 * argument list according to @format_string, returning %TRUE.
5684 *
5685 * If no more items remain then %FALSE is returned.
5686 *
5687 * On the first call to this function, the pointers appearing on the
5688 * variable argument list are assumed to point at uninitialised memory.
5689 * On the second and later calls, it is assumed that the same pointers
5690 * will be given and that they will point to the memory as set by the
5691 * previous call to this function. This allows the previous values to
5692 * be freed, as appropriate.
5693 *
5694 * This function is intended to be used with a while loop as
5695 * demonstrated in the following example. This function can only be
5696 * used when iterating over an array. It is only valid to call this
5697 * function with a string constant for the format string and the same
5698 * string constant must be used each time. Mixing calls to this
5699 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5700 * the same iterator causes undefined behavior.
5701 *
5702 * If you break out of a such a while loop using g_variant_iter_loop() then
5703 * you must free or unreference all the unpacked values as you would with
5704 * g_variant_get(). Failure to do so will cause a memory leak.
5705 *
5706 * Here is an example for memory management with g_variant_iter_loop():
5707 * |[<!-- language="C" -->
5708 * // Iterates a dictionary of type 'a{sv}'
5709 * void
5710 * iterate_dictionary (GVariant *dictionary)
5711 * {
5712 * GVariantIter iter;
5713 * GVariant *value;
5714 * gchar *key;
5715 *
5716 * g_variant_iter_init (&iter, dictionary);
5717 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5718 * {
5719 * g_print ("Item '%s' has type '%s'\n", key,
5720 * g_variant_get_type_string (value));
5721 *
5722 * // no need to free 'key' and 'value' here
5723 * // unless breaking out of this loop
5724 * }
5725 * }
5726 * ]|
5727 *
5728 * For most cases you should use g_variant_iter_next().
5729 *
5730 * This function is really only useful when unpacking into #GVariant or
5731 * #GVariantIter in order to allow you to skip the call to
5732 * g_variant_unref() or g_variant_iter_free().
5733 *
5734 * For example, if you are only looping over simple integer and string
5735 * types, g_variant_iter_next() is definitely preferred. For string
5736 * types, use the '&' prefix to avoid allocating any memory at all (and
5737 * thereby avoiding the need to free anything as well).
5738 *
5739 * @format_string determines the C types that are used for unpacking
5740 * the values and also determines if the values are copied or borrowed.
5741 *
5742 * See the section on
5743 * [GVariant format strings][gvariant-format-strings-pointers].
5744 *
5745 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5746 * value
5747 *
5748 * Since: 2.24
5749 **/
5750 gboolean
g_variant_iter_loop(GVariantIter * iter,const gchar * format_string,...)5751 g_variant_iter_loop (GVariantIter *iter,
5752 const gchar *format_string,
5753 ...)
5754 {
5755 gboolean first_time = GVSI(iter)->loop_format == NULL;
5756 GVariant *value;
5757 va_list ap;
5758
5759 g_return_val_if_fail (first_time ||
5760 format_string == GVSI(iter)->loop_format,
5761 FALSE);
5762
5763 if (first_time)
5764 {
5765 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5766 GVSI(iter)->loop_format = format_string;
5767
5768 if (strchr (format_string, '&'))
5769 g_variant_get_data (GVSI(iter)->value);
5770 }
5771
5772 value = g_variant_iter_next_value (iter);
5773
5774 g_return_val_if_fail (!first_time ||
5775 valid_format_string (format_string, TRUE, value),
5776 FALSE);
5777
5778 va_start (ap, format_string);
5779 g_variant_valist_get (&format_string, value, !first_time, &ap);
5780 va_end (ap);
5781
5782 if (value != NULL)
5783 g_variant_unref (value);
5784
5785 return value != NULL;
5786 }
5787
5788 /* Serialised data {{{1 */
5789 static GVariant *
g_variant_deep_copy(GVariant * value)5790 g_variant_deep_copy (GVariant *value)
5791 {
5792 switch (g_variant_classify (value))
5793 {
5794 case G_VARIANT_CLASS_MAYBE:
5795 case G_VARIANT_CLASS_ARRAY:
5796 case G_VARIANT_CLASS_TUPLE:
5797 case G_VARIANT_CLASS_DICT_ENTRY:
5798 case G_VARIANT_CLASS_VARIANT:
5799 {
5800 GVariantBuilder builder;
5801 GVariantIter iter;
5802 GVariant *child;
5803
5804 g_variant_builder_init (&builder, g_variant_get_type (value));
5805 g_variant_iter_init (&iter, value);
5806
5807 while ((child = g_variant_iter_next_value (&iter)))
5808 {
5809 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5810 g_variant_unref (child);
5811 }
5812
5813 return g_variant_builder_end (&builder);
5814 }
5815
5816 case G_VARIANT_CLASS_BOOLEAN:
5817 return g_variant_new_boolean (g_variant_get_boolean (value));
5818
5819 case G_VARIANT_CLASS_BYTE:
5820 return g_variant_new_byte (g_variant_get_byte (value));
5821
5822 case G_VARIANT_CLASS_INT16:
5823 return g_variant_new_int16 (g_variant_get_int16 (value));
5824
5825 case G_VARIANT_CLASS_UINT16:
5826 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5827
5828 case G_VARIANT_CLASS_INT32:
5829 return g_variant_new_int32 (g_variant_get_int32 (value));
5830
5831 case G_VARIANT_CLASS_UINT32:
5832 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5833
5834 case G_VARIANT_CLASS_INT64:
5835 return g_variant_new_int64 (g_variant_get_int64 (value));
5836
5837 case G_VARIANT_CLASS_UINT64:
5838 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5839
5840 case G_VARIANT_CLASS_HANDLE:
5841 return g_variant_new_handle (g_variant_get_handle (value));
5842
5843 case G_VARIANT_CLASS_DOUBLE:
5844 return g_variant_new_double (g_variant_get_double (value));
5845
5846 case G_VARIANT_CLASS_STRING:
5847 return g_variant_new_string (g_variant_get_string (value, NULL));
5848
5849 case G_VARIANT_CLASS_OBJECT_PATH:
5850 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5851
5852 case G_VARIANT_CLASS_SIGNATURE:
5853 return g_variant_new_signature (g_variant_get_string (value, NULL));
5854 }
5855
5856 g_assert_not_reached ();
5857 }
5858
5859 /**
5860 * g_variant_get_normal_form:
5861 * @value: a #GVariant
5862 *
5863 * Gets a #GVariant instance that has the same value as @value and is
5864 * trusted to be in normal form.
5865 *
5866 * If @value is already trusted to be in normal form then a new
5867 * reference to @value is returned.
5868 *
5869 * If @value is not already trusted, then it is scanned to check if it
5870 * is in normal form. If it is found to be in normal form then it is
5871 * marked as trusted and a new reference to it is returned.
5872 *
5873 * If @value is found not to be in normal form then a new trusted
5874 * #GVariant is created with the same value as @value.
5875 *
5876 * It makes sense to call this function if you've received #GVariant
5877 * data from untrusted sources and you want to ensure your serialised
5878 * output is definitely in normal form.
5879 *
5880 * If @value is already in normal form, a new reference will be returned
5881 * (which will be floating if @value is floating). If it is not in normal form,
5882 * the newly created #GVariant will be returned with a single non-floating
5883 * reference. Typically, g_variant_take_ref() should be called on the return
5884 * value from this function to guarantee ownership of a single non-floating
5885 * reference to it.
5886 *
5887 * Returns: (transfer full): a trusted #GVariant
5888 *
5889 * Since: 2.24
5890 **/
5891 GVariant *
g_variant_get_normal_form(GVariant * value)5892 g_variant_get_normal_form (GVariant *value)
5893 {
5894 GVariant *trusted;
5895
5896 if (g_variant_is_normal_form (value))
5897 return g_variant_ref (value);
5898
5899 trusted = g_variant_deep_copy (value);
5900 g_assert (g_variant_is_trusted (trusted));
5901
5902 return g_variant_ref_sink (trusted);
5903 }
5904
5905 /**
5906 * g_variant_byteswap:
5907 * @value: a #GVariant
5908 *
5909 * Performs a byteswapping operation on the contents of @value. The
5910 * result is that all multi-byte numeric data contained in @value is
5911 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5912 * integers as well as file handles and double precision floating point
5913 * values.
5914 *
5915 * This function is an identity mapping on any value that does not
5916 * contain multi-byte numeric data. That include strings, booleans,
5917 * bytes and containers containing only these things (recursively).
5918 *
5919 * The returned value is always in normal form and is marked as trusted.
5920 *
5921 * Returns: (transfer full): the byteswapped form of @value
5922 *
5923 * Since: 2.24
5924 **/
5925 GVariant *
g_variant_byteswap(GVariant * value)5926 g_variant_byteswap (GVariant *value)
5927 {
5928 GVariantTypeInfo *type_info;
5929 guint alignment;
5930 GVariant *new;
5931
5932 type_info = g_variant_get_type_info (value);
5933
5934 g_variant_type_info_query (type_info, &alignment, NULL);
5935
5936 if (alignment)
5937 /* (potentially) contains multi-byte numeric data */
5938 {
5939 GVariantSerialised serialised;
5940 GVariant *trusted;
5941 GBytes *bytes;
5942
5943 trusted = g_variant_get_normal_form (value);
5944 serialised.type_info = g_variant_get_type_info (trusted);
5945 serialised.size = g_variant_get_size (trusted);
5946 serialised.data = g_malloc (serialised.size);
5947 g_variant_store (trusted, serialised.data);
5948 g_variant_unref (trusted);
5949
5950 g_variant_serialised_byteswap (serialised);
5951
5952 bytes = g_bytes_new_take (serialised.data, serialised.size);
5953 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5954 g_bytes_unref (bytes);
5955 }
5956 else
5957 /* contains no multi-byte data */
5958 new = value;
5959
5960 return g_variant_ref_sink (new);
5961 }
5962
5963 /**
5964 * g_variant_new_from_data:
5965 * @type: a definite #GVariantType
5966 * @data: (array length=size) (element-type guint8): the serialised data
5967 * @size: the size of @data
5968 * @trusted: %TRUE if @data is definitely in normal form
5969 * @notify: (scope async): function to call when @data is no longer needed
5970 * @user_data: data for @notify
5971 *
5972 * Creates a new #GVariant instance from serialised data.
5973 *
5974 * @type is the type of #GVariant instance that will be constructed.
5975 * The interpretation of @data depends on knowing the type.
5976 *
5977 * @data is not modified by this function and must remain valid with an
5978 * unchanging value until such a time as @notify is called with
5979 * @user_data. If the contents of @data change before that time then
5980 * the result is undefined.
5981 *
5982 * If @data is trusted to be serialised data in normal form then
5983 * @trusted should be %TRUE. This applies to serialised data created
5984 * within this process or read from a trusted location on the disk (such
5985 * as a file installed in /usr/lib alongside your application). You
5986 * should set trusted to %FALSE if @data is read from the network, a
5987 * file in the user's home directory, etc.
5988 *
5989 * If @data was not stored in this machine's native endianness, any multi-byte
5990 * numeric values in the returned variant will also be in non-native
5991 * endianness. g_variant_byteswap() can be used to recover the original values.
5992 *
5993 * @notify will be called with @user_data when @data is no longer
5994 * needed. The exact time of this call is unspecified and might even be
5995 * before this function returns.
5996 *
5997 * Note: @data must be backed by memory that is aligned appropriately for the
5998 * @type being loaded. Otherwise this function will internally create a copy of
5999 * the memory (since GLib 2.60) or (in older versions) fail and exit the
6000 * process.
6001 *
6002 * Returns: (transfer none): a new floating #GVariant of type @type
6003 *
6004 * Since: 2.24
6005 **/
6006 GVariant *
g_variant_new_from_data(const GVariantType * type,gconstpointer data,gsize size,gboolean trusted,GDestroyNotify notify,gpointer user_data)6007 g_variant_new_from_data (const GVariantType *type,
6008 gconstpointer data,
6009 gsize size,
6010 gboolean trusted,
6011 GDestroyNotify notify,
6012 gpointer user_data)
6013 {
6014 GVariant *value;
6015 GBytes *bytes;
6016
6017 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6018 g_return_val_if_fail (data != NULL || size == 0, NULL);
6019
6020 if (notify)
6021 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6022 else
6023 bytes = g_bytes_new_static (data, size);
6024
6025 value = g_variant_new_from_bytes (type, bytes, trusted);
6026 g_bytes_unref (bytes);
6027
6028 return value;
6029 }
6030
6031 /* Epilogue {{{1 */
6032 /* vim:set foldmethod=marker: */
6033