2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
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.
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.
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/>.
18 * Author: Ryan Lortie <desrt@desrt.ca>
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>
40 * @short_description: strongly typed value datatype
41 * @see_also: GVariantType
43 * #GVariant is a variant datatype; it can contain one or more values
44 * along with information about the type of the values.
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.
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.
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.
57 * For instance, if you want to create a #GVariant holding an integer value you
60 * |[<!-- language="C" -->
61 * GVariant *v = g_variant_new ("u", 40);
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.
67 * More advanced examples of #GVariant in use can be found in documentation for
68 * [GVariant format strings][gvariant-format-strings-pointers].
70 * The range of possible values is determined by the type.
72 * The type system used by #GVariant is #GVariantType.
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.
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().
83 * #GVariant is completely threadsafe. A #GVariant instance can be
84 * concurrently accessed in any way from any number of threads without
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.
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.)
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).
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.
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.
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.
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
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.
133 * ## Serialised Data Memory
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.
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.
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.
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.
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.
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.
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
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.
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.
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
192 * ## Type Information Cache
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.
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
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.
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).
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).
225 * This means that in total, for our "a{sv}" example, 91 bytes of
226 * type information would be allocated.
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.
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.
238 * ## Buffer Management Memory
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().
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.
251 * ## GVariant structure
253 * The size of a #GVariant structure is 6 * (void *). On 32-bit
254 * systems, that's 24 bytes.
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
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
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
287 /* definition of GVariant structure is in gvariant-core.c */
289 /* this is a g_return_val_if_fail() for making
290 * sure a (GVariant *) has the required type.
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 \
300 /* Numeric Type Constructor/Getters {{{1 */
302 * g_variant_new_from_trusted:
303 * @type: the #GVariantType
304 * @data: the data to use
305 * @size: the size of @data
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.
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
315 * Returns: a new floating #GVariant
318 g_variant_new_from_trusted (const GVariantType *type,
325 bytes = g_bytes_new (data, size);
326 value = g_variant_new_from_bytes (type, bytes, TRUE);
327 g_bytes_unref (bytes);
333 * g_variant_new_boolean:
334 * @value: a #gboolean value
336 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
338 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
343 g_variant_new_boolean (gboolean value)
347 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
351 * g_variant_get_boolean:
352 * @value: a boolean #GVariant instance
354 * Returns the boolean value of @value.
356 * It is an error to call this function with a @value of any type
357 * other than %G_VARIANT_TYPE_BOOLEAN.
359 * Returns: %TRUE or %FALSE
364 g_variant_get_boolean (GVariant *value)
368 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
370 data = g_variant_get_data (value);
372 return data != NULL ? *data != 0 : FALSE;
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
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); \
384 ctype g_variant_get_##type (GVariant *value) { \
386 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
387 data = g_variant_get_data (value); \
388 return data != NULL ? *data : 0; \
393 * g_variant_new_byte:
394 * @value: a #guint8 value
396 * Creates a new byte #GVariant instance.
398 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
403 * g_variant_get_byte:
404 * @value: a byte #GVariant instance
406 * Returns the byte value of @value.
408 * It is an error to call this function with a @value of any type
409 * other than %G_VARIANT_TYPE_BYTE.
415 NUMERIC_TYPE (BYTE, byte, guint8)
418 * g_variant_new_int16:
419 * @value: a #gint16 value
421 * Creates a new int16 #GVariant instance.
423 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
428 * g_variant_get_int16:
429 * @value: an int16 #GVariant instance
431 * Returns the 16-bit signed integer value of @value.
433 * It is an error to call this function with a @value of any type
434 * other than %G_VARIANT_TYPE_INT16.
440 NUMERIC_TYPE (INT16, int16, gint16)
443 * g_variant_new_uint16:
444 * @value: a #guint16 value
446 * Creates a new uint16 #GVariant instance.
448 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
453 * g_variant_get_uint16:
454 * @value: a uint16 #GVariant instance
456 * Returns the 16-bit unsigned integer value of @value.
458 * It is an error to call this function with a @value of any type
459 * other than %G_VARIANT_TYPE_UINT16.
461 * Returns: a #guint16
465 NUMERIC_TYPE (UINT16, uint16, guint16)
468 * g_variant_new_int32:
469 * @value: a #gint32 value
471 * Creates a new int32 #GVariant instance.
473 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
478 * g_variant_get_int32:
479 * @value: an int32 #GVariant instance
481 * Returns the 32-bit signed integer value of @value.
483 * It is an error to call this function with a @value of any type
484 * other than %G_VARIANT_TYPE_INT32.
490 NUMERIC_TYPE (INT32, int32, gint32)
493 * g_variant_new_uint32:
494 * @value: a #guint32 value
496 * Creates a new uint32 #GVariant instance.
498 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
503 * g_variant_get_uint32:
504 * @value: a uint32 #GVariant instance
506 * Returns the 32-bit unsigned integer value of @value.
508 * It is an error to call this function with a @value of any type
509 * other than %G_VARIANT_TYPE_UINT32.
511 * Returns: a #guint32
515 NUMERIC_TYPE (UINT32, uint32, guint32)
518 * g_variant_new_int64:
519 * @value: a #gint64 value
521 * Creates a new int64 #GVariant instance.
523 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
528 * g_variant_get_int64:
529 * @value: an int64 #GVariant instance
531 * Returns the 64-bit signed integer value of @value.
533 * It is an error to call this function with a @value of any type
534 * other than %G_VARIANT_TYPE_INT64.
540 NUMERIC_TYPE (INT64, int64, gint64)
543 * g_variant_new_uint64:
544 * @value: a #guint64 value
546 * Creates a new uint64 #GVariant instance.
548 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
553 * g_variant_get_uint64:
554 * @value: a uint64 #GVariant instance
556 * Returns the 64-bit unsigned integer value of @value.
558 * It is an error to call this function with a @value of any type
559 * other than %G_VARIANT_TYPE_UINT64.
561 * Returns: a #guint64
565 NUMERIC_TYPE (UINT64, uint64, guint64)
568 * g_variant_new_handle:
569 * @value: a #gint32 value
571 * Creates a new handle #GVariant instance.
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.
577 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
582 * g_variant_get_handle:
583 * @value: a handle #GVariant instance
585 * Returns the 32-bit signed integer value of @value.
587 * It is an error to call this function with a @value of any type other
588 * than %G_VARIANT_TYPE_HANDLE.
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.
598 NUMERIC_TYPE (HANDLE, handle, gint32)
601 * g_variant_new_double:
602 * @value: a #gdouble floating point value
604 * Creates a new double #GVariant instance.
606 * Returns: (transfer none): a floating reference to a new double #GVariant instance
611 * g_variant_get_double:
612 * @value: a double #GVariant instance
614 * Returns the double precision floating point value of @value.
616 * It is an error to call this function with a @value of any type
617 * other than %G_VARIANT_TYPE_DOUBLE.
619 * Returns: a #gdouble
623 NUMERIC_TYPE (DOUBLE, double, gdouble)
625 /* Container type Constructor / Deconstructors {{{1 */
627 * g_variant_new_maybe:
628 * @child_type: (nullable): the #GVariantType of the child, or %NULL
629 * @child: (nullable): the child value, or %NULL
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.
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
639 * If @child is a floating reference (see g_variant_ref_sink()), the new
640 * instance takes ownership of @child.
642 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
647 g_variant_new_maybe (const GVariantType *child_type,
650 GVariantType *maybe_type;
653 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
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),
660 if (child_type == NULL)
661 child_type = g_variant_get_type (child);
663 maybe_type = g_variant_type_new_maybe (child_type);
670 children = g_new (GVariant *, 1);
671 children[0] = g_variant_ref_sink (child);
672 trusted = g_variant_is_trusted (children[0]);
674 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
677 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
679 g_variant_type_free (maybe_type);
685 * g_variant_get_maybe:
686 * @value: a maybe-typed value
688 * Given a maybe-typed #GVariant instance, extract its value. If the
689 * value is Nothing, then this function returns %NULL.
691 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
696 g_variant_get_maybe (GVariant *value)
698 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
700 if (g_variant_n_children (value))
701 return g_variant_get_child_value (value, 0);
707 * g_variant_new_variant: (constructor)
708 * @value: a #GVariant instance
710 * Boxes @value. The result is a #GVariant instance representing a
711 * variant containing the original value.
713 * If @child is a floating reference (see g_variant_ref_sink()), the new
714 * instance takes ownership of @child.
716 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
721 g_variant_new_variant (GVariant *value)
723 g_return_val_if_fail (value != NULL, NULL);
725 g_variant_ref_sink (value);
727 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
728 g_memdup (&value, sizeof value),
729 1, g_variant_is_trusted (value));
733 * g_variant_get_variant:
734 * @value: a variant #GVariant instance
736 * Unboxes @value. The result is the #GVariant instance that was
737 * contained in @value.
739 * Returns: (transfer full): the item contained in the variant
744 g_variant_get_variant (GVariant *value)
746 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
748 return g_variant_get_child_value (value, 0);
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
758 * Creates a new #GVariant array from @children.
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
765 * The items of the array are taken from the @children array. No entry
766 * in the @children array may be %NULL.
768 * All items in the array must have the same type, which must be the
769 * same as @child_type, if given.
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().
774 * Returns: (transfer none): a floating reference to a new #GVariant array
779 g_variant_new_array (const GVariantType *child_type,
780 GVariant * const *children,
783 GVariantType *array_type;
784 GVariant **my_children;
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);
794 my_children = g_new (GVariant *, n_children);
797 if (child_type == NULL)
798 child_type = g_variant_get_type (children[0]);
799 array_type = g_variant_type_new_array (child_type);
801 for (i = 0; i < n_children; i++)
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]);
808 value = g_variant_new_from_children (array_type, my_children,
809 n_children, trusted);
810 g_variant_type_free (array_type);
816 * g_variant_make_tuple_type:
817 * @children: (array length=n_children): an array of GVariant *
818 * @n_children: the length of @children
820 * Return the type of a tuple containing @children as its items.
822 static GVariantType *
823 g_variant_make_tuple_type (GVariant * const *children,
826 const GVariantType **types;
830 types = g_new (const GVariantType *, n_children);
832 for (i = 0; i < n_children; i++)
833 types[i] = g_variant_get_type (children[i]);
835 type = g_variant_type_new_tuple (types, n_children);
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
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.
850 * If @n_children is 0 then the unit tuple is constructed.
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().
855 * Returns: (transfer none): a floating reference to a new #GVariant tuple
860 g_variant_new_tuple (GVariant * const *children,
863 GVariantType *tuple_type;
864 GVariant **my_children;
869 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
871 my_children = g_new (GVariant *, n_children);
874 for (i = 0; i < n_children; i++)
876 my_children[i] = g_variant_ref_sink (children[i]);
877 trusted &= g_variant_is_trusted (children[i]);
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);
889 * g_variant_make_dict_entry_type:
890 * @key: a #GVariant, the key
891 * @val: a #GVariant, the value
893 * Return the type of a dictionary entry containing @key and @val as its
896 static GVariantType *
897 g_variant_make_dict_entry_type (GVariant *key,
900 return g_variant_type_new_dict_entry (g_variant_get_type (key),
901 g_variant_get_type (val));
905 * g_variant_new_dict_entry: (constructor)
906 * @key: a basic #GVariant, the key
907 * @value: a #GVariant, the value
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).
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().
915 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
920 g_variant_new_dict_entry (GVariant *key,
923 GVariantType *dict_type;
927 g_return_val_if_fail (key != NULL && value != NULL, NULL);
928 g_return_val_if_fail (!g_variant_is_container (key), NULL);
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);
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);
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
949 * Looks up a value in a dictionary #GVariant.
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.
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,
959 * [GVariant format strings][gvariant-format-strings-pointers].
961 * This function is currently implemented with a linear scan. If you
962 * plan to do many lookups then #GVariantDict may be more efficient.
964 * Returns: %TRUE if a value was unpacked
969 g_variant_lookup (GVariant *dictionary,
971 const gchar *format_string,
978 g_variant_get_data (dictionary);
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);
988 va_start (ap, format_string);
989 g_variant_get_va (value, format_string, NULL, &ap);
990 g_variant_unref (value);
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
1006 * Looks up a value in a dictionary #GVariant.
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).
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.
1019 * In either case, if @key is not found in @dictionary, %NULL is returned.
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.
1025 * This function is currently implemented with a linear scan. If you
1026 * plan to do many lookups then #GVariantDict may be more efficient.
1028 * Returns: (transfer full): the value of the dictionary key, or %NULL
1033 g_variant_lookup_value (GVariant *dictionary,
1035 const GVariantType *expected_type)
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*}")),
1047 g_variant_iter_init (&iter, dictionary);
1049 while ((entry = g_variant_iter_next_value (&iter)))
1051 GVariant *entry_key;
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);
1061 g_variant_unref (entry);
1067 value = g_variant_get_child_value (entry, 1);
1068 g_variant_unref (entry);
1070 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1074 tmp = g_variant_get_variant (value);
1075 g_variant_unref (value);
1077 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1079 g_variant_unref (tmp);
1086 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1087 g_variant_is_of_type (value, expected_type), NULL);
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
1098 * Provides access to the serialised data for an array of fixed-sized
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.
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].
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
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
1122 * @n_elements, which must be non-%NULL, is set equal to the number of
1123 * items in the array.
1125 * Returns: (array length=n_elements) (transfer none): a pointer to
1131 g_variant_get_fixed_array (GVariant *value,
1135 GVariantTypeInfo *array_info;
1136 gsize array_element_size;
1140 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1142 g_return_val_if_fail (n_elements != NULL, NULL);
1143 g_return_val_if_fail (element_size > 0, NULL);
1145 array_info = g_variant_get_type_info (value);
1146 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1148 g_return_val_if_fail (array_element_size, NULL);
1150 if G_UNLIKELY (array_element_size != element_size)
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);
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.");
1164 data = g_variant_get_data (value);
1165 size = g_variant_get_size (value);
1167 if (size % element_size)
1170 *n_elements = size / element_size;
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
1185 * Constructs a new array #GVariant instance, where the elements are
1186 * of @element_type type.
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.
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
1197 * @n_elements must be the length of the @elements array.
1199 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1204 g_variant_new_fixed_array (const GVariantType *element_type,
1205 gconstpointer elements,
1209 GVariantType *array_type;
1210 gsize array_element_size;
1211 GVariantTypeInfo *array_info;
1215 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1216 g_return_val_if_fail (element_size > 0, NULL);
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)
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);
1228 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
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);
1237 g_variant_type_free (array_type);
1238 g_variant_type_info_unref (array_info);
1243 /* String type constructor/getters/validation {{{1 */
1245 * g_variant_new_string:
1246 * @string: a normal UTF-8 nul-terminated string
1248 * Creates a string #GVariant with the contents of @string.
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].
1254 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1259 g_variant_new_string (const gchar *string)
1261 g_return_val_if_fail (string != NULL, NULL);
1262 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1264 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1265 string, strlen (string) + 1);
1269 * g_variant_new_take_string: (skip)
1270 * @string: a normal UTF-8 nul-terminated string
1272 * Creates a string #GVariant with the contents of @string.
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().
1277 * This function consumes @string. g_free() will be called on @string
1278 * when it is no longer required.
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
1284 * Returns: (transfer none): a floating reference to a new string
1285 * #GVariant instance
1290 g_variant_new_take_string (gchar *string)
1295 g_return_val_if_fail (string != NULL, NULL);
1296 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
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);
1306 * g_variant_new_printf: (skip)
1307 * @format_string: a printf-style format string
1308 * @...: arguments for @format_string
1310 * Creates a string-type GVariant using printf formatting.
1312 * This is similar to calling g_strdup_printf() and then
1313 * g_variant_new_string() but it saves a temporary variable and an
1316 * Returns: (transfer none): a floating reference to a new string
1317 * #GVariant instance
1322 g_variant_new_printf (const gchar *format_string,
1330 g_return_val_if_fail (format_string != NULL, NULL);
1332 va_start (ap, format_string);
1333 string = g_strdup_vprintf (format_string, ap);
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);
1344 * g_variant_new_object_path:
1345 * @object_path: a normal C nul-terminated string
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.
1351 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1356 g_variant_new_object_path (const gchar *object_path)
1358 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1360 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1361 object_path, strlen (object_path) + 1);
1365 * g_variant_is_object_path:
1366 * @string: a normal C nul-terminated string
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().
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.
1377 * Returns: %TRUE if @string is a D-Bus object path
1382 g_variant_is_object_path (const gchar *string)
1384 g_return_val_if_fail (string != NULL, FALSE);
1386 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1390 * g_variant_new_signature:
1391 * @signature: a normal C nul-terminated string
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.
1397 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1402 g_variant_new_signature (const gchar *signature)
1404 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1406 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1407 signature, strlen (signature) + 1);
1411 * g_variant_is_signature:
1412 * @string: a normal C nul-terminated string
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().
1418 * D-Bus type signatures consist of zero or more definite #GVariantType
1419 * strings in sequence.
1421 * Returns: %TRUE if @string is a D-Bus type signature
1426 g_variant_is_signature (const gchar *string)
1428 g_return_val_if_fail (string != NULL, FALSE);
1430 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
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
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.
1443 * The string will always be UTF-8 encoded, will never be %NULL, and will never
1444 * contain nul bytes.
1446 * If @length is non-%NULL then the length of the string (in bytes) is
1447 * returned there. For trusted values, this information is already
1448 * known. Untrusted values will be validated and, if valid, a strlen() will be
1449 * performed. If invalid, a default value will be returned — for
1450 * %G_VARIANT_TYPE_OBJECT_PATH, this is `"/"`, and for other types it is the
1453 * It is an error to call this function with a @value of any type
1454 * other than those three.
1456 * The return value remains valid as long as @value exists.
1458 * Returns: (transfer none): the constant string, UTF-8 encoded
1463 g_variant_get_string (GVariant *value,
1469 g_return_val_if_fail (value != NULL, NULL);
1470 g_return_val_if_fail (
1471 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1472 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1473 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1475 data = g_variant_get_data (value);
1476 size = g_variant_get_size (value);
1478 if (!g_variant_is_trusted (value))
1480 switch (g_variant_classify (value))
1482 case G_VARIANT_CLASS_STRING:
1483 if (g_variant_serialiser_is_string (data, size))
1490 case G_VARIANT_CLASS_OBJECT_PATH:
1491 if (g_variant_serialiser_is_object_path (data, size))
1498 case G_VARIANT_CLASS_SIGNATURE:
1499 if (g_variant_serialiser_is_signature (data, size))
1507 g_assert_not_reached ();
1518 * g_variant_dup_string:
1519 * @value: a string #GVariant instance
1520 * @length: (out): a pointer to a #gsize, to store the length
1522 * Similar to g_variant_get_string() except that instead of returning
1523 * a constant string, the string is duplicated.
1525 * The string will always be UTF-8 encoded.
1527 * The return value must be freed using g_free().
1529 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1534 g_variant_dup_string (GVariant *value,
1537 return g_strdup (g_variant_get_string (value, length));
1541 * g_variant_new_strv:
1542 * @strv: (array length=length) (element-type utf8): an array of strings
1543 * @length: the length of @strv, or -1
1545 * Constructs an array of strings #GVariant from the given array of
1548 * If @length is -1 then @strv is %NULL-terminated.
1550 * Returns: (transfer none): a new floating #GVariant instance
1555 g_variant_new_strv (const gchar * const *strv,
1559 gsize i, length_unsigned;
1561 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1564 length = g_strv_length ((gchar **) strv);
1565 length_unsigned = length;
1567 strings = g_new (GVariant *, length_unsigned);
1568 for (i = 0; i < length_unsigned; i++)
1569 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1571 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1572 strings, length_unsigned, TRUE);
1576 * g_variant_get_strv:
1577 * @value: an array of strings #GVariant
1578 * @length: (out) (optional): the length of the result, or %NULL
1580 * Gets the contents of an array of strings #GVariant. This call
1581 * makes a shallow copy; the return result should be released with
1582 * g_free(), but the individual strings must not be modified.
1584 * If @length is non-%NULL then the number of elements in the result
1585 * is stored there. In any case, the resulting array will be
1588 * For an empty array, @length will be set to 0 and a pointer to a
1589 * %NULL pointer will be returned.
1591 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1596 g_variant_get_strv (GVariant *value,
1603 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1605 g_variant_get_data (value);
1606 n = g_variant_n_children (value);
1607 strv = g_new (const gchar *, n + 1);
1609 for (i = 0; i < n; i++)
1613 string = g_variant_get_child_value (value, i);
1614 strv[i] = g_variant_get_string (string, NULL);
1615 g_variant_unref (string);
1626 * g_variant_dup_strv:
1627 * @value: an array of strings #GVariant
1628 * @length: (out) (optional): the length of the result, or %NULL
1630 * Gets the contents of an array of strings #GVariant. This call
1631 * makes a deep copy; the return result should be released with
1634 * If @length is non-%NULL then the number of elements in the result
1635 * is stored there. In any case, the resulting array will be
1638 * For an empty array, @length will be set to 0 and a pointer to a
1639 * %NULL pointer will be returned.
1641 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1646 g_variant_dup_strv (GVariant *value,
1653 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1655 n = g_variant_n_children (value);
1656 strv = g_new (gchar *, n + 1);
1658 for (i = 0; i < n; i++)
1662 string = g_variant_get_child_value (value, i);
1663 strv[i] = g_variant_dup_string (string, NULL);
1664 g_variant_unref (string);
1675 * g_variant_new_objv:
1676 * @strv: (array length=length) (element-type utf8): an array of strings
1677 * @length: the length of @strv, or -1
1679 * Constructs an array of object paths #GVariant from the given array of
1682 * Each string must be a valid #GVariant object path; see
1683 * g_variant_is_object_path().
1685 * If @length is -1 then @strv is %NULL-terminated.
1687 * Returns: (transfer none): a new floating #GVariant instance
1692 g_variant_new_objv (const gchar * const *strv,
1696 gsize i, length_unsigned;
1698 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1701 length = g_strv_length ((gchar **) strv);
1702 length_unsigned = length;
1704 strings = g_new (GVariant *, length_unsigned);
1705 for (i = 0; i < length_unsigned; i++)
1706 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1708 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1709 strings, length_unsigned, TRUE);
1713 * g_variant_get_objv:
1714 * @value: an array of object paths #GVariant
1715 * @length: (out) (optional): the length of the result, or %NULL
1717 * Gets the contents of an array of object paths #GVariant. This call
1718 * makes a shallow copy; the return result should be released with
1719 * g_free(), but the individual strings must not be modified.
1721 * If @length is non-%NULL then the number of elements in the result
1722 * is stored there. In any case, the resulting array will be
1725 * For an empty array, @length will be set to 0 and a pointer to a
1726 * %NULL pointer will be returned.
1728 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1733 g_variant_get_objv (GVariant *value,
1740 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1742 g_variant_get_data (value);
1743 n = g_variant_n_children (value);
1744 strv = g_new (const gchar *, n + 1);
1746 for (i = 0; i < n; i++)
1750 string = g_variant_get_child_value (value, i);
1751 strv[i] = g_variant_get_string (string, NULL);
1752 g_variant_unref (string);
1763 * g_variant_dup_objv:
1764 * @value: an array of object paths #GVariant
1765 * @length: (out) (optional): the length of the result, or %NULL
1767 * Gets the contents of an array of object paths #GVariant. This call
1768 * makes a deep copy; the return result should be released with
1771 * If @length is non-%NULL then the number of elements in the result
1772 * is stored there. In any case, the resulting array will be
1775 * For an empty array, @length will be set to 0 and a pointer to a
1776 * %NULL pointer will be returned.
1778 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1783 g_variant_dup_objv (GVariant *value,
1790 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1792 n = g_variant_n_children (value);
1793 strv = g_new (gchar *, n + 1);
1795 for (i = 0; i < n; i++)
1799 string = g_variant_get_child_value (value, i);
1800 strv[i] = g_variant_dup_string (string, NULL);
1801 g_variant_unref (string);
1813 * g_variant_new_bytestring:
1814 * @string: (array zero-terminated=1) (element-type guint8): a normal
1815 * nul-terminated string in no particular encoding
1817 * Creates an array-of-bytes #GVariant with the contents of @string.
1818 * This function is just like g_variant_new_string() except that the
1819 * string need not be valid UTF-8.
1821 * The nul terminator character at the end of the string is stored in
1824 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1829 g_variant_new_bytestring (const gchar *string)
1831 g_return_val_if_fail (string != NULL, NULL);
1833 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1834 string, strlen (string) + 1);
1838 * g_variant_get_bytestring:
1839 * @value: an array-of-bytes #GVariant instance
1841 * Returns the string value of a #GVariant instance with an
1842 * array-of-bytes type. The string has no particular encoding.
1844 * If the array does not end with a nul terminator character, the empty
1845 * string is returned. For this reason, you can always trust that a
1846 * non-%NULL nul-terminated string will be returned by this function.
1848 * If the array contains a nul terminator character somewhere other than
1849 * the last byte then the returned string is the string, up to the first
1850 * such nul character.
1852 * g_variant_get_fixed_array() should be used instead if the array contains
1853 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1855 * It is an error to call this function with a @value that is not an
1858 * The return value remains valid as long as @value exists.
1860 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1861 * the constant string
1866 g_variant_get_bytestring (GVariant *value)
1868 const gchar *string;
1871 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1873 /* Won't be NULL since this is an array type */
1874 string = g_variant_get_data (value);
1875 size = g_variant_get_size (value);
1877 if (size && string[size - 1] == '\0')
1884 * g_variant_dup_bytestring:
1885 * @value: an array-of-bytes #GVariant instance
1886 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1887 * the length (not including the nul terminator)
1889 * Similar to g_variant_get_bytestring() except that instead of
1890 * returning a constant string, the string is duplicated.
1892 * The return value must be freed using g_free().
1894 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1895 * a newly allocated string
1900 g_variant_dup_bytestring (GVariant *value,
1903 const gchar *original = g_variant_get_bytestring (value);
1906 /* don't crash in case get_bytestring() had an assert failure */
1907 if (original == NULL)
1910 size = strlen (original);
1915 return g_memdup (original, size + 1);
1919 * g_variant_new_bytestring_array:
1920 * @strv: (array length=length): an array of strings
1921 * @length: the length of @strv, or -1
1923 * Constructs an array of bytestring #GVariant from the given array of
1926 * If @length is -1 then @strv is %NULL-terminated.
1928 * Returns: (transfer none): a new floating #GVariant instance
1933 g_variant_new_bytestring_array (const gchar * const *strv,
1937 gsize i, length_unsigned;
1939 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1942 length = g_strv_length ((gchar **) strv);
1943 length_unsigned = length;
1945 strings = g_new (GVariant *, length_unsigned);
1946 for (i = 0; i < length_unsigned; i++)
1947 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1949 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1950 strings, length_unsigned, TRUE);
1954 * g_variant_get_bytestring_array:
1955 * @value: an array of array of bytes #GVariant ('aay')
1956 * @length: (out) (optional): the length of the result, or %NULL
1958 * Gets the contents of an array of array of bytes #GVariant. This call
1959 * makes a shallow copy; the return result should be released with
1960 * g_free(), but the individual strings must not be modified.
1962 * If @length is non-%NULL then the number of elements in the result is
1963 * stored there. In any case, the resulting array will be
1966 * For an empty array, @length will be set to 0 and a pointer to a
1967 * %NULL pointer will be returned.
1969 * Returns: (array length=length) (transfer container): an array of constant strings
1974 g_variant_get_bytestring_array (GVariant *value,
1981 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1983 g_variant_get_data (value);
1984 n = g_variant_n_children (value);
1985 strv = g_new (const gchar *, n + 1);
1987 for (i = 0; i < n; i++)
1991 string = g_variant_get_child_value (value, i);
1992 strv[i] = g_variant_get_bytestring (string);
1993 g_variant_unref (string);
2004 * g_variant_dup_bytestring_array:
2005 * @value: an array of array of bytes #GVariant ('aay')
2006 * @length: (out) (optional): the length of the result, or %NULL
2008 * Gets the contents of an array of array of bytes #GVariant. This call
2009 * makes a deep copy; the return result should be released with
2012 * If @length is non-%NULL then the number of elements in the result is
2013 * stored there. In any case, the resulting array will be
2016 * For an empty array, @length will be set to 0 and a pointer to a
2017 * %NULL pointer will be returned.
2019 * Returns: (array length=length) (transfer full): an array of strings
2024 g_variant_dup_bytestring_array (GVariant *value,
2031 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2033 g_variant_get_data (value);
2034 n = g_variant_n_children (value);
2035 strv = g_new (gchar *, n + 1);
2037 for (i = 0; i < n; i++)
2041 string = g_variant_get_child_value (value, i);
2042 strv[i] = g_variant_dup_bytestring (string, NULL);
2043 g_variant_unref (string);
2053 /* Type checking and querying {{{1 */
2055 * g_variant_get_type:
2056 * @value: a #GVariant
2058 * Determines the type of @value.
2060 * The return value is valid for the lifetime of @value and must not
2063 * Returns: a #GVariantType
2067 const GVariantType *
2068 g_variant_get_type (GVariant *value)
2070 GVariantTypeInfo *type_info;
2072 g_return_val_if_fail (value != NULL, NULL);
2074 type_info = g_variant_get_type_info (value);
2076 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2080 * g_variant_get_type_string:
2081 * @value: a #GVariant
2083 * Returns the type string of @value. Unlike the result of calling
2084 * g_variant_type_peek_string(), this string is nul-terminated. This
2085 * string belongs to #GVariant and must not be freed.
2087 * Returns: the type string for the type of @value
2092 g_variant_get_type_string (GVariant *value)
2094 GVariantTypeInfo *type_info;
2096 g_return_val_if_fail (value != NULL, NULL);
2098 type_info = g_variant_get_type_info (value);
2100 return g_variant_type_info_get_type_string (type_info);
2104 * g_variant_is_of_type:
2105 * @value: a #GVariant instance
2106 * @type: a #GVariantType
2108 * Checks if a value has a type matching the provided type.
2110 * Returns: %TRUE if the type of @value matches @type
2115 g_variant_is_of_type (GVariant *value,
2116 const GVariantType *type)
2118 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2122 * g_variant_is_container:
2123 * @value: a #GVariant instance
2125 * Checks if @value is a container.
2127 * Returns: %TRUE if @value is a container
2132 g_variant_is_container (GVariant *value)
2134 return g_variant_type_is_container (g_variant_get_type (value));
2139 * g_variant_classify:
2140 * @value: a #GVariant
2142 * Classifies @value according to its top-level type.
2144 * Returns: the #GVariantClass of @value
2150 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2151 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2152 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2153 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2154 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2155 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2156 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2157 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2158 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2159 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2161 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2162 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2164 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2165 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2166 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2167 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2168 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2169 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2171 * The range of possible top-level types of #GVariant instances.
2176 g_variant_classify (GVariant *value)
2178 g_return_val_if_fail (value != NULL, 0);
2180 return *g_variant_get_type_string (value);
2183 /* Pretty printer {{{1 */
2184 /* This function is not introspectable because if @string is NULL,
2185 @returns is (transfer full), otherwise it is (transfer none), which
2186 is not supported by GObjectIntrospection */
2188 * g_variant_print_string: (skip)
2189 * @value: a #GVariant
2190 * @string: (nullable) (default NULL): a #GString, or %NULL
2191 * @type_annotate: %TRUE if type information should be included in
2194 * Behaves as g_variant_print(), but operates on a #GString.
2196 * If @string is non-%NULL then it is appended to and returned. Else,
2197 * a new empty #GString is allocated and it is returned.
2199 * Returns: a #GString containing the string
2204 g_variant_print_string (GVariant *value,
2206 gboolean type_annotate)
2208 if G_UNLIKELY (string == NULL)
2209 string = g_string_new (NULL);
2211 switch (g_variant_classify (value))
2213 case G_VARIANT_CLASS_MAYBE:
2215 g_string_append_printf (string, "@%s ",
2216 g_variant_get_type_string (value));
2218 if (g_variant_n_children (value))
2220 gchar *printed_child;
2225 * Consider the case of the type "mmi". In this case we could
2226 * write "just just 4", but "4" alone is totally unambiguous,
2227 * so we try to drop "just" where possible.
2229 * We have to be careful not to always drop "just", though,
2230 * since "nothing" needs to be distinguishable from "just
2231 * nothing". The case where we need to ensure we keep the
2232 * "just" is actually exactly the case where we have a nested
2235 * Instead of searching for that nested Nothing, we just print
2236 * the contained value into a separate string and see if we
2237 * end up with "nothing" at the end of it. If so, we need to
2238 * add "just" at our level.
2240 element = g_variant_get_child_value (value, 0);
2241 printed_child = g_variant_print (element, FALSE);
2242 g_variant_unref (element);
2244 if (g_str_has_suffix (printed_child, "nothing"))
2245 g_string_append (string, "just ");
2246 g_string_append (string, printed_child);
2247 g_free (printed_child);
2250 g_string_append (string, "nothing");
2254 case G_VARIANT_CLASS_ARRAY:
2255 /* it's an array so the first character of the type string is 'a'
2257 * if the first two characters are 'ay' then it's a bytestring.
2258 * under certain conditions we print those as strings.
2260 if (g_variant_get_type_string (value)[1] == 'y')
2266 /* first determine if it is a byte string.
2267 * that's when there's a single nul character: at the end.
2269 str = g_variant_get_data (value);
2270 size = g_variant_get_size (value);
2272 for (i = 0; i < size; i++)
2276 /* first nul byte is the last byte -> it's a byte string. */
2279 gchar *escaped = g_strescape (str, NULL);
2281 /* use double quotes only if a ' is in the string */
2282 if (strchr (str, '\''))
2283 g_string_append_printf (string, "b\"%s\"", escaped);
2285 g_string_append_printf (string, "b'%s'", escaped);
2293 /* fall through and handle normally... */
2298 * if the first two characters are 'a{' then it's an array of
2299 * dictionary entries (ie: a dictionary) so we print that
2302 if (g_variant_get_type_string (value)[1] == '{')
2305 const gchar *comma = "";
2308 if ((n = g_variant_n_children (value)) == 0)
2311 g_string_append_printf (string, "@%s ",
2312 g_variant_get_type_string (value));
2313 g_string_append (string, "{}");
2317 g_string_append_c (string, '{');
2318 for (i = 0; i < n; i++)
2320 GVariant *entry, *key, *val;
2322 g_string_append (string, comma);
2325 entry = g_variant_get_child_value (value, i);
2326 key = g_variant_get_child_value (entry, 0);
2327 val = g_variant_get_child_value (entry, 1);
2328 g_variant_unref (entry);
2330 g_variant_print_string (key, string, type_annotate);
2331 g_variant_unref (key);
2332 g_string_append (string, ": ");
2333 g_variant_print_string (val, string, type_annotate);
2334 g_variant_unref (val);
2335 type_annotate = FALSE;
2337 g_string_append_c (string, '}');
2340 /* normal (non-dictionary) array */
2342 const gchar *comma = "";
2345 if ((n = g_variant_n_children (value)) == 0)
2348 g_string_append_printf (string, "@%s ",
2349 g_variant_get_type_string (value));
2350 g_string_append (string, "[]");
2354 g_string_append_c (string, '[');
2355 for (i = 0; i < n; i++)
2359 g_string_append (string, comma);
2362 element = g_variant_get_child_value (value, i);
2364 g_variant_print_string (element, string, type_annotate);
2365 g_variant_unref (element);
2366 type_annotate = FALSE;
2368 g_string_append_c (string, ']');
2373 case G_VARIANT_CLASS_TUPLE:
2377 n = g_variant_n_children (value);
2379 g_string_append_c (string, '(');
2380 for (i = 0; i < n; i++)
2384 element = g_variant_get_child_value (value, i);
2385 g_variant_print_string (element, string, type_annotate);
2386 g_string_append (string, ", ");
2387 g_variant_unref (element);
2390 /* for >1 item: remove final ", "
2391 * for 1 item: remove final " ", but leave the ","
2392 * for 0 items: there is only "(", so remove nothing
2394 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2395 g_string_append_c (string, ')');
2399 case G_VARIANT_CLASS_DICT_ENTRY:
2403 g_string_append_c (string, '{');
2405 element = g_variant_get_child_value (value, 0);
2406 g_variant_print_string (element, string, type_annotate);
2407 g_variant_unref (element);
2409 g_string_append (string, ", ");
2411 element = g_variant_get_child_value (value, 1);
2412 g_variant_print_string (element, string, type_annotate);
2413 g_variant_unref (element);
2415 g_string_append_c (string, '}');
2419 case G_VARIANT_CLASS_VARIANT:
2421 GVariant *child = g_variant_get_variant (value);
2423 /* Always annotate types in nested variants, because they are
2424 * (by nature) of variable type.
2426 g_string_append_c (string, '<');
2427 g_variant_print_string (child, string, TRUE);
2428 g_string_append_c (string, '>');
2430 g_variant_unref (child);
2434 case G_VARIANT_CLASS_BOOLEAN:
2435 if (g_variant_get_boolean (value))
2436 g_string_append (string, "true");
2438 g_string_append (string, "false");
2441 case G_VARIANT_CLASS_STRING:
2443 const gchar *str = g_variant_get_string (value, NULL);
2444 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2446 g_string_append_c (string, quote);
2450 gunichar c = g_utf8_get_char (str);
2452 if (c == quote || c == '\\')
2453 g_string_append_c (string, '\\');
2455 if (g_unichar_isprint (c))
2456 g_string_append_unichar (string, c);
2460 g_string_append_c (string, '\\');
2465 g_string_append_c (string, 'a');
2469 g_string_append_c (string, 'b');
2473 g_string_append_c (string, 'f');
2477 g_string_append_c (string, 'n');
2481 g_string_append_c (string, 'r');
2485 g_string_append_c (string, 't');
2489 g_string_append_c (string, 'v');
2493 g_string_append_printf (string, "u%04x", c);
2497 g_string_append_printf (string, "U%08x", c);
2500 str = g_utf8_next_char (str);
2503 g_string_append_c (string, quote);
2507 case G_VARIANT_CLASS_BYTE:
2509 g_string_append (string, "byte ");
2510 g_string_append_printf (string, "0x%02x",
2511 g_variant_get_byte (value));
2514 case G_VARIANT_CLASS_INT16:
2516 g_string_append (string, "int16 ");
2517 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2518 g_variant_get_int16 (value));
2521 case G_VARIANT_CLASS_UINT16:
2523 g_string_append (string, "uint16 ");
2524 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2525 g_variant_get_uint16 (value));
2528 case G_VARIANT_CLASS_INT32:
2529 /* Never annotate this type because it is the default for numbers
2530 * (and this is a *pretty* printer)
2532 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2533 g_variant_get_int32 (value));
2536 case G_VARIANT_CLASS_HANDLE:
2538 g_string_append (string, "handle ");
2539 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2540 g_variant_get_handle (value));
2543 case G_VARIANT_CLASS_UINT32:
2545 g_string_append (string, "uint32 ");
2546 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2547 g_variant_get_uint32 (value));
2550 case G_VARIANT_CLASS_INT64:
2552 g_string_append (string, "int64 ");
2553 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2554 g_variant_get_int64 (value));
2557 case G_VARIANT_CLASS_UINT64:
2559 g_string_append (string, "uint64 ");
2560 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2561 g_variant_get_uint64 (value));
2564 case G_VARIANT_CLASS_DOUBLE:
2569 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2571 for (i = 0; buffer[i]; i++)
2572 if (buffer[i] == '.' || buffer[i] == 'e' ||
2573 buffer[i] == 'n' || buffer[i] == 'N')
2576 /* if there is no '.' or 'e' in the float then add one */
2577 if (buffer[i] == '\0')
2584 g_string_append (string, buffer);
2588 case G_VARIANT_CLASS_OBJECT_PATH:
2590 g_string_append (string, "objectpath ");
2591 g_string_append_printf (string, "\'%s\'",
2592 g_variant_get_string (value, NULL));
2595 case G_VARIANT_CLASS_SIGNATURE:
2597 g_string_append (string, "signature ");
2598 g_string_append_printf (string, "\'%s\'",
2599 g_variant_get_string (value, NULL));
2603 g_assert_not_reached ();
2611 * @value: a #GVariant
2612 * @type_annotate: %TRUE if type information should be included in
2615 * Pretty-prints @value in the format understood by g_variant_parse().
2617 * The format is described [here][gvariant-text].
2619 * If @type_annotate is %TRUE, then type information is included in
2622 * Returns: (transfer full): a newly-allocated string holding the result.
2627 g_variant_print (GVariant *value,
2628 gboolean type_annotate)
2630 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2634 /* Hash, Equal, Compare {{{1 */
2637 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2639 * Generates a hash value for a #GVariant instance.
2641 * The output of this function is guaranteed to be the same for a given
2642 * value only per-process. It may change between different processor
2643 * architectures or even different versions of GLib. Do not use this
2644 * function as a basis for building protocols or file formats.
2646 * The type of @value is #gconstpointer only to allow use of this
2647 * function with #GHashTable. @value must be a #GVariant.
2649 * Returns: a hash value corresponding to @value
2654 g_variant_hash (gconstpointer value_)
2656 GVariant *value = (GVariant *) value_;
2658 switch (g_variant_classify (value))
2660 case G_VARIANT_CLASS_STRING:
2661 case G_VARIANT_CLASS_OBJECT_PATH:
2662 case G_VARIANT_CLASS_SIGNATURE:
2663 return g_str_hash (g_variant_get_string (value, NULL));
2665 case G_VARIANT_CLASS_BOOLEAN:
2666 /* this is a very odd thing to hash... */
2667 return g_variant_get_boolean (value);
2669 case G_VARIANT_CLASS_BYTE:
2670 return g_variant_get_byte (value);
2672 case G_VARIANT_CLASS_INT16:
2673 case G_VARIANT_CLASS_UINT16:
2677 ptr = g_variant_get_data (value);
2685 case G_VARIANT_CLASS_INT32:
2686 case G_VARIANT_CLASS_UINT32:
2687 case G_VARIANT_CLASS_HANDLE:
2691 ptr = g_variant_get_data (value);
2699 case G_VARIANT_CLASS_INT64:
2700 case G_VARIANT_CLASS_UINT64:
2701 case G_VARIANT_CLASS_DOUBLE:
2702 /* need a separate case for these guys because otherwise
2703 * performance could be quite bad on big endian systems
2708 ptr = g_variant_get_data (value);
2711 return ptr[0] + ptr[1];
2717 g_return_val_if_fail (!g_variant_is_container (value), 0);
2718 g_assert_not_reached ();
2724 * @one: (type GVariant): a #GVariant instance
2725 * @two: (type GVariant): a #GVariant instance
2727 * Checks if @one and @two have the same type and value.
2729 * The types of @one and @two are #gconstpointer only to allow use of
2730 * this function with #GHashTable. They must each be a #GVariant.
2732 * Returns: %TRUE if @one and @two are equal
2737 g_variant_equal (gconstpointer one,
2742 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2744 if (g_variant_get_type_info ((GVariant *) one) !=
2745 g_variant_get_type_info ((GVariant *) two))
2748 /* if both values are trusted to be in their canonical serialised form
2749 * then a simple memcmp() of their serialised data will answer the
2752 * if not, then this might generate a false negative (since it is
2753 * possible for two different byte sequences to represent the same
2754 * value). for now we solve this by pretty-printing both values and
2755 * comparing the result.
2757 if (g_variant_is_trusted ((GVariant *) one) &&
2758 g_variant_is_trusted ((GVariant *) two))
2760 gconstpointer data_one, data_two;
2761 gsize size_one, size_two;
2763 size_one = g_variant_get_size ((GVariant *) one);
2764 size_two = g_variant_get_size ((GVariant *) two);
2766 if (size_one != size_two)
2769 data_one = g_variant_get_data ((GVariant *) one);
2770 data_two = g_variant_get_data ((GVariant *) two);
2773 equal = memcmp (data_one, data_two, size_one) == 0;
2779 gchar *strone, *strtwo;
2781 strone = g_variant_print ((GVariant *) one, FALSE);
2782 strtwo = g_variant_print ((GVariant *) two, FALSE);
2783 equal = strcmp (strone, strtwo) == 0;
2792 * g_variant_compare:
2793 * @one: (type GVariant): a basic-typed #GVariant instance
2794 * @two: (type GVariant): a #GVariant instance of the same type
2796 * Compares @one and @two.
2798 * The types of @one and @two are #gconstpointer only to allow use of
2799 * this function with #GTree, #GPtrArray, etc. They must each be a
2802 * Comparison is only defined for basic types (ie: booleans, numbers,
2803 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2804 * ordered in the usual way. Strings are in ASCII lexographical order.
2806 * It is a programmer error to attempt to compare container values or
2807 * two values that have types that are not exactly equal. For example,
2808 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2809 * integer. Also note that this function is not particularly
2810 * well-behaved when it comes to comparison of doubles; in particular,
2811 * the handling of incomparable values (ie: NaN) is undefined.
2813 * If you only require an equality comparison, g_variant_equal() is more
2816 * Returns: negative value if a < b;
2818 * positive value if a > b.
2823 g_variant_compare (gconstpointer one,
2826 GVariant *a = (GVariant *) one;
2827 GVariant *b = (GVariant *) two;
2829 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2831 switch (g_variant_classify (a))
2833 case G_VARIANT_CLASS_BOOLEAN:
2834 return g_variant_get_boolean (a) -
2835 g_variant_get_boolean (b);
2837 case G_VARIANT_CLASS_BYTE:
2838 return ((gint) g_variant_get_byte (a)) -
2839 ((gint) g_variant_get_byte (b));
2841 case G_VARIANT_CLASS_INT16:
2842 return ((gint) g_variant_get_int16 (a)) -
2843 ((gint) g_variant_get_int16 (b));
2845 case G_VARIANT_CLASS_UINT16:
2846 return ((gint) g_variant_get_uint16 (a)) -
2847 ((gint) g_variant_get_uint16 (b));
2849 case G_VARIANT_CLASS_INT32:
2851 gint32 a_val = g_variant_get_int32 (a);
2852 gint32 b_val = g_variant_get_int32 (b);
2854 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2857 case G_VARIANT_CLASS_UINT32:
2859 guint32 a_val = g_variant_get_uint32 (a);
2860 guint32 b_val = g_variant_get_uint32 (b);
2862 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2865 case G_VARIANT_CLASS_INT64:
2867 gint64 a_val = g_variant_get_int64 (a);
2868 gint64 b_val = g_variant_get_int64 (b);
2870 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2873 case G_VARIANT_CLASS_UINT64:
2875 guint64 a_val = g_variant_get_uint64 (a);
2876 guint64 b_val = g_variant_get_uint64 (b);
2878 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2881 case G_VARIANT_CLASS_DOUBLE:
2883 gdouble a_val = g_variant_get_double (a);
2884 gdouble b_val = g_variant_get_double (b);
2886 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2889 case G_VARIANT_CLASS_STRING:
2890 case G_VARIANT_CLASS_OBJECT_PATH:
2891 case G_VARIANT_CLASS_SIGNATURE:
2892 return strcmp (g_variant_get_string (a, NULL),
2893 g_variant_get_string (b, NULL));
2896 g_return_val_if_fail (!g_variant_is_container (a), 0);
2897 g_assert_not_reached ();
2901 /* GVariantIter {{{1 */
2903 * GVariantIter: (skip)
2905 * #GVariantIter is an opaque data structure and can only be accessed
2906 * using the following functions.
2913 const gchar *loop_format;
2919 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2923 struct stack_iter iter;
2925 GVariant *value_ref;
2929 #define GVSI(i) ((struct stack_iter *) (i))
2930 #define GVHI(i) ((struct heap_iter *) (i))
2931 #define GVSI_MAGIC ((gsize) 3579507750u)
2932 #define GVHI_MAGIC ((gsize) 1450270775u)
2933 #define is_valid_iter(i) (i != NULL && \
2934 GVSI(i)->magic == GVSI_MAGIC)
2935 #define is_valid_heap_iter(i) (is_valid_iter(i) && \
2936 GVHI(i)->magic == GVHI_MAGIC)
2939 * g_variant_iter_new:
2940 * @value: a container #GVariant
2942 * Creates a heap-allocated #GVariantIter for iterating over the items
2945 * Use g_variant_iter_free() to free the return value when you no longer
2948 * A reference is taken to @value and will be released only when
2949 * g_variant_iter_free() is called.
2951 * Returns: (transfer full): a new heap-allocated #GVariantIter
2956 g_variant_iter_new (GVariant *value)
2960 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2961 GVHI(iter)->value_ref = g_variant_ref (value);
2962 GVHI(iter)->magic = GVHI_MAGIC;
2964 g_variant_iter_init (iter, value);
2970 * g_variant_iter_init: (skip)
2971 * @iter: a pointer to a #GVariantIter
2972 * @value: a container #GVariant
2974 * Initialises (without allocating) a #GVariantIter. @iter may be
2975 * completely uninitialised prior to this call; its old value is
2978 * The iterator remains valid for as long as @value exists, and need not
2979 * be freed in any way.
2981 * Returns: the number of items in @value
2986 g_variant_iter_init (GVariantIter *iter,
2989 GVSI(iter)->magic = GVSI_MAGIC;
2990 GVSI(iter)->value = value;
2991 GVSI(iter)->n = g_variant_n_children (value);
2993 GVSI(iter)->loop_format = NULL;
2995 return GVSI(iter)->n;
2999 * g_variant_iter_copy:
3000 * @iter: a #GVariantIter
3002 * Creates a new heap-allocated #GVariantIter to iterate over the
3003 * container that was being iterated over by @iter. Iteration begins on
3004 * the new iterator from the current position of the old iterator but
3005 * the two copies are independent past that point.
3007 * Use g_variant_iter_free() to free the return value when you no longer
3010 * A reference is taken to the container that @iter is iterating over
3011 * and will be related only when g_variant_iter_free() is called.
3013 * Returns: (transfer full): a new heap-allocated #GVariantIter
3018 g_variant_iter_copy (GVariantIter *iter)
3022 g_return_val_if_fail (is_valid_iter (iter), 0);
3024 copy = g_variant_iter_new (GVSI(iter)->value);
3025 GVSI(copy)->i = GVSI(iter)->i;
3031 * g_variant_iter_n_children:
3032 * @iter: a #GVariantIter
3034 * Queries the number of child items in the container that we are
3035 * iterating over. This is the total number of items -- not the number
3036 * of items remaining.
3038 * This function might be useful for preallocation of arrays.
3040 * Returns: the number of children in the container
3045 g_variant_iter_n_children (GVariantIter *iter)
3047 g_return_val_if_fail (is_valid_iter (iter), 0);
3049 return GVSI(iter)->n;
3053 * g_variant_iter_free:
3054 * @iter: (transfer full): a heap-allocated #GVariantIter
3056 * Frees a heap-allocated #GVariantIter. Only call this function on
3057 * iterators that were returned by g_variant_iter_new() or
3058 * g_variant_iter_copy().
3063 g_variant_iter_free (GVariantIter *iter)
3065 g_return_if_fail (is_valid_heap_iter (iter));
3067 g_variant_unref (GVHI(iter)->value_ref);
3068 GVHI(iter)->magic = 0;
3070 g_slice_free (struct heap_iter, GVHI(iter));
3074 * g_variant_iter_next_value:
3075 * @iter: a #GVariantIter
3077 * Gets the next item in the container. If no more items remain then
3078 * %NULL is returned.
3080 * Use g_variant_unref() to drop your reference on the return value when
3081 * you no longer need it.
3083 * Here is an example for iterating with g_variant_iter_next_value():
3084 * |[<!-- language="C" -->
3085 * // recursively iterate a container
3087 * iterate_container_recursive (GVariant *container)
3089 * GVariantIter iter;
3092 * g_variant_iter_init (&iter, container);
3093 * while ((child = g_variant_iter_next_value (&iter)))
3095 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3097 * if (g_variant_is_container (child))
3098 * iterate_container_recursive (child);
3100 * g_variant_unref (child);
3105 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3110 g_variant_iter_next_value (GVariantIter *iter)
3112 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3114 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3116 g_critical ("g_variant_iter_next_value: must not be called again "
3117 "after NULL has already been returned.");
3123 if (GVSI(iter)->i < GVSI(iter)->n)
3124 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3129 /* GVariantBuilder {{{1 */
3133 * A utility type for constructing container-type #GVariant instances.
3135 * This is an opaque structure and may only be accessed using the
3136 * following functions.
3138 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3139 * access it from more than one thread.
3142 struct stack_builder
3144 GVariantBuilder *parent;
3147 /* type constraint explicitly specified by 'type'.
3148 * for tuple types, this moves along as we add more items.
3150 const GVariantType *expected_type;
3152 /* type constraint implied by previous array item.
3154 const GVariantType *prev_item_type;
3156 /* constraints on the number of children. max = -1 for unlimited. */
3160 /* dynamically-growing pointer array */
3161 GVariant **children;
3162 gsize allocated_children;
3165 /* set to '1' if all items in the container will have the same type
3166 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3168 guint uniform_item_types : 1;
3170 /* set to '1' initially and changed to '0' if an untrusted value is
3178 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3182 GVariantBuilder builder;
3188 #define GVSB(b) ((struct stack_builder *) (b))
3189 #define GVHB(b) ((struct heap_builder *) (b))
3190 #define GVSB_MAGIC ((gsize) 1033660112u)
3191 #define GVSB_MAGIC_PARTIAL ((gsize) 2942751021u)
3192 #define GVHB_MAGIC ((gsize) 3087242682u)
3193 #define is_valid_builder(b) (b != NULL && \
3194 GVSB(b)->magic == GVSB_MAGIC)
3195 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3197 /* Just to make sure that by adding a union to GVariantBuilder, we
3198 * didn't accidentally change ABI. */
3199 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3202 ensure_valid_builder (GVariantBuilder *builder)
3204 if (is_valid_builder (builder))
3206 if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3208 static GVariantBuilder cleared_builder;
3210 /* Make sure that only first two fields were set and the rest is
3211 * zeroed to avoid messing up the builder that had parent
3212 * address equal to GVSB_MAGIC_PARTIAL. */
3213 if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3216 g_variant_builder_init (builder, builder->u.s.type);
3218 return is_valid_builder (builder);
3222 * g_variant_builder_new:
3223 * @type: a container type
3225 * Allocates and initialises a new #GVariantBuilder.
3227 * You should call g_variant_builder_unref() on the return value when it
3228 * is no longer needed. The memory will not be automatically freed by
3231 * In most cases it is easier to place a #GVariantBuilder directly on
3232 * the stack of the calling function and initialise it with
3233 * g_variant_builder_init().
3235 * Returns: (transfer full): a #GVariantBuilder
3240 g_variant_builder_new (const GVariantType *type)
3242 GVariantBuilder *builder;
3244 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3245 g_variant_builder_init (builder, type);
3246 GVHB(builder)->magic = GVHB_MAGIC;
3247 GVHB(builder)->ref_count = 1;
3253 * g_variant_builder_unref:
3254 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3256 * Decreases the reference count on @builder.
3258 * In the event that there are no more references, releases all memory
3259 * associated with the #GVariantBuilder.
3261 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3262 * things will happen.
3267 g_variant_builder_unref (GVariantBuilder *builder)
3269 g_return_if_fail (is_valid_heap_builder (builder));
3271 if (--GVHB(builder)->ref_count)
3274 g_variant_builder_clear (builder);
3275 GVHB(builder)->magic = 0;
3277 g_slice_free (struct heap_builder, GVHB(builder));
3281 * g_variant_builder_ref:
3282 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3284 * Increases the reference count on @builder.
3286 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3287 * things will happen.
3289 * Returns: (transfer full): a new reference to @builder
3294 g_variant_builder_ref (GVariantBuilder *builder)
3296 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3298 GVHB(builder)->ref_count++;
3304 * g_variant_builder_clear: (skip)
3305 * @builder: a #GVariantBuilder
3307 * Releases all memory associated with a #GVariantBuilder without
3308 * freeing the #GVariantBuilder structure itself.
3310 * It typically only makes sense to do this on a stack-allocated
3311 * #GVariantBuilder if you want to abort building the value part-way
3312 * through. This function need not be called if you call
3313 * g_variant_builder_end() and it also doesn't need to be called on
3314 * builders allocated with g_variant_builder_new() (see
3315 * g_variant_builder_unref() for that).
3317 * This function leaves the #GVariantBuilder structure set to all-zeros.
3318 * It is valid to call this function on either an initialised
3319 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3320 * to call this function on uninitialised memory.
3325 g_variant_builder_clear (GVariantBuilder *builder)
3329 if (GVSB(builder)->magic == 0)
3330 /* all-zeros or partial case */
3333 g_return_if_fail (ensure_valid_builder (builder));
3335 g_variant_type_free (GVSB(builder)->type);
3337 for (i = 0; i < GVSB(builder)->offset; i++)
3338 g_variant_unref (GVSB(builder)->children[i]);
3340 g_free (GVSB(builder)->children);
3342 if (GVSB(builder)->parent)
3344 g_variant_builder_clear (GVSB(builder)->parent);
3345 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3348 memset (builder, 0, sizeof (GVariantBuilder));
3352 * g_variant_builder_init: (skip)
3353 * @builder: a #GVariantBuilder
3354 * @type: a container type
3356 * Initialises a #GVariantBuilder structure.
3358 * @type must be non-%NULL. It specifies the type of container to
3359 * construct. It can be an indefinite type such as
3360 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3361 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3364 * After the builder is initialised, values are added using
3365 * g_variant_builder_add_value() or g_variant_builder_add().
3367 * After all the child values are added, g_variant_builder_end() frees
3368 * the memory associated with the builder and returns the #GVariant that
3371 * This function completely ignores the previous contents of @builder.
3372 * On one hand this means that it is valid to pass in completely
3373 * uninitialised memory. On the other hand, this means that if you are
3374 * initialising over top of an existing #GVariantBuilder you need to
3375 * first call g_variant_builder_clear() in order to avoid leaking
3378 * You must not call g_variant_builder_ref() or
3379 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3380 * with this function. If you ever pass a reference to a
3381 * #GVariantBuilder outside of the control of your own code then you
3382 * should assume that the person receiving that reference may try to use
3383 * reference counting; you should use g_variant_builder_new() instead of
3389 g_variant_builder_init (GVariantBuilder *builder,
3390 const GVariantType *type)
3392 g_return_if_fail (type != NULL);
3393 g_return_if_fail (g_variant_type_is_container (type));
3395 memset (builder, 0, sizeof (GVariantBuilder));
3397 GVSB(builder)->type = g_variant_type_copy (type);
3398 GVSB(builder)->magic = GVSB_MAGIC;
3399 GVSB(builder)->trusted = TRUE;
3401 switch (*(const gchar *) type)
3403 case G_VARIANT_CLASS_VARIANT:
3404 GVSB(builder)->uniform_item_types = TRUE;
3405 GVSB(builder)->allocated_children = 1;
3406 GVSB(builder)->expected_type = NULL;
3407 GVSB(builder)->min_items = 1;
3408 GVSB(builder)->max_items = 1;
3411 case G_VARIANT_CLASS_ARRAY:
3412 GVSB(builder)->uniform_item_types = TRUE;
3413 GVSB(builder)->allocated_children = 8;
3414 GVSB(builder)->expected_type =
3415 g_variant_type_element (GVSB(builder)->type);
3416 GVSB(builder)->min_items = 0;
3417 GVSB(builder)->max_items = -1;
3420 case G_VARIANT_CLASS_MAYBE:
3421 GVSB(builder)->uniform_item_types = TRUE;
3422 GVSB(builder)->allocated_children = 1;
3423 GVSB(builder)->expected_type =
3424 g_variant_type_element (GVSB(builder)->type);
3425 GVSB(builder)->min_items = 0;
3426 GVSB(builder)->max_items = 1;
3429 case G_VARIANT_CLASS_DICT_ENTRY:
3430 GVSB(builder)->uniform_item_types = FALSE;
3431 GVSB(builder)->allocated_children = 2;
3432 GVSB(builder)->expected_type =
3433 g_variant_type_key (GVSB(builder)->type);
3434 GVSB(builder)->min_items = 2;
3435 GVSB(builder)->max_items = 2;
3438 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3439 GVSB(builder)->uniform_item_types = FALSE;
3440 GVSB(builder)->allocated_children = 8;
3441 GVSB(builder)->expected_type = NULL;
3442 GVSB(builder)->min_items = 0;
3443 GVSB(builder)->max_items = -1;
3446 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3447 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3448 GVSB(builder)->expected_type =
3449 g_variant_type_first (GVSB(builder)->type);
3450 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3451 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3452 GVSB(builder)->uniform_item_types = FALSE;
3456 g_assert_not_reached ();
3459 GVSB(builder)->children = g_new (GVariant *,
3460 GVSB(builder)->allocated_children);
3464 g_variant_builder_make_room (struct stack_builder *builder)
3466 if (builder->offset == builder->allocated_children)
3468 builder->allocated_children *= 2;
3469 builder->children = g_renew (GVariant *, builder->children,
3470 builder->allocated_children);
3475 * g_variant_builder_add_value:
3476 * @builder: a #GVariantBuilder
3477 * @value: a #GVariant
3479 * Adds @value to @builder.
3481 * It is an error to call this function in any way that would create an
3482 * inconsistent value to be constructed. Some examples of this are
3483 * putting different types of items into an array, putting the wrong
3484 * types or number of items in a tuple, putting more than one value into
3487 * If @value is a floating reference (see g_variant_ref_sink()),
3488 * the @builder instance takes ownership of @value.
3493 g_variant_builder_add_value (GVariantBuilder *builder,
3496 g_return_if_fail (ensure_valid_builder (builder));
3497 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3498 g_return_if_fail (!GVSB(builder)->expected_type ||
3499 g_variant_is_of_type (value,
3500 GVSB(builder)->expected_type));
3501 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3502 g_variant_is_of_type (value,
3503 GVSB(builder)->prev_item_type));
3505 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3507 if (!GVSB(builder)->uniform_item_types)
3509 /* advance our expected type pointers */
3510 if (GVSB(builder)->expected_type)
3511 GVSB(builder)->expected_type =
3512 g_variant_type_next (GVSB(builder)->expected_type);
3514 if (GVSB(builder)->prev_item_type)
3515 GVSB(builder)->prev_item_type =
3516 g_variant_type_next (GVSB(builder)->prev_item_type);
3519 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3521 g_variant_builder_make_room (GVSB(builder));
3523 GVSB(builder)->children[GVSB(builder)->offset++] =
3524 g_variant_ref_sink (value);
3528 * g_variant_builder_open:
3529 * @builder: a #GVariantBuilder
3530 * @type: the #GVariantType of the container
3532 * Opens a subcontainer inside the given @builder. When done adding
3533 * items to the subcontainer, g_variant_builder_close() must be called. @type
3534 * is the type of the container: so to build a tuple of several values, @type
3535 * must include the tuple itself.
3537 * It is an error to call this function in any way that would cause an
3538 * inconsistent value to be constructed (ie: adding too many values or
3539 * a value of an incorrect type).
3541 * Example of building a nested variant:
3542 * |[<!-- language="C" -->
3543 * GVariantBuilder builder;
3544 * guint32 some_number = get_number ();
3545 * g_autoptr (GHashTable) some_dict = get_dict ();
3546 * GHashTableIter iter;
3548 * const GVariant *value;
3549 * g_autoptr (GVariant) output = NULL;
3551 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3552 * g_variant_builder_add (&builder, "u", some_number);
3553 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3555 * g_hash_table_iter_init (&iter, some_dict);
3556 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3558 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3559 * g_variant_builder_add (&builder, "s", key);
3560 * g_variant_builder_add (&builder, "v", value);
3561 * g_variant_builder_close (&builder);
3564 * g_variant_builder_close (&builder);
3566 * output = g_variant_builder_end (&builder);
3572 g_variant_builder_open (GVariantBuilder *builder,
3573 const GVariantType *type)
3575 GVariantBuilder *parent;
3577 g_return_if_fail (ensure_valid_builder (builder));
3578 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3579 g_return_if_fail (!GVSB(builder)->expected_type ||
3580 g_variant_type_is_subtype_of (type,
3581 GVSB(builder)->expected_type));
3582 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3583 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3586 parent = g_slice_dup (GVariantBuilder, builder);
3587 g_variant_builder_init (builder, type);
3588 GVSB(builder)->parent = parent;
3590 /* push the prev_item_type down into the subcontainer */
3591 if (GVSB(parent)->prev_item_type)
3593 if (!GVSB(builder)->uniform_item_types)
3594 /* tuples and dict entries */
3595 GVSB(builder)->prev_item_type =
3596 g_variant_type_first (GVSB(parent)->prev_item_type);
3598 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3599 /* maybes and arrays */
3600 GVSB(builder)->prev_item_type =
3601 g_variant_type_element (GVSB(parent)->prev_item_type);
3606 * g_variant_builder_close:
3607 * @builder: a #GVariantBuilder
3609 * Closes the subcontainer inside the given @builder that was opened by
3610 * the most recent call to g_variant_builder_open().
3612 * It is an error to call this function in any way that would create an
3613 * inconsistent value to be constructed (ie: too few values added to the
3619 g_variant_builder_close (GVariantBuilder *builder)
3621 GVariantBuilder *parent;
3623 g_return_if_fail (ensure_valid_builder (builder));
3624 g_return_if_fail (GVSB(builder)->parent != NULL);
3626 parent = GVSB(builder)->parent;
3627 GVSB(builder)->parent = NULL;
3629 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3632 g_slice_free (GVariantBuilder, parent);
3636 * g_variant_make_maybe_type:
3637 * @element: a #GVariant
3639 * Return the type of a maybe containing @element.
3641 static GVariantType *
3642 g_variant_make_maybe_type (GVariant *element)
3644 return g_variant_type_new_maybe (g_variant_get_type (element));
3648 * g_variant_make_array_type:
3649 * @element: a #GVariant
3651 * Return the type of an array containing @element.
3653 static GVariantType *
3654 g_variant_make_array_type (GVariant *element)
3656 return g_variant_type_new_array (g_variant_get_type (element));
3660 * g_variant_builder_end:
3661 * @builder: a #GVariantBuilder
3663 * Ends the builder process and returns the constructed value.
3665 * It is not permissible to use @builder in any way after this call
3666 * except for reference counting operations (in the case of a
3667 * heap-allocated #GVariantBuilder) or by reinitialising it with
3668 * g_variant_builder_init() (in the case of stack-allocated). This
3669 * means that for the stack-allocated builders there is no need to
3670 * call g_variant_builder_clear() after the call to
3671 * g_variant_builder_end().
3673 * It is an error to call this function in any way that would create an
3674 * inconsistent value to be constructed (ie: insufficient number of
3675 * items added to a container with a specific number of children
3676 * required). It is also an error to call this function if the builder
3677 * was created with an indefinite array or maybe type and no children
3678 * have been added; in this case it is impossible to infer the type of
3681 * Returns: (transfer none): a new, floating, #GVariant
3686 g_variant_builder_end (GVariantBuilder *builder)
3688 GVariantType *my_type;
3691 g_return_val_if_fail (ensure_valid_builder (builder), NULL);
3692 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3694 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3695 GVSB(builder)->prev_item_type != NULL ||
3696 g_variant_type_is_definite (GVSB(builder)->type),
3699 if (g_variant_type_is_definite (GVSB(builder)->type))
3700 my_type = g_variant_type_copy (GVSB(builder)->type);
3702 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3703 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3705 else if (g_variant_type_is_array (GVSB(builder)->type))
3706 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3708 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3709 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3710 GVSB(builder)->offset);
3712 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3713 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3714 GVSB(builder)->children[1]);
3716 g_assert_not_reached ();
3718 value = g_variant_new_from_children (my_type,
3719 g_renew (GVariant *,
3720 GVSB(builder)->children,
3721 GVSB(builder)->offset),
3722 GVSB(builder)->offset,
3723 GVSB(builder)->trusted);
3724 GVSB(builder)->children = NULL;
3725 GVSB(builder)->offset = 0;
3727 g_variant_builder_clear (builder);
3728 g_variant_type_free (my_type);
3733 /* GVariantDict {{{1 */
3738 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3740 * It can be used for doing a sequence of dictionary lookups in an
3741 * efficient way on an existing #GVariant dictionary or it can be used
3742 * to construct new dictionaries with a hashtable-like interface. It
3743 * can also be used for taking existing dictionaries and modifying them
3744 * in order to create new ones.
3746 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3749 * It is possible to use #GVariantDict allocated on the stack or on the
3750 * heap. When using a stack-allocated #GVariantDict, you begin with a
3751 * call to g_variant_dict_init() and free the resources with a call to
3752 * g_variant_dict_clear().
3754 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3755 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3756 * and g_variant_dict_unref().
3758 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3759 * dictionary-type #GVariant. When used with stack-allocated instances,
3760 * this also implicitly frees all associated memory, but for
3761 * heap-allocated instances, you must still call g_variant_dict_unref()
3764 * You will typically want to use a heap-allocated #GVariantDict when
3765 * you expose it as part of an API. For most other uses, the
3766 * stack-allocated form will be more convenient.
3768 * Consider the following two examples that do the same thing in each
3769 * style: take an existing dictionary and look up the "count" uint32
3770 * key, adding 1 to it if it is found, or returning an error if the
3771 * key is not found. Each returns the new dictionary as a floating
3774 * ## Using a stack-allocated GVariantDict
3776 * |[<!-- language="C" -->
3778 * add_to_count (GVariant *orig,
3781 * GVariantDict dict;
3784 * g_variant_dict_init (&dict, orig);
3785 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3787 * g_set_error (...);
3788 * g_variant_dict_clear (&dict);
3792 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3794 * return g_variant_dict_end (&dict);
3798 * ## Using heap-allocated GVariantDict
3800 * |[<!-- language="C" -->
3802 * add_to_count (GVariant *orig,
3805 * GVariantDict *dict;
3809 * dict = g_variant_dict_new (orig);
3811 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3813 * g_variant_dict_insert (dict, "count", "u", count + 1);
3814 * result = g_variant_dict_end (dict);
3818 * g_set_error (...);
3822 * g_variant_dict_unref (dict);
3836 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3840 struct stack_dict dict;
3845 #define GVSD(d) ((struct stack_dict *) (d))
3846 #define GVHD(d) ((struct heap_dict *) (d))
3847 #define GVSD_MAGIC ((gsize) 2579507750u)
3848 #define GVSD_MAGIC_PARTIAL ((gsize) 3488698669u)
3849 #define GVHD_MAGIC ((gsize) 2450270775u)
3850 #define is_valid_dict(d) (d != NULL && \
3851 GVSD(d)->magic == GVSD_MAGIC)
3852 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3854 /* Just to make sure that by adding a union to GVariantDict, we didn't
3855 * accidentally change ABI. */
3856 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3859 ensure_valid_dict (GVariantDict *dict)
3861 if (is_valid_dict (dict))
3863 if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3865 static GVariantDict cleared_dict;
3867 /* Make sure that only first two fields were set and the rest is
3868 * zeroed to avoid messing up the builder that had parent
3869 * address equal to GVSB_MAGIC_PARTIAL. */
3870 if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3873 g_variant_dict_init (dict, dict->u.s.asv);
3875 return is_valid_dict (dict);
3879 * g_variant_dict_new:
3880 * @from_asv: (nullable): the #GVariant with which to initialise the
3883 * Allocates and initialises a new #GVariantDict.
3885 * You should call g_variant_dict_unref() on the return value when it
3886 * is no longer needed. The memory will not be automatically freed by
3889 * In some cases it may be easier to place a #GVariantDict directly on
3890 * the stack of the calling function and initialise it with
3891 * g_variant_dict_init(). This is particularly useful when you are
3892 * using #GVariantDict to construct a #GVariant.
3894 * Returns: (transfer full): a #GVariantDict
3899 g_variant_dict_new (GVariant *from_asv)
3903 dict = g_slice_alloc (sizeof (struct heap_dict));
3904 g_variant_dict_init (dict, from_asv);
3905 GVHD(dict)->magic = GVHD_MAGIC;
3906 GVHD(dict)->ref_count = 1;
3912 * g_variant_dict_init: (skip)
3913 * @dict: a #GVariantDict
3914 * @from_asv: (nullable): the initial value for @dict
3916 * Initialises a #GVariantDict structure.
3918 * If @from_asv is given, it is used to initialise the dictionary.
3920 * This function completely ignores the previous contents of @dict. On
3921 * one hand this means that it is valid to pass in completely
3922 * uninitialised memory. On the other hand, this means that if you are
3923 * initialising over top of an existing #GVariantDict you need to first
3924 * call g_variant_dict_clear() in order to avoid leaking memory.
3926 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3927 * #GVariantDict that was initialised with this function. If you ever
3928 * pass a reference to a #GVariantDict outside of the control of your
3929 * own code then you should assume that the person receiving that
3930 * reference may try to use reference counting; you should use
3931 * g_variant_dict_new() instead of this function.
3936 g_variant_dict_init (GVariantDict *dict,
3943 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3944 GVSD(dict)->magic = GVSD_MAGIC;
3948 g_variant_iter_init (&iter, from_asv);
3949 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3950 g_hash_table_insert (GVSD(dict)->values, key, value);
3955 * g_variant_dict_lookup:
3956 * @dict: a #GVariantDict
3957 * @key: the key to look up in the dictionary
3958 * @format_string: a GVariant format string
3959 * @...: the arguments to unpack the value into
3961 * Looks up a value in a #GVariantDict.
3963 * This function is a wrapper around g_variant_dict_lookup_value() and
3964 * g_variant_get(). In the case that %NULL would have been returned,
3965 * this function returns %FALSE. Otherwise, it unpacks the returned
3966 * value and returns %TRUE.
3968 * @format_string determines the C types that are used for unpacking the
3969 * values and also determines if the values are copied or borrowed, see the
3970 * section on [GVariant format strings][gvariant-format-strings-pointers].
3972 * Returns: %TRUE if a value was unpacked
3977 g_variant_dict_lookup (GVariantDict *dict,
3979 const gchar *format_string,
3985 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
3986 g_return_val_if_fail (key != NULL, FALSE);
3987 g_return_val_if_fail (format_string != NULL, FALSE);
3989 value = g_hash_table_lookup (GVSD(dict)->values, key);
3991 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3994 va_start (ap, format_string);
3995 g_variant_get_va (value, format_string, NULL, &ap);
4002 * g_variant_dict_lookup_value:
4003 * @dict: a #GVariantDict
4004 * @key: the key to look up in the dictionary
4005 * @expected_type: (nullable): a #GVariantType, or %NULL
4007 * Looks up a value in a #GVariantDict.
4009 * If @key is not found in @dictionary, %NULL is returned.
4011 * The @expected_type string specifies what type of value is expected.
4012 * If the value associated with @key has a different type then %NULL is
4015 * If the key is found and the value has the correct type, it is
4016 * returned. If @expected_type was specified then any non-%NULL return
4017 * value will have this type.
4019 * Returns: (transfer full): the value of the dictionary key, or %NULL
4024 g_variant_dict_lookup_value (GVariantDict *dict,
4026 const GVariantType *expected_type)
4030 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4031 g_return_val_if_fail (key != NULL, NULL);
4033 result = g_hash_table_lookup (GVSD(dict)->values, key);
4035 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4036 return g_variant_ref (result);
4042 * g_variant_dict_contains:
4043 * @dict: a #GVariantDict
4044 * @key: the key to look up in the dictionary
4046 * Checks if @key exists in @dict.
4048 * Returns: %TRUE if @key is in @dict
4053 g_variant_dict_contains (GVariantDict *dict,
4056 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4057 g_return_val_if_fail (key != NULL, FALSE);
4059 return g_hash_table_contains (GVSD(dict)->values, key);
4063 * g_variant_dict_insert:
4064 * @dict: a #GVariantDict
4065 * @key: the key to insert a value for
4066 * @format_string: a #GVariant varargs format string
4067 * @...: arguments, as per @format_string
4069 * Inserts a value into a #GVariantDict.
4071 * This call is a convenience wrapper that is exactly equivalent to
4072 * calling g_variant_new() followed by g_variant_dict_insert_value().
4077 g_variant_dict_insert (GVariantDict *dict,
4079 const gchar *format_string,
4084 g_return_if_fail (ensure_valid_dict (dict));
4085 g_return_if_fail (key != NULL);
4086 g_return_if_fail (format_string != NULL);
4088 va_start (ap, format_string);
4089 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4094 * g_variant_dict_insert_value:
4095 * @dict: a #GVariantDict
4096 * @key: the key to insert a value for
4097 * @value: the value to insert
4099 * Inserts (or replaces) a key in a #GVariantDict.
4101 * @value is consumed if it is floating.
4106 g_variant_dict_insert_value (GVariantDict *dict,
4110 g_return_if_fail (ensure_valid_dict (dict));
4111 g_return_if_fail (key != NULL);
4112 g_return_if_fail (value != NULL);
4114 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4118 * g_variant_dict_remove:
4119 * @dict: a #GVariantDict
4120 * @key: the key to remove
4122 * Removes a key and its associated value from a #GVariantDict.
4124 * Returns: %TRUE if the key was found and removed
4129 g_variant_dict_remove (GVariantDict *dict,
4132 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4133 g_return_val_if_fail (key != NULL, FALSE);
4135 return g_hash_table_remove (GVSD(dict)->values, key);
4139 * g_variant_dict_clear:
4140 * @dict: a #GVariantDict
4142 * Releases all memory associated with a #GVariantDict without freeing
4143 * the #GVariantDict structure itself.
4145 * It typically only makes sense to do this on a stack-allocated
4146 * #GVariantDict if you want to abort building the value part-way
4147 * through. This function need not be called if you call
4148 * g_variant_dict_end() and it also doesn't need to be called on dicts
4149 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4152 * It is valid to call this function on either an initialised
4153 * #GVariantDict or one that was previously cleared by an earlier call
4154 * to g_variant_dict_clear() but it is not valid to call this function
4155 * on uninitialised memory.
4160 g_variant_dict_clear (GVariantDict *dict)
4162 if (GVSD(dict)->magic == 0)
4163 /* all-zeros case */
4166 g_return_if_fail (ensure_valid_dict (dict));
4168 g_hash_table_unref (GVSD(dict)->values);
4169 GVSD(dict)->values = NULL;
4171 GVSD(dict)->magic = 0;
4175 * g_variant_dict_end:
4176 * @dict: a #GVariantDict
4178 * Returns the current value of @dict as a #GVariant of type
4179 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4181 * It is not permissible to use @dict in any way after this call except
4182 * for reference counting operations (in the case of a heap-allocated
4183 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4184 * the case of stack-allocated).
4186 * Returns: (transfer none): a new, floating, #GVariant
4191 g_variant_dict_end (GVariantDict *dict)
4193 GVariantBuilder builder;
4194 GHashTableIter iter;
4195 gpointer key, value;
4197 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4199 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4201 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4202 while (g_hash_table_iter_next (&iter, &key, &value))
4203 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4205 g_variant_dict_clear (dict);
4207 return g_variant_builder_end (&builder);
4211 * g_variant_dict_ref:
4212 * @dict: a heap-allocated #GVariantDict
4214 * Increases the reference count on @dict.
4216 * Don't call this on stack-allocated #GVariantDict instances or bad
4217 * things will happen.
4219 * Returns: (transfer full): a new reference to @dict
4224 g_variant_dict_ref (GVariantDict *dict)
4226 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4228 GVHD(dict)->ref_count++;
4234 * g_variant_dict_unref:
4235 * @dict: (transfer full): a heap-allocated #GVariantDict
4237 * Decreases the reference count on @dict.
4239 * In the event that there are no more references, releases all memory
4240 * associated with the #GVariantDict.
4242 * Don't call this on stack-allocated #GVariantDict instances or bad
4243 * things will happen.
4248 g_variant_dict_unref (GVariantDict *dict)
4250 g_return_if_fail (is_valid_heap_dict (dict));
4252 if (--GVHD(dict)->ref_count == 0)
4254 g_variant_dict_clear (dict);
4255 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4260 /* Format strings {{{1 */
4262 * g_variant_format_string_scan:
4263 * @string: a string that may be prefixed with a format string
4264 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4266 * @endptr: (nullable) (default NULL): location to store the end pointer,
4269 * Checks the string pointed to by @string for starting with a properly
4270 * formed #GVariant varargs format string. If no valid format string is
4271 * found then %FALSE is returned.
4273 * If @string does start with a valid format string then %TRUE is
4274 * returned. If @endptr is non-%NULL then it is updated to point to the
4275 * first character after the format string.
4277 * If @limit is non-%NULL then @limit (and any character after it) will
4278 * not be accessed and the effect is otherwise equivalent to if the
4279 * character at @limit were nul.
4281 * See the section on [GVariant format strings][gvariant-format-strings].
4283 * Returns: %TRUE if there was a valid format string
4288 g_variant_format_string_scan (const gchar *string,
4290 const gchar **endptr)
4292 #define next_char() (string == limit ? '\0' : *string++)
4293 #define peek_char() (string == limit ? '\0' : *string)
4296 switch (next_char())
4298 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4299 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4300 case 'g': case 'v': case '*': case '?': case 'r':
4304 return g_variant_format_string_scan (string, limit, endptr);
4308 return g_variant_type_string_scan (string, limit, endptr);
4311 while (peek_char() != ')')
4312 if (!g_variant_format_string_scan (string, limit, &string))
4315 next_char(); /* consume ')' */
4325 if (c != 's' && c != 'o' && c != 'g')
4333 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4334 * The terminating null character is considered to be
4335 * part of the string.
4337 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4341 if (!g_variant_format_string_scan (string, limit, &string))
4344 if (next_char() != '}')
4350 if ((c = next_char()) == 'a')
4352 if ((c = next_char()) == '&')
4354 if ((c = next_char()) == 'a')
4356 if ((c = next_char()) == 'y')
4357 break; /* '^a&ay' */
4360 else if (c == 's' || c == 'o')
4361 break; /* '^a&s', '^a&o' */
4366 if ((c = next_char()) == 'y')
4370 else if (c == 's' || c == 'o')
4371 break; /* '^as', '^ao' */
4378 if ((c = next_char()) == 'a')
4380 if ((c = next_char()) == 'y')
4390 if (c != 's' && c != 'o' && c != 'g')
4409 * g_variant_check_format_string:
4410 * @value: a #GVariant
4411 * @format_string: a valid #GVariant format string
4412 * @copy_only: %TRUE to ensure the format string makes deep copies
4414 * Checks if calling g_variant_get() with @format_string on @value would
4415 * be valid from a type-compatibility standpoint. @format_string is
4416 * assumed to be a valid format string (from a syntactic standpoint).
4418 * If @copy_only is %TRUE then this function additionally checks that it
4419 * would be safe to call g_variant_unref() on @value immediately after
4420 * the call to g_variant_get() without invalidating the result. This is
4421 * only possible if deep copies are made (ie: there are no pointers to
4422 * the data inside of the soon-to-be-freed #GVariant instance). If this
4423 * check fails then a g_critical() is printed and %FALSE is returned.
4425 * This function is meant to be used by functions that wish to provide
4426 * varargs accessors to #GVariant values of uncertain values (eg:
4427 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4429 * Returns: %TRUE if @format_string is safe to use
4434 g_variant_check_format_string (GVariant *value,
4435 const gchar *format_string,
4438 const gchar *original_format = format_string;
4439 const gchar *type_string;
4441 /* Interesting factoid: assuming a format string is valid, it can be
4442 * converted to a type string by removing all '@' '&' and '^'
4445 * Instead of doing that, we can just skip those characters when
4446 * comparing it to the type string of @value.
4448 * For the copy-only case we can just drop the '&' from the list of
4449 * characters to skip over. A '&' will never appear in a type string
4450 * so we know that it won't be possible to return %TRUE if it is in a
4453 type_string = g_variant_get_type_string (value);
4455 while (*type_string || *format_string)
4457 gchar format = *format_string++;
4462 if G_UNLIKELY (copy_only)
4464 /* for the love of all that is good, please don't mark this string for translation... */
4465 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4466 "interface to validate the passed format string for type safety. The passed format "
4467 "(%s) contains a '&' character which would result in a pointer being returned to the "
4468 "data inside of a GVariant instance that may no longer exist by the time the function "
4469 "returns. Modify your code to use a format string without '&'.", original_format);
4476 /* ignore these 2 (or 3) */
4480 /* attempt to consume one of 'bynqiuxthdsog' */
4482 char s = *type_string++;
4484 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4490 /* ensure it's a tuple */
4491 if (*type_string != '(')
4496 /* consume a full type string for the '*' or 'r' */
4497 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4503 /* attempt to consume exactly one character equal to the format */
4504 if (format != *type_string++)
4513 * g_variant_format_string_scan_type:
4514 * @string: a string that may be prefixed with a format string
4515 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4517 * @endptr: (nullable) (default NULL): location to store the end pointer,
4520 * If @string starts with a valid format string then this function will
4521 * return the type that the format string corresponds to. Otherwise
4522 * this function returns %NULL.
4524 * Use g_variant_type_free() to free the return value when you no longer
4527 * This function is otherwise exactly like
4528 * g_variant_format_string_scan().
4530 * Returns: (nullable): a #GVariantType if there was a valid format string
4535 g_variant_format_string_scan_type (const gchar *string,
4537 const gchar **endptr)
4539 const gchar *my_end;
4546 if (!g_variant_format_string_scan (string, limit, endptr))
4549 dest = new = g_malloc (*endptr - string + 1);
4550 while (string != *endptr)
4552 if (*string != '@' && *string != '&' && *string != '^')
4558 return (GVariantType *) G_VARIANT_TYPE (new);
4562 valid_format_string (const gchar *format_string,
4566 const gchar *endptr;
4569 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4571 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4574 g_critical ("'%s' is not a valid GVariant format string",
4577 g_critical ("'%s' does not have a valid GVariant format "
4578 "string as a prefix", format_string);
4581 g_variant_type_free (type);
4586 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4591 fragment = g_strndup (format_string, endptr - format_string);
4592 typestr = g_variant_type_dup_string (type);
4594 g_critical ("the GVariant format string '%s' has a type of "
4595 "'%s' but the given value has a type of '%s'",
4596 fragment, typestr, g_variant_get_type_string (value));
4598 g_variant_type_free (type);
4605 g_variant_type_free (type);
4610 /* Variable Arguments {{{1 */
4611 /* We consider 2 main classes of format strings:
4613 * - recursive format strings
4614 * these are ones that result in recursion and the collection of
4615 * possibly more than one argument. Maybe types, tuples,
4616 * dictionary entries.
4618 * - leaf format string
4619 * these result in the collection of a single argument.
4621 * Leaf format strings are further subdivided into two categories:
4623 * - single non-null pointer ("nnp")
4624 * these either collect or return a single non-null pointer.
4627 * these collect or return something else (bool, number, etc).
4629 * Based on the above, the varargs handling code is split into 4 main parts:
4631 * - nnp handling code
4632 * - leaf handling code (which may invoke nnp code)
4633 * - generic handling code (may be recursive, may invoke leaf code)
4634 * - user-facing API (which invokes the generic code)
4636 * Each section implements some of the following functions:
4639 * collect the arguments for the format string as if
4640 * g_variant_new() had been called, but do nothing with them. used
4641 * for skipping over arguments when constructing a Nothing maybe
4645 * create a GVariant *
4648 * unpack a GVariant *
4650 * - free (nnp only):
4651 * free a previously allocated item
4655 g_variant_format_string_is_leaf (const gchar *str)
4657 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4661 g_variant_format_string_is_nnp (const gchar *str)
4663 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4664 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4665 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4668 /* Single non-null pointer ("nnp") {{{2 */
4670 g_variant_valist_free_nnp (const gchar *str,
4676 g_variant_iter_free (ptr);
4680 if (g_str_has_suffix (str, "y"))
4682 if (str[2] != 'a') /* '^a&ay', '^ay' */
4684 else if (str[1] == 'a') /* '^aay' */
4688 else if (str[2] != '&') /* '^as', '^ao' */
4690 else /* '^a&s', '^a&o' */
4704 g_variant_unref (ptr);
4711 g_assert_not_reached ();
4716 g_variant_scan_convenience (const gchar **str,
4739 g_variant_valist_new_nnp (const gchar **str,
4750 const GVariantType *type;
4753 value = g_variant_builder_end (ptr);
4754 type = g_variant_get_type (value);
4756 if G_UNLIKELY (!g_variant_type_is_array (type))
4757 g_error ("g_variant_new: expected array GVariantBuilder but "
4758 "the built value has type '%s'",
4759 g_variant_get_type_string (value));
4761 type = g_variant_type_element (type);
4763 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4765 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4766 g_error ("g_variant_new: expected GVariantBuilder array element "
4767 "type '%s' but the built value has element type '%s'",
4768 type_string, g_variant_get_type_string (value) + 1);
4769 g_free (type_string);
4772 g_variant_type_string_scan (*str, NULL, str);
4778 /* special case: NULL pointer for empty array */
4780 const GVariantType *type = (GVariantType *) *str;
4782 g_variant_type_string_scan (*str, NULL, str);
4784 if G_UNLIKELY (!g_variant_type_is_definite (type))
4785 g_error ("g_variant_new: NULL pointer given with indefinite "
4786 "array type; unable to determine which type of empty "
4787 "array to construct.");
4789 return g_variant_new_array (type, NULL, 0);
4796 value = g_variant_new_string (ptr);
4799 value = g_variant_new_string ("[Invalid UTF-8]");
4805 return g_variant_new_object_path (ptr);
4808 return g_variant_new_signature (ptr);
4816 type = g_variant_scan_convenience (str, &constant, &arrays);
4819 return g_variant_new_strv (ptr, -1);
4822 return g_variant_new_objv (ptr, -1);
4825 return g_variant_new_bytestring_array (ptr, -1);
4827 return g_variant_new_bytestring (ptr);
4831 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4833 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4834 g_error ("g_variant_new: expected GVariant of type '%s' but "
4835 "received value has type '%s'",
4836 type_string, g_variant_get_type_string (ptr));
4837 g_free (type_string);
4840 g_variant_type_string_scan (*str, NULL, str);
4848 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4849 g_error ("g_variant_new: format string '?' expects basic-typed "
4850 "GVariant, but received value has type '%s'",
4851 g_variant_get_type_string (ptr));
4856 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4857 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4858 "GVariant, but received value has type '%s'",
4859 g_variant_get_type_string (ptr));
4864 return g_variant_new_variant (ptr);
4867 g_assert_not_reached ();
4872 g_variant_valist_get_nnp (const gchar **str,
4878 g_variant_type_string_scan (*str, NULL, str);
4879 return g_variant_iter_new (value);
4883 return (gchar *) g_variant_get_string (value, NULL);
4888 return g_variant_dup_string (value, NULL);
4896 type = g_variant_scan_convenience (str, &constant, &arrays);
4901 return g_variant_get_strv (value, NULL);
4903 return g_variant_dup_strv (value, NULL);
4906 else if (type == 'o')
4909 return g_variant_get_objv (value, NULL);
4911 return g_variant_dup_objv (value, NULL);
4914 else if (arrays > 1)
4917 return g_variant_get_bytestring_array (value, NULL);
4919 return g_variant_dup_bytestring_array (value, NULL);
4925 return (gchar *) g_variant_get_bytestring (value);
4927 return g_variant_dup_bytestring (value, NULL);
4932 g_variant_type_string_scan (*str, NULL, str);
4938 return g_variant_ref (value);
4941 return g_variant_get_variant (value);
4944 g_assert_not_reached ();
4950 g_variant_valist_skip_leaf (const gchar **str,
4953 if (g_variant_format_string_is_nnp (*str))
4955 g_variant_format_string_scan (*str, NULL, str);
4956 va_arg (*app, gpointer);
4974 va_arg (*app, guint64);
4978 va_arg (*app, gdouble);
4982 g_assert_not_reached ();
4987 g_variant_valist_new_leaf (const gchar **str,
4990 if (g_variant_format_string_is_nnp (*str))
4991 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4996 return g_variant_new_boolean (va_arg (*app, gboolean));
4999 return g_variant_new_byte (va_arg (*app, guint));
5002 return g_variant_new_int16 (va_arg (*app, gint));
5005 return g_variant_new_uint16 (va_arg (*app, guint));
5008 return g_variant_new_int32 (va_arg (*app, gint));
5011 return g_variant_new_uint32 (va_arg (*app, guint));
5014 return g_variant_new_int64 (va_arg (*app, gint64));
5017 return g_variant_new_uint64 (va_arg (*app, guint64));
5020 return g_variant_new_handle (va_arg (*app, gint));
5023 return g_variant_new_double (va_arg (*app, gdouble));
5026 g_assert_not_reached ();
5030 /* The code below assumes this */
5031 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5032 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5035 g_variant_valist_get_leaf (const gchar **str,
5040 gpointer ptr = va_arg (*app, gpointer);
5044 g_variant_format_string_scan (*str, NULL, str);
5048 if (g_variant_format_string_is_nnp (*str))
5050 gpointer *nnp = (gpointer *) ptr;
5052 if (free && *nnp != NULL)
5053 g_variant_valist_free_nnp (*str, *nnp);
5058 *nnp = g_variant_valist_get_nnp (str, value);
5060 g_variant_format_string_scan (*str, NULL, str);
5070 *(gboolean *) ptr = g_variant_get_boolean (value);
5074 *(guint8 *) ptr = g_variant_get_byte (value);
5078 *(gint16 *) ptr = g_variant_get_int16 (value);
5082 *(guint16 *) ptr = g_variant_get_uint16 (value);
5086 *(gint32 *) ptr = g_variant_get_int32 (value);
5090 *(guint32 *) ptr = g_variant_get_uint32 (value);
5094 *(gint64 *) ptr = g_variant_get_int64 (value);
5098 *(guint64 *) ptr = g_variant_get_uint64 (value);
5102 *(gint32 *) ptr = g_variant_get_handle (value);
5106 *(gdouble *) ptr = g_variant_get_double (value);
5115 *(guint8 *) ptr = 0;
5120 *(guint16 *) ptr = 0;
5127 *(guint32 *) ptr = 0;
5133 *(guint64 *) ptr = 0;
5138 g_assert_not_reached ();
5141 /* Generic (recursive) {{{2 */
5143 g_variant_valist_skip (const gchar **str,
5146 if (g_variant_format_string_is_leaf (*str))
5147 g_variant_valist_skip_leaf (str, app);
5149 else if (**str == 'm') /* maybe */
5153 if (!g_variant_format_string_is_nnp (*str))
5154 va_arg (*app, gboolean);
5156 g_variant_valist_skip (str, app);
5158 else /* tuple, dictionary entry */
5160 g_assert (**str == '(' || **str == '{');
5162 while (**str != ')' && **str != '}')
5163 g_variant_valist_skip (str, app);
5169 g_variant_valist_new (const gchar **str,
5172 if (g_variant_format_string_is_leaf (*str))
5173 return g_variant_valist_new_leaf (str, app);
5175 if (**str == 'm') /* maybe */
5177 GVariantType *type = NULL;
5178 GVariant *value = NULL;
5182 if (g_variant_format_string_is_nnp (*str))
5184 gpointer nnp = va_arg (*app, gpointer);
5187 value = g_variant_valist_new_nnp (str, nnp);
5189 type = g_variant_format_string_scan_type (*str, NULL, str);
5193 gboolean just = va_arg (*app, gboolean);
5196 value = g_variant_valist_new (str, app);
5199 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5200 g_variant_valist_skip (str, app);
5204 value = g_variant_new_maybe (type, value);
5207 g_variant_type_free (type);
5211 else /* tuple, dictionary entry */
5216 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5219 g_assert (**str == '{');
5220 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5224 while (**str != ')' && **str != '}')
5225 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5228 return g_variant_builder_end (&b);
5233 g_variant_valist_get (const gchar **str,
5238 if (g_variant_format_string_is_leaf (*str))
5239 g_variant_valist_get_leaf (str, value, free, app);
5241 else if (**str == 'm')
5246 value = g_variant_get_maybe (value);
5248 if (!g_variant_format_string_is_nnp (*str))
5250 gboolean *ptr = va_arg (*app, gboolean *);
5253 *ptr = value != NULL;
5256 g_variant_valist_get (str, value, free, app);
5259 g_variant_unref (value);
5262 else /* tuple, dictionary entry */
5266 g_assert (**str == '(' || **str == '{');
5269 while (**str != ')' && **str != '}')
5273 GVariant *child = g_variant_get_child_value (value, index++);
5274 g_variant_valist_get (str, child, free, app);
5275 g_variant_unref (child);
5278 g_variant_valist_get (str, NULL, free, app);
5284 /* User-facing API {{{2 */
5286 * g_variant_new: (skip)
5287 * @format_string: a #GVariant format string
5288 * @...: arguments, as per @format_string
5290 * Creates a new #GVariant instance.
5292 * Think of this function as an analogue to g_strdup_printf().
5294 * The type of the created instance and the arguments that are expected
5295 * by this function are determined by @format_string. See the section on
5296 * [GVariant format strings][gvariant-format-strings]. Please note that
5297 * the syntax of the format string is very likely to be extended in the
5300 * The first character of the format string must not be '*' '?' '@' or
5301 * 'r'; in essence, a new #GVariant must always be constructed by this
5302 * function (and not merely passed through it unmodified).
5304 * Note that the arguments must be of the correct width for their types
5305 * specified in @format_string. This can be achieved by casting them. See
5306 * the [GVariant varargs documentation][gvariant-varargs].
5308 * |[<!-- language="C" -->
5309 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5310 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5311 * GVariant *new_variant;
5313 * new_variant = g_variant_new ("(t^as)",
5314 * // This cast is required.
5315 * (guint64) some_flags,
5319 * Returns: a new floating #GVariant instance
5324 g_variant_new (const gchar *format_string,
5330 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5331 format_string[0] != '?' && format_string[0] != '@' &&
5332 format_string[0] != '*' && format_string[0] != 'r',
5335 va_start (ap, format_string);
5336 value = g_variant_new_va (format_string, NULL, &ap);
5343 * g_variant_new_va: (skip)
5344 * @format_string: a string that is prefixed with a format string
5345 * @endptr: (nullable) (default NULL): location to store the end pointer,
5347 * @app: a pointer to a #va_list
5349 * This function is intended to be used by libraries based on
5350 * #GVariant that want to provide g_variant_new()-like functionality
5353 * The API is more general than g_variant_new() to allow a wider range
5356 * @format_string must still point to a valid format string, but it only
5357 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5358 * non-%NULL then it is updated to point to the first character past the
5359 * end of the format string.
5361 * @app is a pointer to a #va_list. The arguments, according to
5362 * @format_string, are collected from this #va_list and the list is left
5363 * pointing to the argument following the last.
5365 * Note that the arguments in @app must be of the correct width for their
5366 * types specified in @format_string when collected into the #va_list.
5367 * See the [GVariant varargs documentation][gvariant-varargs].
5369 * These two generalisations allow mixing of multiple calls to
5370 * g_variant_new_va() and g_variant_get_va() within a single actual
5371 * varargs call by the user.
5373 * The return value will be floating if it was a newly created GVariant
5374 * instance (for example, if the format string was "(ii)"). In the case
5375 * that the format_string was '*', '?', 'r', or a format starting with
5376 * '@' then the collected #GVariant pointer will be returned unmodified,
5377 * without adding any additional references.
5379 * In order to behave correctly in all cases it is necessary for the
5380 * calling function to g_variant_ref_sink() the return result before
5381 * returning control to the user that originally provided the pointer.
5382 * At this point, the caller will have their own full reference to the
5383 * result. This can also be done by adding the result to a container,
5384 * or by passing it to another g_variant_new() call.
5386 * Returns: a new, usually floating, #GVariant
5391 g_variant_new_va (const gchar *format_string,
5392 const gchar **endptr,
5397 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5399 g_return_val_if_fail (app != NULL, NULL);
5401 value = g_variant_valist_new (&format_string, app);
5404 *endptr = format_string;
5410 * g_variant_get: (skip)
5411 * @value: a #GVariant instance
5412 * @format_string: a #GVariant format string
5413 * @...: arguments, as per @format_string
5415 * Deconstructs a #GVariant instance.
5417 * Think of this function as an analogue to scanf().
5419 * The arguments that are expected by this function are entirely
5420 * determined by @format_string. @format_string also restricts the
5421 * permissible types of @value. It is an error to give a value with
5422 * an incompatible type. See the section on
5423 * [GVariant format strings][gvariant-format-strings].
5424 * Please note that the syntax of the format string is very likely to be
5425 * extended in the future.
5427 * @format_string determines the C types that are used for unpacking
5428 * the values and also determines if the values are copied or borrowed,
5429 * see the section on
5430 * [GVariant format strings][gvariant-format-strings-pointers].
5435 g_variant_get (GVariant *value,
5436 const gchar *format_string,
5441 g_return_if_fail (value != NULL);
5442 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5444 /* if any direct-pointer-access formats are in use, flatten first */
5445 if (strchr (format_string, '&'))
5446 g_variant_get_data (value);
5448 va_start (ap, format_string);
5449 g_variant_get_va (value, format_string, NULL, &ap);
5454 * g_variant_get_va: (skip)
5455 * @value: a #GVariant
5456 * @format_string: a string that is prefixed with a format string
5457 * @endptr: (nullable) (default NULL): location to store the end pointer,
5459 * @app: a pointer to a #va_list
5461 * This function is intended to be used by libraries based on #GVariant
5462 * that want to provide g_variant_get()-like functionality to their
5465 * The API is more general than g_variant_get() to allow a wider range
5468 * @format_string must still point to a valid format string, but it only
5469 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5470 * non-%NULL then it is updated to point to the first character past the
5471 * end of the format string.
5473 * @app is a pointer to a #va_list. The arguments, according to
5474 * @format_string, are collected from this #va_list and the list is left
5475 * pointing to the argument following the last.
5477 * These two generalisations allow mixing of multiple calls to
5478 * g_variant_new_va() and g_variant_get_va() within a single actual
5479 * varargs call by the user.
5481 * @format_string determines the C types that are used for unpacking
5482 * the values and also determines if the values are copied or borrowed,
5483 * see the section on
5484 * [GVariant format strings][gvariant-format-strings-pointers].
5489 g_variant_get_va (GVariant *value,
5490 const gchar *format_string,
5491 const gchar **endptr,
5494 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5495 g_return_if_fail (value != NULL);
5496 g_return_if_fail (app != NULL);
5498 /* if any direct-pointer-access formats are in use, flatten first */
5499 if (strchr (format_string, '&'))
5500 g_variant_get_data (value);
5502 g_variant_valist_get (&format_string, value, FALSE, app);
5505 *endptr = format_string;
5508 /* Varargs-enabled Utility Functions {{{1 */
5511 * g_variant_builder_add: (skip)
5512 * @builder: a #GVariantBuilder
5513 * @format_string: a #GVariant varargs format string
5514 * @...: arguments, as per @format_string
5516 * Adds to a #GVariantBuilder.
5518 * This call is a convenience wrapper that is exactly equivalent to
5519 * calling g_variant_new() followed by g_variant_builder_add_value().
5521 * Note that the arguments must be of the correct width for their types
5522 * specified in @format_string. This can be achieved by casting them. See
5523 * the [GVariant varargs documentation][gvariant-varargs].
5525 * This function might be used as follows:
5527 * |[<!-- language="C" -->
5529 * make_pointless_dictionary (void)
5531 * GVariantBuilder builder;
5534 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5535 * for (i = 0; i < 16; i++)
5539 * sprintf (buf, "%d", i);
5540 * g_variant_builder_add (&builder, "{is}", i, buf);
5543 * return g_variant_builder_end (&builder);
5550 g_variant_builder_add (GVariantBuilder *builder,
5551 const gchar *format_string,
5557 va_start (ap, format_string);
5558 variant = g_variant_new_va (format_string, NULL, &ap);
5561 g_variant_builder_add_value (builder, variant);
5565 * g_variant_get_child: (skip)
5566 * @value: a container #GVariant
5567 * @index_: the index of the child to deconstruct
5568 * @format_string: a #GVariant format string
5569 * @...: arguments, as per @format_string
5571 * Reads a child item out of a container #GVariant instance and
5572 * deconstructs it according to @format_string. This call is
5573 * essentially a combination of g_variant_get_child_value() and
5576 * @format_string determines the C types that are used for unpacking
5577 * the values and also determines if the values are copied or borrowed,
5578 * see the section on
5579 * [GVariant format strings][gvariant-format-strings-pointers].
5584 g_variant_get_child (GVariant *value,
5586 const gchar *format_string,
5592 /* if any direct-pointer-access formats are in use, flatten first */
5593 if (strchr (format_string, '&'))
5594 g_variant_get_data (value);
5596 child = g_variant_get_child_value (value, index_);
5597 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5599 va_start (ap, format_string);
5600 g_variant_get_va (child, format_string, NULL, &ap);
5603 g_variant_unref (child);
5607 * g_variant_iter_next: (skip)
5608 * @iter: a #GVariantIter
5609 * @format_string: a GVariant format string
5610 * @...: the arguments to unpack the value into
5612 * Gets the next item in the container and unpacks it into the variable
5613 * argument list according to @format_string, returning %TRUE.
5615 * If no more items remain then %FALSE is returned.
5617 * All of the pointers given on the variable arguments list of this
5618 * function are assumed to point at uninitialised memory. It is the
5619 * responsibility of the caller to free all of the values returned by
5620 * the unpacking process.
5622 * Here is an example for memory management with g_variant_iter_next():
5623 * |[<!-- language="C" -->
5624 * // Iterates a dictionary of type 'a{sv}'
5626 * iterate_dictionary (GVariant *dictionary)
5628 * GVariantIter iter;
5632 * g_variant_iter_init (&iter, dictionary);
5633 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5635 * g_print ("Item '%s' has type '%s'\n", key,
5636 * g_variant_get_type_string (value));
5638 * // must free data for ourselves
5639 * g_variant_unref (value);
5645 * For a solution that is likely to be more convenient to C programmers
5646 * when dealing with loops, see g_variant_iter_loop().
5648 * @format_string determines the C types that are used for unpacking
5649 * the values and also determines if the values are copied or borrowed.
5651 * See the section on
5652 * [GVariant format strings][gvariant-format-strings-pointers].
5654 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5659 g_variant_iter_next (GVariantIter *iter,
5660 const gchar *format_string,
5665 value = g_variant_iter_next_value (iter);
5667 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5674 va_start (ap, format_string);
5675 g_variant_valist_get (&format_string, value, FALSE, &ap);
5678 g_variant_unref (value);
5681 return value != NULL;
5685 * g_variant_iter_loop: (skip)
5686 * @iter: a #GVariantIter
5687 * @format_string: a GVariant format string
5688 * @...: the arguments to unpack the value into
5690 * Gets the next item in the container and unpacks it into the variable
5691 * argument list according to @format_string, returning %TRUE.
5693 * If no more items remain then %FALSE is returned.
5695 * On the first call to this function, the pointers appearing on the
5696 * variable argument list are assumed to point at uninitialised memory.
5697 * On the second and later calls, it is assumed that the same pointers
5698 * will be given and that they will point to the memory as set by the
5699 * previous call to this function. This allows the previous values to
5700 * be freed, as appropriate.
5702 * This function is intended to be used with a while loop as
5703 * demonstrated in the following example. This function can only be
5704 * used when iterating over an array. It is only valid to call this
5705 * function with a string constant for the format string and the same
5706 * string constant must be used each time. Mixing calls to this
5707 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5708 * the same iterator causes undefined behavior.
5710 * If you break out of a such a while loop using g_variant_iter_loop() then
5711 * you must free or unreference all the unpacked values as you would with
5712 * g_variant_get(). Failure to do so will cause a memory leak.
5714 * Here is an example for memory management with g_variant_iter_loop():
5715 * |[<!-- language="C" -->
5716 * // Iterates a dictionary of type 'a{sv}'
5718 * iterate_dictionary (GVariant *dictionary)
5720 * GVariantIter iter;
5724 * g_variant_iter_init (&iter, dictionary);
5725 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5727 * g_print ("Item '%s' has type '%s'\n", key,
5728 * g_variant_get_type_string (value));
5730 * // no need to free 'key' and 'value' here
5731 * // unless breaking out of this loop
5736 * For most cases you should use g_variant_iter_next().
5738 * This function is really only useful when unpacking into #GVariant or
5739 * #GVariantIter in order to allow you to skip the call to
5740 * g_variant_unref() or g_variant_iter_free().
5742 * For example, if you are only looping over simple integer and string
5743 * types, g_variant_iter_next() is definitely preferred. For string
5744 * types, use the '&' prefix to avoid allocating any memory at all (and
5745 * thereby avoiding the need to free anything as well).
5747 * @format_string determines the C types that are used for unpacking
5748 * the values and also determines if the values are copied or borrowed.
5750 * See the section on
5751 * [GVariant format strings][gvariant-format-strings-pointers].
5753 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5759 g_variant_iter_loop (GVariantIter *iter,
5760 const gchar *format_string,
5763 gboolean first_time = GVSI(iter)->loop_format == NULL;
5767 g_return_val_if_fail (first_time ||
5768 format_string == GVSI(iter)->loop_format,
5773 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5774 GVSI(iter)->loop_format = format_string;
5776 if (strchr (format_string, '&'))
5777 g_variant_get_data (GVSI(iter)->value);
5780 value = g_variant_iter_next_value (iter);
5782 g_return_val_if_fail (!first_time ||
5783 valid_format_string (format_string, TRUE, value),
5786 va_start (ap, format_string);
5787 g_variant_valist_get (&format_string, value, !first_time, &ap);
5791 g_variant_unref (value);
5793 return value != NULL;
5796 /* Serialised data {{{1 */
5798 g_variant_deep_copy (GVariant *value)
5800 switch (g_variant_classify (value))
5802 case G_VARIANT_CLASS_MAYBE:
5803 case G_VARIANT_CLASS_ARRAY:
5804 case G_VARIANT_CLASS_TUPLE:
5805 case G_VARIANT_CLASS_DICT_ENTRY:
5806 case G_VARIANT_CLASS_VARIANT:
5808 GVariantBuilder builder;
5812 g_variant_builder_init (&builder, g_variant_get_type (value));
5813 g_variant_iter_init (&iter, value);
5815 while ((child = g_variant_iter_next_value (&iter)))
5817 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5818 g_variant_unref (child);
5821 return g_variant_builder_end (&builder);
5824 case G_VARIANT_CLASS_BOOLEAN:
5825 return g_variant_new_boolean (g_variant_get_boolean (value));
5827 case G_VARIANT_CLASS_BYTE:
5828 return g_variant_new_byte (g_variant_get_byte (value));
5830 case G_VARIANT_CLASS_INT16:
5831 return g_variant_new_int16 (g_variant_get_int16 (value));
5833 case G_VARIANT_CLASS_UINT16:
5834 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5836 case G_VARIANT_CLASS_INT32:
5837 return g_variant_new_int32 (g_variant_get_int32 (value));
5839 case G_VARIANT_CLASS_UINT32:
5840 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5842 case G_VARIANT_CLASS_INT64:
5843 return g_variant_new_int64 (g_variant_get_int64 (value));
5845 case G_VARIANT_CLASS_UINT64:
5846 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5848 case G_VARIANT_CLASS_HANDLE:
5849 return g_variant_new_handle (g_variant_get_handle (value));
5851 case G_VARIANT_CLASS_DOUBLE:
5852 return g_variant_new_double (g_variant_get_double (value));
5854 case G_VARIANT_CLASS_STRING:
5855 return g_variant_new_string (g_variant_get_string (value, NULL));
5857 case G_VARIANT_CLASS_OBJECT_PATH:
5858 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5860 case G_VARIANT_CLASS_SIGNATURE:
5861 return g_variant_new_signature (g_variant_get_string (value, NULL));
5864 g_assert_not_reached ();
5868 * g_variant_get_normal_form:
5869 * @value: a #GVariant
5871 * Gets a #GVariant instance that has the same value as @value and is
5872 * trusted to be in normal form.
5874 * If @value is already trusted to be in normal form then a new
5875 * reference to @value is returned.
5877 * If @value is not already trusted, then it is scanned to check if it
5878 * is in normal form. If it is found to be in normal form then it is
5879 * marked as trusted and a new reference to it is returned.
5881 * If @value is found not to be in normal form then a new trusted
5882 * #GVariant is created with the same value as @value.
5884 * It makes sense to call this function if you've received #GVariant
5885 * data from untrusted sources and you want to ensure your serialised
5886 * output is definitely in normal form.
5888 * If @value is already in normal form, a new reference will be returned
5889 * (which will be floating if @value is floating). If it is not in normal form,
5890 * the newly created #GVariant will be returned with a single non-floating
5891 * reference. Typically, g_variant_take_ref() should be called on the return
5892 * value from this function to guarantee ownership of a single non-floating
5895 * Returns: (transfer full): a trusted #GVariant
5900 g_variant_get_normal_form (GVariant *value)
5904 if (g_variant_is_normal_form (value))
5905 return g_variant_ref (value);
5907 trusted = g_variant_deep_copy (value);
5908 g_assert (g_variant_is_trusted (trusted));
5910 return g_variant_ref_sink (trusted);
5914 * g_variant_byteswap:
5915 * @value: a #GVariant
5917 * Performs a byteswapping operation on the contents of @value. The
5918 * result is that all multi-byte numeric data contained in @value is
5919 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5920 * integers as well as file handles and double precision floating point
5923 * This function is an identity mapping on any value that does not
5924 * contain multi-byte numeric data. That include strings, booleans,
5925 * bytes and containers containing only these things (recursively).
5927 * The returned value is always in normal form and is marked as trusted.
5929 * Returns: (transfer full): the byteswapped form of @value
5934 g_variant_byteswap (GVariant *value)
5936 GVariantTypeInfo *type_info;
5940 type_info = g_variant_get_type_info (value);
5942 g_variant_type_info_query (type_info, &alignment, NULL);
5945 /* (potentially) contains multi-byte numeric data */
5947 GVariantSerialised serialised;
5951 trusted = g_variant_get_normal_form (value);
5952 serialised.type_info = g_variant_get_type_info (trusted);
5953 serialised.size = g_variant_get_size (trusted);
5954 serialised.data = g_malloc (serialised.size);
5955 serialised.depth = g_variant_get_depth (trusted);
5956 g_variant_store (trusted, serialised.data);
5957 g_variant_unref (trusted);
5959 g_variant_serialised_byteswap (serialised);
5961 bytes = g_bytes_new_take (serialised.data, serialised.size);
5962 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5963 g_bytes_unref (bytes);
5966 /* contains no multi-byte data */
5969 return g_variant_ref_sink (new);
5973 * g_variant_new_from_data:
5974 * @type: a definite #GVariantType
5975 * @data: (array length=size) (element-type guint8): the serialised data
5976 * @size: the size of @data
5977 * @trusted: %TRUE if @data is definitely in normal form
5978 * @notify: (scope async): function to call when @data is no longer needed
5979 * @user_data: data for @notify
5981 * Creates a new #GVariant instance from serialised data.
5983 * @type is the type of #GVariant instance that will be constructed.
5984 * The interpretation of @data depends on knowing the type.
5986 * @data is not modified by this function and must remain valid with an
5987 * unchanging value until such a time as @notify is called with
5988 * @user_data. If the contents of @data change before that time then
5989 * the result is undefined.
5991 * If @data is trusted to be serialised data in normal form then
5992 * @trusted should be %TRUE. This applies to serialised data created
5993 * within this process or read from a trusted location on the disk (such
5994 * as a file installed in /usr/lib alongside your application). You
5995 * should set trusted to %FALSE if @data is read from the network, a
5996 * file in the user's home directory, etc.
5998 * If @data was not stored in this machine's native endianness, any multi-byte
5999 * numeric values in the returned variant will also be in non-native
6000 * endianness. g_variant_byteswap() can be used to recover the original values.
6002 * @notify will be called with @user_data when @data is no longer
6003 * needed. The exact time of this call is unspecified and might even be
6004 * before this function returns.
6006 * Note: @data must be backed by memory that is aligned appropriately for the
6007 * @type being loaded. Otherwise this function will internally create a copy of
6008 * the memory (since GLib 2.60) or (in older versions) fail and exit the
6011 * Returns: (transfer none): a new floating #GVariant of type @type
6016 g_variant_new_from_data (const GVariantType *type,
6020 GDestroyNotify notify,
6026 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6027 g_return_val_if_fail (data != NULL || size == 0, NULL);
6030 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6032 bytes = g_bytes_new_static (data, size);
6034 value = g_variant_new_from_bytes (type, bytes, trusted);
6035 g_bytes_unref (bytes);
6041 /* vim:set foldmethod=marker: */