2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Author: Ryan Lortie <desrt@desrt.ca>
27 #include <glib/gvariant-serialiser.h>
28 #include "gvariant-internal.h"
29 #include <glib/gvariant-core.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gstrfuncs.h>
32 #include <glib/gslice.h>
33 #include <glib/ghash.h>
34 #include <glib/gmem.h>
41 * @short_description: strongly typed value datatype
42 * @see_also: GVariantType
44 * #GVariant is a variant datatype; it can contain one or more values
45 * along with information about the type of the values.
47 * A #GVariant may contain simple types, like an integer, or a boolean value;
48 * or complex types, like an array of two strings, or a dictionary of key
49 * value pairs. A #GVariant is also immutable: once it's been created neither
50 * its type nor its content can be modified further.
52 * GVariant is useful whenever data needs to be serialized, for example when
53 * sending method parameters in D-Bus, or when saving settings using GSettings.
55 * When creating a new #GVariant, you pass the data you want to store in it
56 * along with a string representing the type of data you wish to pass to it.
58 * For instance, if you want to create a #GVariant holding an integer value you
61 * |[<!-- language="C" -->
62 * GVariant *v = g_variant_new ("u", 40);
65 * The string "u" in the first argument tells #GVariant that the data passed to
66 * the constructor (40) is going to be an unsigned integer.
68 * More advanced examples of #GVariant in use can be found in documentation for
69 * [GVariant format strings][gvariant-format-strings-pointers].
71 * The range of possible values is determined by the type.
73 * The type system used by #GVariant is #GVariantType.
75 * #GVariant instances always have a type and a value (which are given
76 * at construction time). The type and value of a #GVariant instance
77 * can never change other than by the #GVariant itself being
78 * destroyed. A #GVariant cannot contain a pointer.
80 * #GVariant is reference counted using g_variant_ref() and
81 * g_variant_unref(). #GVariant also has floating reference counts --
82 * see g_variant_ref_sink().
84 * #GVariant is completely threadsafe. A #GVariant instance can be
85 * concurrently accessed in any way from any number of threads without
88 * #GVariant is heavily optimised for dealing with data in serialized
89 * form. It works particularly well with data located in memory-mapped
90 * files. It can perform nearly all deserialization operations in a
91 * small constant time, usually touching only a single memory page.
92 * Serialized #GVariant data can also be sent over the network.
94 * #GVariant is largely compatible with D-Bus. Almost all types of
95 * #GVariant instances can be sent over D-Bus. See #GVariantType for
96 * exceptions. (However, #GVariant's serialization format is not the same
97 * as the serialization format of a D-Bus message body: use #GDBusMessage,
98 * in the gio library, for those.)
100 * For space-efficiency, the #GVariant serialization format does not
101 * automatically include the variant's length, type or endianness,
102 * which must either be implied from context (such as knowledge that a
103 * particular file format always contains a little-endian
104 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
105 * or supplied out-of-band (for instance, a length, type and/or endianness
106 * indicator could be placed at the beginning of a file, network message
107 * or network stream).
109 * A #GVariant's size is limited mainly by any lower level operating
110 * system constraints, such as the number of bits in #gsize. For
111 * example, it is reasonable to have a 2GB file mapped into memory
112 * with #GMappedFile, and call g_variant_new_from_data() on it.
114 * For convenience to C programmers, #GVariant features powerful
115 * varargs-based value construction and destruction. This feature is
116 * designed to be embedded in other libraries.
118 * There is a Python-inspired text language for describing #GVariant
119 * values. #GVariant includes a printer for this language and a parser
120 * with type inferencing.
124 * #GVariant tries to be quite efficient with respect to memory use.
125 * This section gives a rough idea of how much memory is used by the
126 * current implementation. The information here is subject to change
129 * The memory allocated by #GVariant can be grouped into 4 broad
130 * purposes: memory for serialized data, memory for the type
131 * information cache, buffer management memory and memory for the
132 * #GVariant structure itself.
134 * ## Serialized Data Memory
136 * This is the memory that is used for storing GVariant data in
137 * serialized form. This is what would be sent over the network or
138 * what would end up on disk, not counting any indicator of the
139 * endianness, or of the length or type of the top-level variant.
141 * The amount of memory required to store a boolean is 1 byte. 16,
142 * 32 and 64 bit integers and double precision floating point numbers
143 * use their "natural" size. Strings (including object path and
144 * signature strings) are stored with a nul terminator, and as such
145 * use the length of the string plus 1 byte.
147 * Maybe types use no space at all to represent the null value and
148 * use the same amount of space (sometimes plus one byte) as the
149 * equivalent non-maybe-typed value to represent the non-null case.
151 * Arrays use the amount of space required to store each of their
152 * members, concatenated. Additionally, if the items stored in an
153 * array are not of a fixed-size (ie: strings, other arrays, etc)
154 * then an additional framing offset is stored for each item. The
155 * size of this offset is either 1, 2 or 4 bytes depending on the
156 * overall size of the container. Additionally, extra padding bytes
157 * are added as required for alignment of child values.
159 * Tuples (including dictionary entries) use the amount of space
160 * required to store each of their members, concatenated, plus one
161 * framing offset (as per arrays) for each non-fixed-sized item in
162 * the tuple, except for the last one. Additionally, extra padding
163 * bytes are added as required for alignment of child values.
165 * Variants use the same amount of space as the item inside of the
166 * variant, plus 1 byte, plus the length of the type string for the
167 * item inside the variant.
169 * As an example, consider a dictionary mapping strings to variants.
170 * In the case that the dictionary is empty, 0 bytes are required for
173 * If we add an item "width" that maps to the int32 value of 500 then
174 * we will use 4 byte to store the int32 (so 6 for the variant
175 * containing it) and 6 bytes for the string. The variant must be
176 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
177 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
178 * for the dictionary entry. An additional 1 byte is added to the
179 * array as a framing offset making a total of 15 bytes.
181 * If we add another entry, "title" that maps to a nullable string
182 * that happens to have a value of null, then we use 0 bytes for the
183 * null value (and 3 bytes for the variant to contain it along with
184 * its type string) plus 6 bytes for the string. Again, we need 2
185 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
187 * We now require extra padding between the two items in the array.
188 * After the 14 bytes of the first item, that's 2 bytes required.
189 * We now require 2 framing offsets for an extra two
190 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
193 * ## Type Information Cache
195 * For each GVariant type that currently exists in the program a type
196 * information structure is kept in the type information cache. The
197 * type information structure is required for rapid deserialization.
199 * Continuing with the above example, if a #GVariant exists with the
200 * type "a{sv}" then a type information struct will exist for
201 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
202 * will share the same type information. Additionally, all
203 * single-digit types are stored in read-only static memory and do
204 * not contribute to the writable memory footprint of a program using
207 * Aside from the type information structures stored in read-only
208 * memory, there are two forms of type information. One is used for
209 * container types where there is a single element type: arrays and
210 * maybe types. The other is used for container types where there
211 * are multiple element types: tuples and dictionary entries.
213 * Array type info structures are 6 * sizeof (void *), plus the
214 * memory required to store the type string itself. This means that
215 * on 32-bit systems, the cache entry for "a{sv}" would require 30
216 * bytes of memory (plus malloc overhead).
218 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
219 * sizeof (void *) for each item in the tuple, plus the memory
220 * required to store the type string itself. A 2-item tuple, for
221 * example, would have a type information structure that consumed
222 * writable memory in the size of 14 * sizeof (void *) (plus type
223 * string) This means that on 32-bit systems, the cache entry for
224 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
226 * This means that in total, for our "a{sv}" example, 91 bytes of
227 * type information would be allocated.
229 * The type information cache, additionally, uses a #GHashTable to
230 * store and look up the cached items and stores a pointer to this
231 * hash table in static storage. The hash table is freed when there
232 * are zero items in the type cache.
234 * Although these sizes may seem large it is important to remember
235 * that a program will probably only have a very small number of
236 * different types of values in it and that only one type information
237 * structure is required for many different values of the same type.
239 * ## Buffer Management Memory
241 * #GVariant uses an internal buffer management structure to deal
242 * with the various different possible sources of serialized data
243 * that it uses. The buffer is responsible for ensuring that the
244 * correct call is made when the data is no longer in use by
245 * #GVariant. This may involve a g_free() or a g_slice_free() or
246 * even g_mapped_file_unref().
248 * One buffer management structure is used for each chunk of
249 * serialized data. The size of the buffer management structure
250 * is 4 * (void *). On 32-bit systems, that's 16 bytes.
252 * ## GVariant structure
254 * The size of a #GVariant structure is 6 * (void *). On 32-bit
255 * systems, that's 24 bytes.
257 * #GVariant structures only exist if they are explicitly created
258 * with API calls. For example, if a #GVariant is constructed out of
259 * serialized data for the example given above (with the dictionary)
260 * then although there are 9 individual values that comprise the
261 * entire dictionary (two keys, two values, two variants containing
262 * the values, two dictionary entries, plus the dictionary itself),
263 * only 1 #GVariant instance exists -- the one referring to the
266 * If calls are made to start accessing the other values then
267 * #GVariant instances will exist for those values only for as long
268 * as they are in use (ie: until you call g_variant_unref()). The
269 * type information is shared. The serialized data and the buffer
270 * management structure for that serialized data is shared by the
275 * To put the entire example together, for our dictionary mapping
276 * strings to variants (with two entries, as given above), we are
277 * using 91 bytes of memory for type information, 29 bytes of memory
278 * for the serialized data, 16 bytes for buffer management and 24
279 * bytes for the #GVariant instance, or a total of 160 bytes, plus
280 * malloc overhead. If we were to use g_variant_get_child_value() to
281 * access the two dictionary entries, we would use an additional 48
282 * bytes. If we were to have other dictionaries of the same type, we
283 * would use more memory for the serialized data and buffer
284 * management for those dictionaries, but the type information would
288 /* definition of GVariant structure is in gvariant-core.c */
290 /* this is a g_return_val_if_fail() for making
291 * sure a (GVariant *) has the required type.
293 #define TYPE_CHECK(value, TYPE, val) \
294 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
295 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
296 "g_variant_is_of_type (" #value \
301 /* Numeric Type Constructor/Getters {{{1 */
303 * g_variant_new_from_trusted:
304 * @type: the #GVariantType
305 * @data: the data to use
306 * @size: the size of @data
308 * Constructs a new trusted #GVariant instance from the provided data.
309 * This is used to implement g_variant_new_* for all the basic types.
311 * Note: @data must be backed by memory that is aligned appropriately for the
312 * @type being loaded. Otherwise this function will internally create a copy of
313 * the memory (since GLib 2.60) or (in older versions) fail and exit the
316 * Returns: a new floating #GVariant
319 g_variant_new_from_trusted (const GVariantType *type,
326 bytes = g_bytes_new (data, size);
327 value = g_variant_new_from_bytes (type, bytes, TRUE);
328 g_bytes_unref (bytes);
334 * g_variant_new_boolean:
335 * @value: a #gboolean value
337 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
339 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
344 g_variant_new_boolean (gboolean value)
348 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
352 * g_variant_get_boolean:
353 * @value: a boolean #GVariant instance
355 * Returns the boolean value of @value.
357 * It is an error to call this function with a @value of any type
358 * other than %G_VARIANT_TYPE_BOOLEAN.
360 * Returns: %TRUE or %FALSE
365 g_variant_get_boolean (GVariant *value)
369 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
371 data = g_variant_get_data (value);
373 return data != NULL ? *data != 0 : FALSE;
376 /* the constructors and accessors for byte, int{16,32,64}, handles and
377 * doubles all look pretty much exactly the same, so we reduce
380 #define NUMERIC_TYPE(TYPE, type, ctype) \
381 GVariant *g_variant_new_##type (ctype value) { \
382 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
383 &value, sizeof value); \
385 ctype g_variant_get_##type (GVariant *value) { \
387 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
388 data = g_variant_get_data (value); \
389 return data != NULL ? *data : 0; \
394 * g_variant_new_byte:
395 * @value: a #guint8 value
397 * Creates a new byte #GVariant instance.
399 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
404 * g_variant_get_byte:
405 * @value: a byte #GVariant instance
407 * Returns the byte value of @value.
409 * It is an error to call this function with a @value of any type
410 * other than %G_VARIANT_TYPE_BYTE.
416 NUMERIC_TYPE (BYTE, byte, guint8)
419 * g_variant_new_int16:
420 * @value: a #gint16 value
422 * Creates a new int16 #GVariant instance.
424 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
429 * g_variant_get_int16:
430 * @value: an int16 #GVariant instance
432 * Returns the 16-bit signed integer value of @value.
434 * It is an error to call this function with a @value of any type
435 * other than %G_VARIANT_TYPE_INT16.
441 NUMERIC_TYPE (INT16, int16, gint16)
444 * g_variant_new_uint16:
445 * @value: a #guint16 value
447 * Creates a new uint16 #GVariant instance.
449 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
454 * g_variant_get_uint16:
455 * @value: a uint16 #GVariant instance
457 * Returns the 16-bit unsigned integer value of @value.
459 * It is an error to call this function with a @value of any type
460 * other than %G_VARIANT_TYPE_UINT16.
462 * Returns: a #guint16
466 NUMERIC_TYPE (UINT16, uint16, guint16)
469 * g_variant_new_int32:
470 * @value: a #gint32 value
472 * Creates a new int32 #GVariant instance.
474 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
479 * g_variant_get_int32:
480 * @value: an int32 #GVariant instance
482 * Returns the 32-bit signed integer value of @value.
484 * It is an error to call this function with a @value of any type
485 * other than %G_VARIANT_TYPE_INT32.
491 NUMERIC_TYPE (INT32, int32, gint32)
494 * g_variant_new_uint32:
495 * @value: a #guint32 value
497 * Creates a new uint32 #GVariant instance.
499 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
504 * g_variant_get_uint32:
505 * @value: a uint32 #GVariant instance
507 * Returns the 32-bit unsigned integer value of @value.
509 * It is an error to call this function with a @value of any type
510 * other than %G_VARIANT_TYPE_UINT32.
512 * Returns: a #guint32
516 NUMERIC_TYPE (UINT32, uint32, guint32)
519 * g_variant_new_int64:
520 * @value: a #gint64 value
522 * Creates a new int64 #GVariant instance.
524 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
529 * g_variant_get_int64:
530 * @value: an int64 #GVariant instance
532 * Returns the 64-bit signed integer value of @value.
534 * It is an error to call this function with a @value of any type
535 * other than %G_VARIANT_TYPE_INT64.
541 NUMERIC_TYPE (INT64, int64, gint64)
544 * g_variant_new_uint64:
545 * @value: a #guint64 value
547 * Creates a new uint64 #GVariant instance.
549 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
554 * g_variant_get_uint64:
555 * @value: a uint64 #GVariant instance
557 * Returns the 64-bit unsigned integer value of @value.
559 * It is an error to call this function with a @value of any type
560 * other than %G_VARIANT_TYPE_UINT64.
562 * Returns: a #guint64
566 NUMERIC_TYPE (UINT64, uint64, guint64)
569 * g_variant_new_handle:
570 * @value: a #gint32 value
572 * Creates a new handle #GVariant instance.
574 * By convention, handles are indexes into an array of file descriptors
575 * that are sent alongside a D-Bus message. If you're not interacting
576 * with D-Bus, you probably don't need them.
578 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
583 * g_variant_get_handle:
584 * @value: a handle #GVariant instance
586 * Returns the 32-bit signed integer value of @value.
588 * It is an error to call this function with a @value of any type other
589 * than %G_VARIANT_TYPE_HANDLE.
591 * By convention, handles are indexes into an array of file descriptors
592 * that are sent alongside a D-Bus message. If you're not interacting
593 * with D-Bus, you probably don't need them.
599 NUMERIC_TYPE (HANDLE, handle, gint32)
602 * g_variant_new_double:
603 * @value: a #gdouble floating point value
605 * Creates a new double #GVariant instance.
607 * Returns: (transfer none): a floating reference to a new double #GVariant instance
612 * g_variant_get_double:
613 * @value: a double #GVariant instance
615 * Returns the double precision floating point value of @value.
617 * It is an error to call this function with a @value of any type
618 * other than %G_VARIANT_TYPE_DOUBLE.
620 * Returns: a #gdouble
624 NUMERIC_TYPE (DOUBLE, double, gdouble)
626 /* Container type Constructor / Deconstructors {{{1 */
628 * g_variant_new_maybe:
629 * @child_type: (nullable): the #GVariantType of the child, or %NULL
630 * @child: (nullable): the child value, or %NULL
632 * Depending on if @child is %NULL, either wraps @child inside of a
633 * maybe container or creates a Nothing instance for the given @type.
635 * At least one of @child_type and @child must be non-%NULL.
636 * If @child_type is non-%NULL then it must be a definite type.
637 * If they are both non-%NULL then @child_type must be the type
640 * If @child is a floating reference (see g_variant_ref_sink()), the new
641 * instance takes ownership of @child.
643 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
648 g_variant_new_maybe (const GVariantType *child_type,
651 GVariantType *maybe_type;
654 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
656 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
657 g_return_val_if_fail (child_type == NULL || child == NULL ||
658 g_variant_is_of_type (child, child_type),
661 if (child_type == NULL)
662 child_type = g_variant_get_type (child);
664 maybe_type = g_variant_type_new_maybe (child_type);
671 children = g_new (GVariant *, 1);
672 children[0] = g_variant_ref_sink (child);
673 trusted = g_variant_is_trusted (children[0]);
675 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
678 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
680 g_variant_type_free (maybe_type);
686 * g_variant_get_maybe:
687 * @value: a maybe-typed value
689 * Given a maybe-typed #GVariant instance, extract its value. If the
690 * value is Nothing, then this function returns %NULL.
692 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
697 g_variant_get_maybe (GVariant *value)
699 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
701 if (g_variant_n_children (value))
702 return g_variant_get_child_value (value, 0);
708 * g_variant_new_variant: (constructor)
709 * @value: a #GVariant instance
711 * Boxes @value. The result is a #GVariant instance representing a
712 * variant containing the original value.
714 * If @child is a floating reference (see g_variant_ref_sink()), the new
715 * instance takes ownership of @child.
717 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
722 g_variant_new_variant (GVariant *value)
724 g_return_val_if_fail (value != NULL, NULL);
726 g_variant_ref_sink (value);
728 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
729 g_memdup2 (&value, sizeof value),
730 1, g_variant_is_trusted (value));
734 * g_variant_get_variant:
735 * @value: a variant #GVariant instance
737 * Unboxes @value. The result is the #GVariant instance that was
738 * contained in @value.
740 * Returns: (transfer full): the item contained in the variant
745 g_variant_get_variant (GVariant *value)
747 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
749 return g_variant_get_child_value (value, 0);
753 * g_variant_new_array:
754 * @child_type: (nullable): the element type of the new array
755 * @children: (nullable) (array length=n_children): an array of
756 * #GVariant pointers, the children
757 * @n_children: the length of @children
759 * Creates a new #GVariant array from @children.
761 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
762 * child type is determined by inspecting the first element of the
763 * @children array. If @child_type is non-%NULL then it must be a
766 * The items of the array are taken from the @children array. No entry
767 * in the @children array may be %NULL.
769 * All items in the array must have the same type, which must be the
770 * same as @child_type, if given.
772 * If the @children are floating references (see g_variant_ref_sink()), the
773 * new instance takes ownership of them as if via g_variant_ref_sink().
775 * Returns: (transfer none): a floating reference to a new #GVariant array
780 g_variant_new_array (const GVariantType *child_type,
781 GVariant * const *children,
784 GVariantType *array_type;
785 GVariant **my_children;
790 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
791 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
792 g_return_val_if_fail (child_type == NULL ||
793 g_variant_type_is_definite (child_type), NULL);
795 my_children = g_new (GVariant *, n_children);
798 if (child_type == NULL)
799 child_type = g_variant_get_type (children[0]);
800 array_type = g_variant_type_new_array (child_type);
802 for (i = 0; i < n_children; i++)
804 gboolean is_of_child_type = g_variant_is_of_type (children[i], child_type);
805 if G_UNLIKELY (!is_of_child_type)
808 g_variant_unref (my_children[--i]);
809 g_free (my_children);
810 g_return_val_if_fail (is_of_child_type, NULL);
812 my_children[i] = g_variant_ref_sink (children[i]);
813 trusted &= g_variant_is_trusted (children[i]);
816 value = g_variant_new_from_children (array_type, my_children,
817 n_children, trusted);
818 g_variant_type_free (array_type);
824 * g_variant_make_tuple_type:
825 * @children: (array length=n_children): an array of GVariant *
826 * @n_children: the length of @children
828 * Return the type of a tuple containing @children as its items.
830 static GVariantType *
831 g_variant_make_tuple_type (GVariant * const *children,
834 const GVariantType **types;
838 types = g_new (const GVariantType *, n_children);
840 for (i = 0; i < n_children; i++)
841 types[i] = g_variant_get_type (children[i]);
843 type = g_variant_type_new_tuple (types, n_children);
850 * g_variant_new_tuple:
851 * @children: (array length=n_children): the items to make the tuple out of
852 * @n_children: the length of @children
854 * Creates a new tuple #GVariant out of the items in @children. The
855 * type is determined from the types of @children. No entry in the
856 * @children array may be %NULL.
858 * If @n_children is 0 then the unit tuple is constructed.
860 * If the @children are floating references (see g_variant_ref_sink()), the
861 * new instance takes ownership of them as if via g_variant_ref_sink().
863 * Returns: (transfer none): a floating reference to a new #GVariant tuple
868 g_variant_new_tuple (GVariant * const *children,
871 GVariantType *tuple_type;
872 GVariant **my_children;
877 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
879 my_children = g_new (GVariant *, n_children);
882 for (i = 0; i < n_children; i++)
884 my_children[i] = g_variant_ref_sink (children[i]);
885 trusted &= g_variant_is_trusted (children[i]);
888 tuple_type = g_variant_make_tuple_type (children, n_children);
889 value = g_variant_new_from_children (tuple_type, my_children,
890 n_children, trusted);
891 g_variant_type_free (tuple_type);
897 * g_variant_make_dict_entry_type:
898 * @key: a #GVariant, the key
899 * @val: a #GVariant, the value
901 * Return the type of a dictionary entry containing @key and @val as its
904 static GVariantType *
905 g_variant_make_dict_entry_type (GVariant *key,
908 return g_variant_type_new_dict_entry (g_variant_get_type (key),
909 g_variant_get_type (val));
913 * g_variant_new_dict_entry: (constructor)
914 * @key: a basic #GVariant, the key
915 * @value: a #GVariant, the value
917 * Creates a new dictionary entry #GVariant. @key and @value must be
918 * non-%NULL. @key must be a value of a basic type (ie: not a container).
920 * If the @key or @value are floating references (see g_variant_ref_sink()),
921 * the new instance takes ownership of them as if via g_variant_ref_sink().
923 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
928 g_variant_new_dict_entry (GVariant *key,
931 GVariantType *dict_type;
935 g_return_val_if_fail (key != NULL && value != NULL, NULL);
936 g_return_val_if_fail (!g_variant_is_container (key), NULL);
938 children = g_new (GVariant *, 2);
939 children[0] = g_variant_ref_sink (key);
940 children[1] = g_variant_ref_sink (value);
941 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
943 dict_type = g_variant_make_dict_entry_type (key, value);
944 value = g_variant_new_from_children (dict_type, children, 2, trusted);
945 g_variant_type_free (dict_type);
951 * g_variant_lookup: (skip)
952 * @dictionary: a dictionary #GVariant
953 * @key: the key to look up in the dictionary
954 * @format_string: a GVariant format string
955 * @...: the arguments to unpack the value into
957 * Looks up a value in a dictionary #GVariant.
959 * This function is a wrapper around g_variant_lookup_value() and
960 * g_variant_get(). In the case that %NULL would have been returned,
961 * this function returns %FALSE. Otherwise, it unpacks the returned
962 * value and returns %TRUE.
964 * @format_string determines the C types that are used for unpacking
965 * the values and also determines if the values are copied or borrowed,
967 * [GVariant format strings][gvariant-format-strings-pointers].
969 * This function is currently implemented with a linear scan. If you
970 * plan to do many lookups then #GVariantDict may be more efficient.
972 * Returns: %TRUE if a value was unpacked
977 g_variant_lookup (GVariant *dictionary,
979 const gchar *format_string,
986 g_variant_get_data (dictionary);
988 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
989 value = g_variant_lookup_value (dictionary, key, type);
990 g_variant_type_free (type);
996 va_start (ap, format_string);
997 g_variant_get_va (value, format_string, NULL, &ap);
998 g_variant_unref (value);
1009 * g_variant_lookup_value:
1010 * @dictionary: a dictionary #GVariant
1011 * @key: the key to look up in the dictionary
1012 * @expected_type: (nullable): a #GVariantType, or %NULL
1014 * Looks up a value in a dictionary #GVariant.
1016 * This function works with dictionaries of the type a{s*} (and equally
1017 * well with type a{o*}, but we only further discuss the string case
1018 * for sake of clarity).
1020 * In the event that @dictionary has the type a{sv}, the @expected_type
1021 * string specifies what type of value is expected to be inside of the
1022 * variant. If the value inside the variant has a different type then
1023 * %NULL is returned. In the event that @dictionary has a value type other
1024 * than v then @expected_type must directly match the value type and it is
1025 * used to unpack the value directly or an error occurs.
1027 * In either case, if @key is not found in @dictionary, %NULL is returned.
1029 * If the key is found and the value has the correct type, it is
1030 * returned. If @expected_type was specified then any non-%NULL return
1031 * value will have this type.
1033 * This function is currently implemented with a linear scan. If you
1034 * plan to do many lookups then #GVariantDict may be more efficient.
1036 * Returns: (transfer full): the value of the dictionary key, or %NULL
1041 g_variant_lookup_value (GVariant *dictionary,
1043 const GVariantType *expected_type)
1049 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1050 G_VARIANT_TYPE ("a{s*}")) ||
1051 g_variant_is_of_type (dictionary,
1052 G_VARIANT_TYPE ("a{o*}")),
1055 g_variant_iter_init (&iter, dictionary);
1057 while ((entry = g_variant_iter_next_value (&iter)))
1059 GVariant *entry_key;
1062 entry_key = g_variant_get_child_value (entry, 0);
1063 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1064 g_variant_unref (entry_key);
1069 g_variant_unref (entry);
1075 value = g_variant_get_child_value (entry, 1);
1076 g_variant_unref (entry);
1078 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1082 tmp = g_variant_get_variant (value);
1083 g_variant_unref (value);
1085 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1087 g_variant_unref (tmp);
1094 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1095 g_variant_is_of_type (value, expected_type), NULL);
1101 * g_variant_get_fixed_array:
1102 * @value: a #GVariant array with fixed-sized elements
1103 * @n_elements: (out): a pointer to the location to store the number of items
1104 * @element_size: the size of each element
1106 * Provides access to the serialized data for an array of fixed-sized
1109 * @value must be an array with fixed-sized elements. Numeric types are
1110 * fixed-size, as are tuples containing only other fixed-sized types.
1112 * @element_size must be the size of a single element in the array,
1113 * as given by the section on
1114 * [serialized data memory][gvariant-serialized-data-memory].
1116 * In particular, arrays of these fixed-sized types can be interpreted
1117 * as an array of the given C type, with @element_size set to the size
1118 * the appropriate type:
1119 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1120 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1121 * - %G_VARIANT_TYPE_BYTE: #guint8
1122 * - %G_VARIANT_TYPE_HANDLE: #guint32
1123 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1125 * For example, if calling this function for an array of 32-bit integers,
1126 * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1127 * of a double-check that the form of the serialized data matches the caller's
1130 * @n_elements, which must be non-%NULL, is set equal to the number of
1131 * items in the array.
1133 * Returns: (array length=n_elements) (transfer none): a pointer to
1139 g_variant_get_fixed_array (GVariant *value,
1143 GVariantTypeInfo *array_info;
1144 gsize array_element_size;
1148 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1150 g_return_val_if_fail (n_elements != NULL, NULL);
1151 g_return_val_if_fail (element_size > 0, NULL);
1153 array_info = g_variant_get_type_info (value);
1154 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1156 g_return_val_if_fail (array_element_size, NULL);
1158 if G_UNLIKELY (array_element_size != element_size)
1160 if (array_element_size)
1161 g_critical ("g_variant_get_fixed_array: assertion "
1162 "'g_variant_array_has_fixed_size (value, element_size)' "
1163 "failed: array size %"G_GSIZE_FORMAT" does not match "
1164 "given element_size %"G_GSIZE_FORMAT".",
1165 array_element_size, element_size);
1167 g_critical ("g_variant_get_fixed_array: assertion "
1168 "'g_variant_array_has_fixed_size (value, element_size)' "
1169 "failed: array does not have fixed size.");
1172 data = g_variant_get_data (value);
1173 size = g_variant_get_size (value);
1175 if (size % element_size)
1178 *n_elements = size / element_size;
1187 * g_variant_new_fixed_array:
1188 * @element_type: the #GVariantType of each element
1189 * @elements: a pointer to the fixed array of contiguous elements
1190 * @n_elements: the number of elements
1191 * @element_size: the size of each element
1193 * Constructs a new array #GVariant instance, where the elements are
1194 * of @element_type type.
1196 * @elements must be an array with fixed-sized elements. Numeric types are
1197 * fixed-size as are tuples containing only other fixed-sized types.
1199 * @element_size must be the size of a single element in the array.
1200 * For example, if calling this function for an array of 32-bit integers,
1201 * you might say sizeof(gint32). This value isn't used except for the purpose
1202 * of a double-check that the form of the serialized data matches the caller's
1205 * @n_elements must be the length of the @elements array.
1207 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1212 g_variant_new_fixed_array (const GVariantType *element_type,
1213 gconstpointer elements,
1217 GVariantType *array_type;
1218 gsize array_element_size;
1219 GVariantTypeInfo *array_info;
1223 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1224 g_return_val_if_fail (element_size > 0, NULL);
1226 array_type = g_variant_type_new_array (element_type);
1227 array_info = g_variant_type_info_get (array_type);
1228 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1229 if G_UNLIKELY (array_element_size != element_size)
1231 if (array_element_size)
1232 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1233 " does not match given element_size %" G_GSIZE_FORMAT ".",
1234 array_element_size, element_size);
1236 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1240 data = g_memdup2 (elements, n_elements * element_size);
1241 value = g_variant_new_from_data (array_type, data,
1242 n_elements * element_size,
1243 FALSE, g_free, data);
1245 g_variant_type_free (array_type);
1246 g_variant_type_info_unref (array_info);
1251 /* String type constructor/getters/validation {{{1 */
1253 * g_variant_new_string:
1254 * @string: a normal UTF-8 nul-terminated string
1256 * Creates a string #GVariant with the contents of @string.
1258 * @string must be valid UTF-8, and must not be %NULL. To encode
1259 * potentially-%NULL strings, use g_variant_new() with `ms` as the
1260 * [format string][gvariant-format-strings-maybe-types].
1262 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1267 g_variant_new_string (const gchar *string)
1269 g_return_val_if_fail (string != NULL, NULL);
1270 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1272 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1273 string, strlen (string) + 1);
1277 * g_variant_new_take_string: (skip)
1278 * @string: a normal UTF-8 nul-terminated string
1280 * Creates a string #GVariant with the contents of @string.
1282 * @string must be valid UTF-8, and must not be %NULL. To encode
1283 * potentially-%NULL strings, use this with g_variant_new_maybe().
1285 * This function consumes @string. g_free() will be called on @string
1286 * when it is no longer required.
1288 * You must not modify or access @string in any other way after passing
1289 * it to this function. It is even possible that @string is immediately
1292 * Returns: (transfer none): a floating reference to a new string
1293 * #GVariant instance
1298 g_variant_new_take_string (gchar *string)
1303 g_return_val_if_fail (string != NULL, NULL);
1304 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1306 bytes = g_bytes_new_take (string, strlen (string) + 1);
1307 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1308 g_bytes_unref (bytes);
1314 * g_variant_new_printf: (skip)
1315 * @format_string: a printf-style format string
1316 * @...: arguments for @format_string
1318 * Creates a string-type GVariant using printf formatting.
1320 * This is similar to calling g_strdup_printf() and then
1321 * g_variant_new_string() but it saves a temporary variable and an
1324 * Returns: (transfer none): a floating reference to a new string
1325 * #GVariant instance
1330 g_variant_new_printf (const gchar *format_string,
1338 g_return_val_if_fail (format_string != NULL, NULL);
1340 va_start (ap, format_string);
1341 string = g_strdup_vprintf (format_string, ap);
1344 bytes = g_bytes_new_take (string, strlen (string) + 1);
1345 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1346 g_bytes_unref (bytes);
1352 * g_variant_new_object_path:
1353 * @object_path: a normal C nul-terminated string
1355 * Creates a D-Bus object path #GVariant with the contents of @string.
1356 * @string must be a valid D-Bus object path. Use
1357 * g_variant_is_object_path() if you're not sure.
1359 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1364 g_variant_new_object_path (const gchar *object_path)
1366 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1368 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1369 object_path, strlen (object_path) + 1);
1373 * g_variant_is_object_path:
1374 * @string: a normal C nul-terminated string
1376 * Determines if a given string is a valid D-Bus object path. You
1377 * should ensure that a string is a valid D-Bus object path before
1378 * passing it to g_variant_new_object_path().
1380 * A valid object path starts with `/` followed by zero or more
1381 * sequences of characters separated by `/` characters. Each sequence
1382 * must contain only the characters `[A-Z][a-z][0-9]_`. No sequence
1383 * (including the one following the final `/` character) may be empty.
1385 * Returns: %TRUE if @string is a D-Bus object path
1390 g_variant_is_object_path (const gchar *string)
1392 g_return_val_if_fail (string != NULL, FALSE);
1394 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1398 * g_variant_new_signature:
1399 * @signature: a normal C nul-terminated string
1401 * Creates a D-Bus type signature #GVariant with the contents of
1402 * @string. @string must be a valid D-Bus type signature. Use
1403 * g_variant_is_signature() if you're not sure.
1405 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1410 g_variant_new_signature (const gchar *signature)
1412 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1414 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1415 signature, strlen (signature) + 1);
1419 * g_variant_is_signature:
1420 * @string: a normal C nul-terminated string
1422 * Determines if a given string is a valid D-Bus type signature. You
1423 * should ensure that a string is a valid D-Bus type signature before
1424 * passing it to g_variant_new_signature().
1426 * D-Bus type signatures consist of zero or more definite #GVariantType
1427 * strings in sequence.
1429 * Returns: %TRUE if @string is a D-Bus type signature
1434 g_variant_is_signature (const gchar *string)
1436 g_return_val_if_fail (string != NULL, FALSE);
1438 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1442 * g_variant_get_string:
1443 * @value: a string #GVariant instance
1444 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1445 * to store the length
1447 * Returns the string value of a #GVariant instance with a string
1448 * type. This includes the types %G_VARIANT_TYPE_STRING,
1449 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1451 * The string will always be UTF-8 encoded, will never be %NULL, and will never
1452 * contain nul bytes.
1454 * If @length is non-%NULL then the length of the string (in bytes) is
1455 * returned there. For trusted values, this information is already
1456 * known. Untrusted values will be validated and, if valid, a strlen() will be
1457 * performed. If invalid, a default value will be returned — for
1458 * %G_VARIANT_TYPE_OBJECT_PATH, this is `"/"`, and for other types it is the
1461 * It is an error to call this function with a @value of any type
1462 * other than those three.
1464 * The return value remains valid as long as @value exists.
1466 * Returns: (transfer none): the constant string, UTF-8 encoded
1471 g_variant_get_string (GVariant *value,
1477 g_return_val_if_fail (value != NULL, NULL);
1478 g_return_val_if_fail (
1479 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1480 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1481 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1483 data = g_variant_get_data (value);
1484 size = g_variant_get_size (value);
1486 if (!g_variant_is_trusted (value))
1488 switch (g_variant_classify (value))
1490 case G_VARIANT_CLASS_STRING:
1491 if (g_variant_serialiser_is_string (data, size))
1498 case G_VARIANT_CLASS_OBJECT_PATH:
1499 if (g_variant_serialiser_is_object_path (data, size))
1506 case G_VARIANT_CLASS_SIGNATURE:
1507 if (g_variant_serialiser_is_signature (data, size))
1515 g_assert_not_reached ();
1526 * g_variant_dup_string:
1527 * @value: a string #GVariant instance
1528 * @length: (out): a pointer to a #gsize, to store the length
1530 * Similar to g_variant_get_string() except that instead of returning
1531 * a constant string, the string is duplicated.
1533 * The string will always be UTF-8 encoded.
1535 * The return value must be freed using g_free().
1537 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1542 g_variant_dup_string (GVariant *value,
1545 return g_strdup (g_variant_get_string (value, length));
1549 * g_variant_new_strv:
1550 * @strv: (array length=length) (element-type utf8): an array of strings
1551 * @length: the length of @strv, or -1
1553 * Constructs an array of strings #GVariant from the given array of
1556 * If @length is -1 then @strv is %NULL-terminated.
1558 * Returns: (transfer none): a new floating #GVariant instance
1563 g_variant_new_strv (const gchar * const *strv,
1567 gsize i, length_unsigned;
1569 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1572 length = g_strv_length ((gchar **) strv);
1573 length_unsigned = length;
1575 strings = g_new (GVariant *, length_unsigned);
1576 for (i = 0; i < length_unsigned; i++)
1577 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1579 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1580 strings, length_unsigned, TRUE);
1584 * g_variant_get_strv:
1585 * @value: an array of strings #GVariant
1586 * @length: (out) (optional): the length of the result, or %NULL
1588 * Gets the contents of an array of strings #GVariant. This call
1589 * makes a shallow copy; the return result should be released with
1590 * g_free(), but the individual strings must not be modified.
1592 * If @length is non-%NULL then the number of elements in the result
1593 * is stored there. In any case, the resulting array will be
1596 * For an empty array, @length will be set to 0 and a pointer to a
1597 * %NULL pointer will be returned.
1599 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1604 g_variant_get_strv (GVariant *value,
1611 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1613 g_variant_get_data (value);
1614 n = g_variant_n_children (value);
1615 strv = g_new (const gchar *, n + 1);
1617 for (i = 0; i < n; i++)
1621 string = g_variant_get_child_value (value, i);
1622 strv[i] = g_variant_get_string (string, NULL);
1623 g_variant_unref (string);
1634 * g_variant_dup_strv:
1635 * @value: an array of strings #GVariant
1636 * @length: (out) (optional): the length of the result, or %NULL
1638 * Gets the contents of an array of strings #GVariant. This call
1639 * makes a deep copy; the return result should be released with
1642 * If @length is non-%NULL then the number of elements in the result
1643 * is stored there. In any case, the resulting array will be
1646 * For an empty array, @length will be set to 0 and a pointer to a
1647 * %NULL pointer will be returned.
1649 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1654 g_variant_dup_strv (GVariant *value,
1661 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1663 n = g_variant_n_children (value);
1664 strv = g_new (gchar *, n + 1);
1666 for (i = 0; i < n; i++)
1670 string = g_variant_get_child_value (value, i);
1671 strv[i] = g_variant_dup_string (string, NULL);
1672 g_variant_unref (string);
1683 * g_variant_new_objv:
1684 * @strv: (array length=length) (element-type utf8): an array of strings
1685 * @length: the length of @strv, or -1
1687 * Constructs an array of object paths #GVariant from the given array of
1690 * Each string must be a valid #GVariant object path; see
1691 * g_variant_is_object_path().
1693 * If @length is -1 then @strv is %NULL-terminated.
1695 * Returns: (transfer none): a new floating #GVariant instance
1700 g_variant_new_objv (const gchar * const *strv,
1704 gsize i, length_unsigned;
1706 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1709 length = g_strv_length ((gchar **) strv);
1710 length_unsigned = length;
1712 strings = g_new (GVariant *, length_unsigned);
1713 for (i = 0; i < length_unsigned; i++)
1714 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1716 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1717 strings, length_unsigned, TRUE);
1721 * g_variant_get_objv:
1722 * @value: an array of object paths #GVariant
1723 * @length: (out) (optional): the length of the result, or %NULL
1725 * Gets the contents of an array of object paths #GVariant. This call
1726 * makes a shallow copy; the return result should be released with
1727 * g_free(), but the individual strings must not be modified.
1729 * If @length is non-%NULL then the number of elements in the result
1730 * is stored there. In any case, the resulting array will be
1733 * For an empty array, @length will be set to 0 and a pointer to a
1734 * %NULL pointer will be returned.
1736 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1741 g_variant_get_objv (GVariant *value,
1748 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1750 g_variant_get_data (value);
1751 n = g_variant_n_children (value);
1752 strv = g_new (const gchar *, n + 1);
1754 for (i = 0; i < n; i++)
1758 string = g_variant_get_child_value (value, i);
1759 strv[i] = g_variant_get_string (string, NULL);
1760 g_variant_unref (string);
1771 * g_variant_dup_objv:
1772 * @value: an array of object paths #GVariant
1773 * @length: (out) (optional): the length of the result, or %NULL
1775 * Gets the contents of an array of object paths #GVariant. This call
1776 * makes a deep copy; the return result should be released with
1779 * If @length is non-%NULL then the number of elements in the result
1780 * is stored there. In any case, the resulting array will be
1783 * For an empty array, @length will be set to 0 and a pointer to a
1784 * %NULL pointer will be returned.
1786 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1791 g_variant_dup_objv (GVariant *value,
1798 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1800 n = g_variant_n_children (value);
1801 strv = g_new (gchar *, n + 1);
1803 for (i = 0; i < n; i++)
1807 string = g_variant_get_child_value (value, i);
1808 strv[i] = g_variant_dup_string (string, NULL);
1809 g_variant_unref (string);
1821 * g_variant_new_bytestring:
1822 * @string: (array zero-terminated=1) (element-type guint8): a normal
1823 * nul-terminated string in no particular encoding
1825 * Creates an array-of-bytes #GVariant with the contents of @string.
1826 * This function is just like g_variant_new_string() except that the
1827 * string need not be valid UTF-8.
1829 * The nul terminator character at the end of the string is stored in
1832 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1837 g_variant_new_bytestring (const gchar *string)
1839 g_return_val_if_fail (string != NULL, NULL);
1841 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1842 string, strlen (string) + 1);
1846 * g_variant_get_bytestring:
1847 * @value: an array-of-bytes #GVariant instance
1849 * Returns the string value of a #GVariant instance with an
1850 * array-of-bytes type. The string has no particular encoding.
1852 * If the array does not end with a nul terminator character, the empty
1853 * string is returned. For this reason, you can always trust that a
1854 * non-%NULL nul-terminated string will be returned by this function.
1856 * If the array contains a nul terminator character somewhere other than
1857 * the last byte then the returned string is the string, up to the first
1858 * such nul character.
1860 * g_variant_get_fixed_array() should be used instead if the array contains
1861 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1863 * It is an error to call this function with a @value that is not an
1866 * The return value remains valid as long as @value exists.
1868 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1869 * the constant string
1874 g_variant_get_bytestring (GVariant *value)
1876 const gchar *string;
1879 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1881 /* Won't be NULL since this is an array type */
1882 string = g_variant_get_data (value);
1883 size = g_variant_get_size (value);
1885 if (size && string[size - 1] == '\0')
1892 * g_variant_dup_bytestring:
1893 * @value: an array-of-bytes #GVariant instance
1894 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1895 * the length (not including the nul terminator)
1897 * Similar to g_variant_get_bytestring() except that instead of
1898 * returning a constant string, the string is duplicated.
1900 * The return value must be freed using g_free().
1902 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1903 * a newly allocated string
1908 g_variant_dup_bytestring (GVariant *value,
1911 const gchar *original = g_variant_get_bytestring (value);
1914 /* don't crash in case get_bytestring() had an assert failure */
1915 if (original == NULL)
1918 size = strlen (original);
1923 return g_memdup2 (original, size + 1);
1927 * g_variant_new_bytestring_array:
1928 * @strv: (array length=length): an array of strings
1929 * @length: the length of @strv, or -1
1931 * Constructs an array of bytestring #GVariant from the given array of
1934 * If @length is -1 then @strv is %NULL-terminated.
1936 * Returns: (transfer none): a new floating #GVariant instance
1941 g_variant_new_bytestring_array (const gchar * const *strv,
1945 gsize i, length_unsigned;
1947 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1950 length = g_strv_length ((gchar **) strv);
1951 length_unsigned = length;
1953 strings = g_new (GVariant *, length_unsigned);
1954 for (i = 0; i < length_unsigned; i++)
1955 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1957 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1958 strings, length_unsigned, TRUE);
1962 * g_variant_get_bytestring_array:
1963 * @value: an array of array of bytes #GVariant ('aay')
1964 * @length: (out) (optional): the length of the result, or %NULL
1966 * Gets the contents of an array of array of bytes #GVariant. This call
1967 * makes a shallow copy; the return result should be released with
1968 * g_free(), but the individual strings must not be modified.
1970 * If @length is non-%NULL then the number of elements in the result is
1971 * stored there. In any case, the resulting array will be
1974 * For an empty array, @length will be set to 0 and a pointer to a
1975 * %NULL pointer will be returned.
1977 * Returns: (array length=length) (transfer container): an array of constant strings
1982 g_variant_get_bytestring_array (GVariant *value,
1989 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1991 g_variant_get_data (value);
1992 n = g_variant_n_children (value);
1993 strv = g_new (const gchar *, n + 1);
1995 for (i = 0; i < n; i++)
1999 string = g_variant_get_child_value (value, i);
2000 strv[i] = g_variant_get_bytestring (string);
2001 g_variant_unref (string);
2012 * g_variant_dup_bytestring_array:
2013 * @value: an array of array of bytes #GVariant ('aay')
2014 * @length: (out) (optional): the length of the result, or %NULL
2016 * Gets the contents of an array of array of bytes #GVariant. This call
2017 * makes a deep copy; the return result should be released with
2020 * If @length is non-%NULL then the number of elements in the result is
2021 * stored there. In any case, the resulting array will be
2024 * For an empty array, @length will be set to 0 and a pointer to a
2025 * %NULL pointer will be returned.
2027 * Returns: (array length=length) (transfer full): an array of strings
2032 g_variant_dup_bytestring_array (GVariant *value,
2039 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2041 g_variant_get_data (value);
2042 n = g_variant_n_children (value);
2043 strv = g_new (gchar *, n + 1);
2045 for (i = 0; i < n; i++)
2049 string = g_variant_get_child_value (value, i);
2050 strv[i] = g_variant_dup_bytestring (string, NULL);
2051 g_variant_unref (string);
2061 /* Type checking and querying {{{1 */
2063 * g_variant_get_type:
2064 * @value: a #GVariant
2066 * Determines the type of @value.
2068 * The return value is valid for the lifetime of @value and must not
2071 * Returns: a #GVariantType
2075 const GVariantType *
2076 g_variant_get_type (GVariant *value)
2078 GVariantTypeInfo *type_info;
2080 g_return_val_if_fail (value != NULL, NULL);
2082 type_info = g_variant_get_type_info (value);
2084 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2088 * g_variant_get_type_string:
2089 * @value: a #GVariant
2091 * Returns the type string of @value. Unlike the result of calling
2092 * g_variant_type_peek_string(), this string is nul-terminated. This
2093 * string belongs to #GVariant and must not be freed.
2095 * Returns: the type string for the type of @value
2100 g_variant_get_type_string (GVariant *value)
2102 GVariantTypeInfo *type_info;
2104 g_return_val_if_fail (value != NULL, NULL);
2106 type_info = g_variant_get_type_info (value);
2108 return g_variant_type_info_get_type_string (type_info);
2112 * g_variant_is_of_type:
2113 * @value: a #GVariant instance
2114 * @type: a #GVariantType
2116 * Checks if a value has a type matching the provided type.
2118 * Returns: %TRUE if the type of @value matches @type
2123 g_variant_is_of_type (GVariant *value,
2124 const GVariantType *type)
2126 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2130 * g_variant_is_container:
2131 * @value: a #GVariant instance
2133 * Checks if @value is a container.
2135 * Returns: %TRUE if @value is a container
2140 g_variant_is_container (GVariant *value)
2142 return g_variant_type_is_container (g_variant_get_type (value));
2147 * g_variant_classify:
2148 * @value: a #GVariant
2150 * Classifies @value according to its top-level type.
2152 * Returns: the #GVariantClass of @value
2158 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2159 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2160 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2161 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2162 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2163 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2164 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2165 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2166 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2167 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2169 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2170 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2172 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2173 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2174 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2175 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2176 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2177 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2179 * The range of possible top-level types of #GVariant instances.
2184 g_variant_classify (GVariant *value)
2186 g_return_val_if_fail (value != NULL, 0);
2188 return *g_variant_get_type_string (value);
2191 /* Pretty printer {{{1 */
2192 /* This function is not introspectable because if @string is NULL,
2193 @returns is (transfer full), otherwise it is (transfer none), which
2194 is not supported by GObjectIntrospection */
2196 * g_variant_print_string: (skip)
2197 * @value: a #GVariant
2198 * @string: (nullable) (default NULL): a #GString, or %NULL
2199 * @type_annotate: %TRUE if type information should be included in
2202 * Behaves as g_variant_print(), but operates on a #GString.
2204 * If @string is non-%NULL then it is appended to and returned. Else,
2205 * a new empty #GString is allocated and it is returned.
2207 * Returns: a #GString containing the string
2212 g_variant_print_string (GVariant *value,
2214 gboolean type_annotate)
2216 if G_UNLIKELY (string == NULL)
2217 string = g_string_new (NULL);
2219 switch (g_variant_classify (value))
2221 case G_VARIANT_CLASS_MAYBE:
2223 g_string_append_printf (string, "@%s ",
2224 g_variant_get_type_string (value));
2226 if (g_variant_n_children (value))
2228 gchar *printed_child;
2233 * Consider the case of the type "mmi". In this case we could
2234 * write "just just 4", but "4" alone is totally unambiguous,
2235 * so we try to drop "just" where possible.
2237 * We have to be careful not to always drop "just", though,
2238 * since "nothing" needs to be distinguishable from "just
2239 * nothing". The case where we need to ensure we keep the
2240 * "just" is actually exactly the case where we have a nested
2243 * Instead of searching for that nested Nothing, we just print
2244 * the contained value into a separate string and see if we
2245 * end up with "nothing" at the end of it. If so, we need to
2246 * add "just" at our level.
2248 element = g_variant_get_child_value (value, 0);
2249 printed_child = g_variant_print (element, FALSE);
2250 g_variant_unref (element);
2252 if (g_str_has_suffix (printed_child, "nothing"))
2253 g_string_append (string, "just ");
2254 g_string_append (string, printed_child);
2255 g_free (printed_child);
2258 g_string_append (string, "nothing");
2262 case G_VARIANT_CLASS_ARRAY:
2263 /* it's an array so the first character of the type string is 'a'
2265 * if the first two characters are 'ay' then it's a bytestring.
2266 * under certain conditions we print those as strings.
2268 if (g_variant_get_type_string (value)[1] == 'y')
2274 /* first determine if it is a byte string.
2275 * that's when there's a single nul character: at the end.
2277 str = g_variant_get_data (value);
2278 size = g_variant_get_size (value);
2280 for (i = 0; i < size; i++)
2284 /* first nul byte is the last byte -> it's a byte string. */
2287 gchar *escaped = g_strescape (str, NULL);
2289 /* use double quotes only if a ' is in the string */
2290 if (strchr (str, '\''))
2291 g_string_append_printf (string, "b\"%s\"", escaped);
2293 g_string_append_printf (string, "b'%s'", escaped);
2301 /* fall through and handle normally... */
2306 * if the first two characters are 'a{' then it's an array of
2307 * dictionary entries (ie: a dictionary) so we print that
2310 if (g_variant_get_type_string (value)[1] == '{')
2313 const gchar *comma = "";
2316 if ((n = g_variant_n_children (value)) == 0)
2319 g_string_append_printf (string, "@%s ",
2320 g_variant_get_type_string (value));
2321 g_string_append (string, "{}");
2325 g_string_append_c (string, '{');
2326 for (i = 0; i < n; i++)
2328 GVariant *entry, *key, *val;
2330 g_string_append (string, comma);
2333 entry = g_variant_get_child_value (value, i);
2334 key = g_variant_get_child_value (entry, 0);
2335 val = g_variant_get_child_value (entry, 1);
2336 g_variant_unref (entry);
2338 g_variant_print_string (key, string, type_annotate);
2339 g_variant_unref (key);
2340 g_string_append (string, ": ");
2341 g_variant_print_string (val, string, type_annotate);
2342 g_variant_unref (val);
2343 type_annotate = FALSE;
2345 g_string_append_c (string, '}');
2348 /* normal (non-dictionary) array */
2350 const gchar *comma = "";
2353 if ((n = g_variant_n_children (value)) == 0)
2356 g_string_append_printf (string, "@%s ",
2357 g_variant_get_type_string (value));
2358 g_string_append (string, "[]");
2362 g_string_append_c (string, '[');
2363 for (i = 0; i < n; i++)
2367 g_string_append (string, comma);
2370 element = g_variant_get_child_value (value, i);
2372 g_variant_print_string (element, string, type_annotate);
2373 g_variant_unref (element);
2374 type_annotate = FALSE;
2376 g_string_append_c (string, ']');
2381 case G_VARIANT_CLASS_TUPLE:
2385 n = g_variant_n_children (value);
2387 g_string_append_c (string, '(');
2388 for (i = 0; i < n; i++)
2392 element = g_variant_get_child_value (value, i);
2393 g_variant_print_string (element, string, type_annotate);
2394 g_string_append (string, ", ");
2395 g_variant_unref (element);
2398 /* for >1 item: remove final ", "
2399 * for 1 item: remove final " ", but leave the ","
2400 * for 0 items: there is only "(", so remove nothing
2402 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2403 g_string_append_c (string, ')');
2407 case G_VARIANT_CLASS_DICT_ENTRY:
2411 g_string_append_c (string, '{');
2413 element = g_variant_get_child_value (value, 0);
2414 g_variant_print_string (element, string, type_annotate);
2415 g_variant_unref (element);
2417 g_string_append (string, ", ");
2419 element = g_variant_get_child_value (value, 1);
2420 g_variant_print_string (element, string, type_annotate);
2421 g_variant_unref (element);
2423 g_string_append_c (string, '}');
2427 case G_VARIANT_CLASS_VARIANT:
2429 GVariant *child = g_variant_get_variant (value);
2431 /* Always annotate types in nested variants, because they are
2432 * (by nature) of variable type.
2434 g_string_append_c (string, '<');
2435 g_variant_print_string (child, string, TRUE);
2436 g_string_append_c (string, '>');
2438 g_variant_unref (child);
2442 case G_VARIANT_CLASS_BOOLEAN:
2443 if (g_variant_get_boolean (value))
2444 g_string_append (string, "true");
2446 g_string_append (string, "false");
2449 case G_VARIANT_CLASS_STRING:
2451 const gchar *str = g_variant_get_string (value, NULL);
2452 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2454 g_string_append_c (string, quote);
2458 gunichar c = g_utf8_get_char (str);
2460 if (c == quote || c == '\\')
2461 g_string_append_c (string, '\\');
2463 if (g_unichar_isprint (c))
2464 g_string_append_unichar (string, c);
2468 g_string_append_c (string, '\\');
2473 g_string_append_c (string, 'a');
2477 g_string_append_c (string, 'b');
2481 g_string_append_c (string, 'f');
2485 g_string_append_c (string, 'n');
2489 g_string_append_c (string, 'r');
2493 g_string_append_c (string, 't');
2497 g_string_append_c (string, 'v');
2501 g_string_append_printf (string, "u%04x", c);
2505 g_string_append_printf (string, "U%08x", c);
2508 str = g_utf8_next_char (str);
2511 g_string_append_c (string, quote);
2515 case G_VARIANT_CLASS_BYTE:
2517 g_string_append (string, "byte ");
2518 g_string_append_printf (string, "0x%02x",
2519 g_variant_get_byte (value));
2522 case G_VARIANT_CLASS_INT16:
2524 g_string_append (string, "int16 ");
2525 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2526 g_variant_get_int16 (value));
2529 case G_VARIANT_CLASS_UINT16:
2531 g_string_append (string, "uint16 ");
2532 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2533 g_variant_get_uint16 (value));
2536 case G_VARIANT_CLASS_INT32:
2537 /* Never annotate this type because it is the default for numbers
2538 * (and this is a *pretty* printer)
2540 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2541 g_variant_get_int32 (value));
2544 case G_VARIANT_CLASS_HANDLE:
2546 g_string_append (string, "handle ");
2547 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2548 g_variant_get_handle (value));
2551 case G_VARIANT_CLASS_UINT32:
2553 g_string_append (string, "uint32 ");
2554 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2555 g_variant_get_uint32 (value));
2558 case G_VARIANT_CLASS_INT64:
2560 g_string_append (string, "int64 ");
2561 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2562 g_variant_get_int64 (value));
2565 case G_VARIANT_CLASS_UINT64:
2567 g_string_append (string, "uint64 ");
2568 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2569 g_variant_get_uint64 (value));
2572 case G_VARIANT_CLASS_DOUBLE:
2577 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2579 for (i = 0; buffer[i]; i++)
2580 if (buffer[i] == '.' || buffer[i] == 'e' ||
2581 buffer[i] == 'n' || buffer[i] == 'N')
2584 /* if there is no '.' or 'e' in the float then add one */
2585 if (buffer[i] == '\0')
2592 g_string_append (string, buffer);
2596 case G_VARIANT_CLASS_OBJECT_PATH:
2598 g_string_append (string, "objectpath ");
2599 g_string_append_printf (string, "\'%s\'",
2600 g_variant_get_string (value, NULL));
2603 case G_VARIANT_CLASS_SIGNATURE:
2605 g_string_append (string, "signature ");
2606 g_string_append_printf (string, "\'%s\'",
2607 g_variant_get_string (value, NULL));
2611 g_assert_not_reached ();
2619 * @value: a #GVariant
2620 * @type_annotate: %TRUE if type information should be included in
2623 * Pretty-prints @value in the format understood by g_variant_parse().
2625 * The format is described [here][gvariant-text].
2627 * If @type_annotate is %TRUE, then type information is included in
2630 * Returns: (transfer full): a newly-allocated string holding the result.
2635 g_variant_print (GVariant *value,
2636 gboolean type_annotate)
2638 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2642 /* Hash, Equal, Compare {{{1 */
2645 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2647 * Generates a hash value for a #GVariant instance.
2649 * The output of this function is guaranteed to be the same for a given
2650 * value only per-process. It may change between different processor
2651 * architectures or even different versions of GLib. Do not use this
2652 * function as a basis for building protocols or file formats.
2654 * The type of @value is #gconstpointer only to allow use of this
2655 * function with #GHashTable. @value must be a #GVariant.
2657 * Returns: a hash value corresponding to @value
2662 g_variant_hash (gconstpointer value_)
2664 GVariant *value = (GVariant *) value_;
2666 switch (g_variant_classify (value))
2668 case G_VARIANT_CLASS_STRING:
2669 case G_VARIANT_CLASS_OBJECT_PATH:
2670 case G_VARIANT_CLASS_SIGNATURE:
2671 return g_str_hash (g_variant_get_string (value, NULL));
2673 case G_VARIANT_CLASS_BOOLEAN:
2674 /* this is a very odd thing to hash... */
2675 return g_variant_get_boolean (value);
2677 case G_VARIANT_CLASS_BYTE:
2678 return g_variant_get_byte (value);
2680 case G_VARIANT_CLASS_INT16:
2681 case G_VARIANT_CLASS_UINT16:
2685 ptr = g_variant_get_data (value);
2693 case G_VARIANT_CLASS_INT32:
2694 case G_VARIANT_CLASS_UINT32:
2695 case G_VARIANT_CLASS_HANDLE:
2699 ptr = g_variant_get_data (value);
2707 case G_VARIANT_CLASS_INT64:
2708 case G_VARIANT_CLASS_UINT64:
2709 case G_VARIANT_CLASS_DOUBLE:
2710 /* need a separate case for these guys because otherwise
2711 * performance could be quite bad on big endian systems
2716 ptr = g_variant_get_data (value);
2719 return ptr[0] + ptr[1];
2725 g_return_val_if_fail (!g_variant_is_container (value), 0);
2726 g_assert_not_reached ();
2732 * @one: (type GVariant): a #GVariant instance
2733 * @two: (type GVariant): a #GVariant instance
2735 * Checks if @one and @two have the same type and value.
2737 * The types of @one and @two are #gconstpointer only to allow use of
2738 * this function with #GHashTable. They must each be a #GVariant.
2740 * Returns: %TRUE if @one and @two are equal
2745 g_variant_equal (gconstpointer one,
2750 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2752 if (g_variant_get_type_info ((GVariant *) one) !=
2753 g_variant_get_type_info ((GVariant *) two))
2756 /* if both values are trusted to be in their canonical serialized form
2757 * then a simple memcmp() of their serialized data will answer the
2760 * if not, then this might generate a false negative (since it is
2761 * possible for two different byte sequences to represent the same
2762 * value). for now we solve this by pretty-printing both values and
2763 * comparing the result.
2765 if (g_variant_is_trusted ((GVariant *) one) &&
2766 g_variant_is_trusted ((GVariant *) two))
2768 gconstpointer data_one, data_two;
2769 gsize size_one, size_two;
2771 size_one = g_variant_get_size ((GVariant *) one);
2772 size_two = g_variant_get_size ((GVariant *) two);
2774 if (size_one != size_two)
2777 data_one = g_variant_get_data ((GVariant *) one);
2778 data_two = g_variant_get_data ((GVariant *) two);
2781 equal = memcmp (data_one, data_two, size_one) == 0;
2787 gchar *strone, *strtwo;
2789 strone = g_variant_print ((GVariant *) one, FALSE);
2790 strtwo = g_variant_print ((GVariant *) two, FALSE);
2791 equal = strcmp (strone, strtwo) == 0;
2800 * g_variant_compare:
2801 * @one: (type GVariant): a basic-typed #GVariant instance
2802 * @two: (type GVariant): a #GVariant instance of the same type
2804 * Compares @one and @two.
2806 * The types of @one and @two are #gconstpointer only to allow use of
2807 * this function with #GTree, #GPtrArray, etc. They must each be a
2810 * Comparison is only defined for basic types (ie: booleans, numbers,
2811 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2812 * ordered in the usual way. Strings are in ASCII lexographical order.
2814 * It is a programmer error to attempt to compare container values or
2815 * two values that have types that are not exactly equal. For example,
2816 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2817 * integer. Also note that this function is not particularly
2818 * well-behaved when it comes to comparison of doubles; in particular,
2819 * the handling of incomparable values (ie: NaN) is undefined.
2821 * If you only require an equality comparison, g_variant_equal() is more
2824 * Returns: negative value if a < b;
2826 * positive value if a > b.
2831 g_variant_compare (gconstpointer one,
2834 GVariant *a = (GVariant *) one;
2835 GVariant *b = (GVariant *) two;
2837 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2839 switch (g_variant_classify (a))
2841 case G_VARIANT_CLASS_BOOLEAN:
2842 return g_variant_get_boolean (a) -
2843 g_variant_get_boolean (b);
2845 case G_VARIANT_CLASS_BYTE:
2846 return ((gint) g_variant_get_byte (a)) -
2847 ((gint) g_variant_get_byte (b));
2849 case G_VARIANT_CLASS_INT16:
2850 return ((gint) g_variant_get_int16 (a)) -
2851 ((gint) g_variant_get_int16 (b));
2853 case G_VARIANT_CLASS_UINT16:
2854 return ((gint) g_variant_get_uint16 (a)) -
2855 ((gint) g_variant_get_uint16 (b));
2857 case G_VARIANT_CLASS_INT32:
2859 gint32 a_val = g_variant_get_int32 (a);
2860 gint32 b_val = g_variant_get_int32 (b);
2862 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2865 case G_VARIANT_CLASS_UINT32:
2867 guint32 a_val = g_variant_get_uint32 (a);
2868 guint32 b_val = g_variant_get_uint32 (b);
2870 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2873 case G_VARIANT_CLASS_INT64:
2875 gint64 a_val = g_variant_get_int64 (a);
2876 gint64 b_val = g_variant_get_int64 (b);
2878 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2881 case G_VARIANT_CLASS_UINT64:
2883 guint64 a_val = g_variant_get_uint64 (a);
2884 guint64 b_val = g_variant_get_uint64 (b);
2886 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2889 case G_VARIANT_CLASS_DOUBLE:
2891 gdouble a_val = g_variant_get_double (a);
2892 gdouble b_val = g_variant_get_double (b);
2894 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2897 case G_VARIANT_CLASS_STRING:
2898 case G_VARIANT_CLASS_OBJECT_PATH:
2899 case G_VARIANT_CLASS_SIGNATURE:
2900 return strcmp (g_variant_get_string (a, NULL),
2901 g_variant_get_string (b, NULL));
2904 g_return_val_if_fail (!g_variant_is_container (a), 0);
2905 g_assert_not_reached ();
2909 /* GVariantIter {{{1 */
2911 * GVariantIter: (skip)
2913 * #GVariantIter is an opaque data structure and can only be accessed
2914 * using the following functions.
2921 const gchar *loop_format;
2927 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2931 struct stack_iter iter;
2933 GVariant *value_ref;
2937 #define GVSI(i) ((struct stack_iter *) (i))
2938 #define GVHI(i) ((struct heap_iter *) (i))
2939 #define GVSI_MAGIC ((gsize) 3579507750u)
2940 #define GVHI_MAGIC ((gsize) 1450270775u)
2941 #define is_valid_iter(i) (i != NULL && \
2942 GVSI(i)->magic == GVSI_MAGIC)
2943 #define is_valid_heap_iter(i) (is_valid_iter(i) && \
2944 GVHI(i)->magic == GVHI_MAGIC)
2947 * g_variant_iter_new:
2948 * @value: a container #GVariant
2950 * Creates a heap-allocated #GVariantIter for iterating over the items
2953 * Use g_variant_iter_free() to free the return value when you no longer
2956 * A reference is taken to @value and will be released only when
2957 * g_variant_iter_free() is called.
2959 * Returns: (transfer full): a new heap-allocated #GVariantIter
2964 g_variant_iter_new (GVariant *value)
2968 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2969 GVHI(iter)->value_ref = g_variant_ref (value);
2970 GVHI(iter)->magic = GVHI_MAGIC;
2972 g_variant_iter_init (iter, value);
2978 * g_variant_iter_init: (skip)
2979 * @iter: a pointer to a #GVariantIter
2980 * @value: a container #GVariant
2982 * Initialises (without allocating) a #GVariantIter. @iter may be
2983 * completely uninitialised prior to this call; its old value is
2986 * The iterator remains valid for as long as @value exists, and need not
2987 * be freed in any way.
2989 * Returns: the number of items in @value
2994 g_variant_iter_init (GVariantIter *iter,
2997 GVSI(iter)->magic = GVSI_MAGIC;
2998 GVSI(iter)->value = value;
2999 GVSI(iter)->n = g_variant_n_children (value);
3001 GVSI(iter)->loop_format = NULL;
3003 return GVSI(iter)->n;
3007 * g_variant_iter_copy:
3008 * @iter: a #GVariantIter
3010 * Creates a new heap-allocated #GVariantIter to iterate over the
3011 * container that was being iterated over by @iter. Iteration begins on
3012 * the new iterator from the current position of the old iterator but
3013 * the two copies are independent past that point.
3015 * Use g_variant_iter_free() to free the return value when you no longer
3018 * A reference is taken to the container that @iter is iterating over
3019 * and will be related only when g_variant_iter_free() is called.
3021 * Returns: (transfer full): a new heap-allocated #GVariantIter
3026 g_variant_iter_copy (GVariantIter *iter)
3030 g_return_val_if_fail (is_valid_iter (iter), 0);
3032 copy = g_variant_iter_new (GVSI(iter)->value);
3033 GVSI(copy)->i = GVSI(iter)->i;
3039 * g_variant_iter_n_children:
3040 * @iter: a #GVariantIter
3042 * Queries the number of child items in the container that we are
3043 * iterating over. This is the total number of items -- not the number
3044 * of items remaining.
3046 * This function might be useful for preallocation of arrays.
3048 * Returns: the number of children in the container
3053 g_variant_iter_n_children (GVariantIter *iter)
3055 g_return_val_if_fail (is_valid_iter (iter), 0);
3057 return GVSI(iter)->n;
3061 * g_variant_iter_free:
3062 * @iter: (transfer full): a heap-allocated #GVariantIter
3064 * Frees a heap-allocated #GVariantIter. Only call this function on
3065 * iterators that were returned by g_variant_iter_new() or
3066 * g_variant_iter_copy().
3071 g_variant_iter_free (GVariantIter *iter)
3073 g_return_if_fail (is_valid_heap_iter (iter));
3075 g_variant_unref (GVHI(iter)->value_ref);
3076 GVHI(iter)->magic = 0;
3078 g_slice_free (struct heap_iter, GVHI(iter));
3082 * g_variant_iter_next_value:
3083 * @iter: a #GVariantIter
3085 * Gets the next item in the container. If no more items remain then
3086 * %NULL is returned.
3088 * Use g_variant_unref() to drop your reference on the return value when
3089 * you no longer need it.
3091 * Here is an example for iterating with g_variant_iter_next_value():
3092 * |[<!-- language="C" -->
3093 * // recursively iterate a container
3095 * iterate_container_recursive (GVariant *container)
3097 * GVariantIter iter;
3100 * g_variant_iter_init (&iter, container);
3101 * while ((child = g_variant_iter_next_value (&iter)))
3103 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3105 * if (g_variant_is_container (child))
3106 * iterate_container_recursive (child);
3108 * g_variant_unref (child);
3113 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3118 g_variant_iter_next_value (GVariantIter *iter)
3120 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3122 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3124 g_critical ("g_variant_iter_next_value: must not be called again "
3125 "after NULL has already been returned.");
3131 if (GVSI(iter)->i < GVSI(iter)->n)
3132 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3137 /* GVariantBuilder {{{1 */
3141 * A utility type for constructing container-type #GVariant instances.
3143 * This is an opaque structure and may only be accessed using the
3144 * following functions.
3146 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3147 * access it from more than one thread.
3150 struct stack_builder
3152 GVariantBuilder *parent;
3155 /* type constraint explicitly specified by 'type'.
3156 * for tuple types, this moves along as we add more items.
3158 const GVariantType *expected_type;
3160 /* type constraint implied by previous array item.
3162 const GVariantType *prev_item_type;
3164 /* constraints on the number of children. max = -1 for unlimited. */
3168 /* dynamically-growing pointer array */
3169 GVariant **children;
3170 gsize allocated_children;
3173 /* set to '1' if all items in the container will have the same type
3174 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3176 guint uniform_item_types : 1;
3178 /* set to '1' initially and changed to '0' if an untrusted value is
3186 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3190 GVariantBuilder builder;
3196 #define GVSB(b) ((struct stack_builder *) (b))
3197 #define GVHB(b) ((struct heap_builder *) (b))
3198 #define GVSB_MAGIC ((gsize) 1033660112u)
3199 #define GVSB_MAGIC_PARTIAL ((gsize) 2942751021u)
3200 #define GVHB_MAGIC ((gsize) 3087242682u)
3201 #define is_valid_builder(b) (GVSB(b)->magic == GVSB_MAGIC)
3202 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3204 /* Just to make sure that by adding a union to GVariantBuilder, we
3205 * didn't accidentally change ABI. */
3206 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3209 ensure_valid_builder (GVariantBuilder *builder)
3211 if (builder == NULL)
3213 else if (is_valid_builder (builder))
3215 if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3217 static GVariantBuilder cleared_builder;
3219 /* Make sure that only first two fields were set and the rest is
3220 * zeroed to avoid messing up the builder that had parent
3221 * address equal to GVSB_MAGIC_PARTIAL. */
3222 if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3225 g_variant_builder_init (builder, builder->u.s.type);
3227 return is_valid_builder (builder);
3230 /* return_if_invalid_builder (b) is like
3231 * g_return_if_fail (ensure_valid_builder (b)), except that
3232 * the side effects of ensure_valid_builder are evaluated
3233 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3234 #define return_if_invalid_builder(b) G_STMT_START { \
3235 gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3236 g_return_if_fail (valid_builder); \
3239 /* return_val_if_invalid_builder (b, val) is like
3240 * g_return_val_if_fail (ensure_valid_builder (b), val), except that
3241 * the side effects of ensure_valid_builder are evaluated
3242 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3243 #define return_val_if_invalid_builder(b, val) G_STMT_START { \
3244 gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3245 g_return_val_if_fail (valid_builder, val); \
3249 * g_variant_builder_new:
3250 * @type: a container type
3252 * Allocates and initialises a new #GVariantBuilder.
3254 * You should call g_variant_builder_unref() on the return value when it
3255 * is no longer needed. The memory will not be automatically freed by
3258 * In most cases it is easier to place a #GVariantBuilder directly on
3259 * the stack of the calling function and initialise it with
3260 * g_variant_builder_init().
3262 * Returns: (transfer full): a #GVariantBuilder
3267 g_variant_builder_new (const GVariantType *type)
3269 GVariantBuilder *builder;
3271 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3272 g_variant_builder_init (builder, type);
3273 GVHB(builder)->magic = GVHB_MAGIC;
3274 GVHB(builder)->ref_count = 1;
3280 * g_variant_builder_unref:
3281 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3283 * Decreases the reference count on @builder.
3285 * In the event that there are no more references, releases all memory
3286 * associated with the #GVariantBuilder.
3288 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3289 * things will happen.
3294 g_variant_builder_unref (GVariantBuilder *builder)
3296 g_return_if_fail (is_valid_heap_builder (builder));
3298 if (--GVHB(builder)->ref_count)
3301 g_variant_builder_clear (builder);
3302 GVHB(builder)->magic = 0;
3304 g_slice_free (struct heap_builder, GVHB(builder));
3308 * g_variant_builder_ref:
3309 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3311 * Increases the reference count on @builder.
3313 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3314 * things will happen.
3316 * Returns: (transfer full): a new reference to @builder
3321 g_variant_builder_ref (GVariantBuilder *builder)
3323 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3325 GVHB(builder)->ref_count++;
3331 * g_variant_builder_clear: (skip)
3332 * @builder: a #GVariantBuilder
3334 * Releases all memory associated with a #GVariantBuilder without
3335 * freeing the #GVariantBuilder structure itself.
3337 * It typically only makes sense to do this on a stack-allocated
3338 * #GVariantBuilder if you want to abort building the value part-way
3339 * through. This function need not be called if you call
3340 * g_variant_builder_end() and it also doesn't need to be called on
3341 * builders allocated with g_variant_builder_new() (see
3342 * g_variant_builder_unref() for that).
3344 * This function leaves the #GVariantBuilder structure set to all-zeros.
3345 * It is valid to call this function on either an initialised
3346 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3347 * to call this function on uninitialised memory.
3352 g_variant_builder_clear (GVariantBuilder *builder)
3356 if (GVSB(builder)->magic == 0)
3357 /* all-zeros or partial case */
3360 return_if_invalid_builder (builder);
3362 g_variant_type_free (GVSB(builder)->type);
3364 for (i = 0; i < GVSB(builder)->offset; i++)
3365 g_variant_unref (GVSB(builder)->children[i]);
3367 g_free (GVSB(builder)->children);
3369 if (GVSB(builder)->parent)
3371 g_variant_builder_clear (GVSB(builder)->parent);
3372 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3375 memset (builder, 0, sizeof (GVariantBuilder));
3379 * g_variant_builder_init: (skip)
3380 * @builder: a #GVariantBuilder
3381 * @type: a container type
3383 * Initialises a #GVariantBuilder structure.
3385 * @type must be non-%NULL. It specifies the type of container to
3386 * construct. It can be an indefinite type such as
3387 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3388 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3391 * After the builder is initialised, values are added using
3392 * g_variant_builder_add_value() or g_variant_builder_add().
3394 * After all the child values are added, g_variant_builder_end() frees
3395 * the memory associated with the builder and returns the #GVariant that
3398 * This function completely ignores the previous contents of @builder.
3399 * On one hand this means that it is valid to pass in completely
3400 * uninitialised memory. On the other hand, this means that if you are
3401 * initialising over top of an existing #GVariantBuilder you need to
3402 * first call g_variant_builder_clear() in order to avoid leaking
3405 * You must not call g_variant_builder_ref() or
3406 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3407 * with this function. If you ever pass a reference to a
3408 * #GVariantBuilder outside of the control of your own code then you
3409 * should assume that the person receiving that reference may try to use
3410 * reference counting; you should use g_variant_builder_new() instead of
3416 g_variant_builder_init (GVariantBuilder *builder,
3417 const GVariantType *type)
3419 g_return_if_fail (type != NULL);
3420 g_return_if_fail (g_variant_type_is_container (type));
3422 memset (builder, 0, sizeof (GVariantBuilder));
3424 GVSB(builder)->type = g_variant_type_copy (type);
3425 GVSB(builder)->magic = GVSB_MAGIC;
3426 GVSB(builder)->trusted = TRUE;
3428 switch (*(const gchar *) type)
3430 case G_VARIANT_CLASS_VARIANT:
3431 GVSB(builder)->uniform_item_types = TRUE;
3432 GVSB(builder)->allocated_children = 1;
3433 GVSB(builder)->expected_type = NULL;
3434 GVSB(builder)->min_items = 1;
3435 GVSB(builder)->max_items = 1;
3438 case G_VARIANT_CLASS_ARRAY:
3439 GVSB(builder)->uniform_item_types = TRUE;
3440 GVSB(builder)->allocated_children = 8;
3441 GVSB(builder)->expected_type =
3442 g_variant_type_element (GVSB(builder)->type);
3443 GVSB(builder)->min_items = 0;
3444 GVSB(builder)->max_items = -1;
3447 case G_VARIANT_CLASS_MAYBE:
3448 GVSB(builder)->uniform_item_types = TRUE;
3449 GVSB(builder)->allocated_children = 1;
3450 GVSB(builder)->expected_type =
3451 g_variant_type_element (GVSB(builder)->type);
3452 GVSB(builder)->min_items = 0;
3453 GVSB(builder)->max_items = 1;
3456 case G_VARIANT_CLASS_DICT_ENTRY:
3457 GVSB(builder)->uniform_item_types = FALSE;
3458 GVSB(builder)->allocated_children = 2;
3459 GVSB(builder)->expected_type =
3460 g_variant_type_key (GVSB(builder)->type);
3461 GVSB(builder)->min_items = 2;
3462 GVSB(builder)->max_items = 2;
3465 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3466 GVSB(builder)->uniform_item_types = FALSE;
3467 GVSB(builder)->allocated_children = 8;
3468 GVSB(builder)->expected_type = NULL;
3469 GVSB(builder)->min_items = 0;
3470 GVSB(builder)->max_items = -1;
3473 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3474 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3475 GVSB(builder)->expected_type =
3476 g_variant_type_first (GVSB(builder)->type);
3477 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3478 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3479 GVSB(builder)->uniform_item_types = FALSE;
3483 g_assert_not_reached ();
3486 #ifdef G_ANALYZER_ANALYZING
3487 /* Static analysers can’t couple the code in g_variant_builder_init() to the
3488 * code in g_variant_builder_end() by GVariantType, so end up assuming that
3489 * @offset and @children mismatch and that uninitialised memory is accessed
3490 * from @children. At runtime, this is caught by the preconditions at the top
3491 * of g_variant_builder_end(). Help the analyser by zero-initialising the
3492 * memory to avoid a false positive. */
3493 GVSB(builder)->children = g_new0 (GVariant *,
3494 GVSB(builder)->allocated_children);
3496 GVSB(builder)->children = g_new (GVariant *,
3497 GVSB(builder)->allocated_children);
3502 g_variant_builder_make_room (struct stack_builder *builder)
3504 if (builder->offset == builder->allocated_children)
3506 builder->allocated_children *= 2;
3507 builder->children = g_renew (GVariant *, builder->children,
3508 builder->allocated_children);
3513 * g_variant_builder_add_value:
3514 * @builder: a #GVariantBuilder
3515 * @value: a #GVariant
3517 * Adds @value to @builder.
3519 * It is an error to call this function in any way that would create an
3520 * inconsistent value to be constructed. Some examples of this are
3521 * putting different types of items into an array, putting the wrong
3522 * types or number of items in a tuple, putting more than one value into
3525 * If @value is a floating reference (see g_variant_ref_sink()),
3526 * the @builder instance takes ownership of @value.
3531 g_variant_builder_add_value (GVariantBuilder *builder,
3534 return_if_invalid_builder (builder);
3535 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3536 g_return_if_fail (!GVSB(builder)->expected_type ||
3537 g_variant_is_of_type (value,
3538 GVSB(builder)->expected_type));
3539 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3540 g_variant_is_of_type (value,
3541 GVSB(builder)->prev_item_type));
3543 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3545 if (!GVSB(builder)->uniform_item_types)
3547 /* advance our expected type pointers */
3548 if (GVSB(builder)->expected_type)
3549 GVSB(builder)->expected_type =
3550 g_variant_type_next (GVSB(builder)->expected_type);
3552 if (GVSB(builder)->prev_item_type)
3553 GVSB(builder)->prev_item_type =
3554 g_variant_type_next (GVSB(builder)->prev_item_type);
3557 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3559 g_variant_builder_make_room (GVSB(builder));
3561 GVSB(builder)->children[GVSB(builder)->offset++] =
3562 g_variant_ref_sink (value);
3566 * g_variant_builder_open:
3567 * @builder: a #GVariantBuilder
3568 * @type: the #GVariantType of the container
3570 * Opens a subcontainer inside the given @builder. When done adding
3571 * items to the subcontainer, g_variant_builder_close() must be called. @type
3572 * is the type of the container: so to build a tuple of several values, @type
3573 * must include the tuple itself.
3575 * It is an error to call this function in any way that would cause an
3576 * inconsistent value to be constructed (ie: adding too many values or
3577 * a value of an incorrect type).
3579 * Example of building a nested variant:
3580 * |[<!-- language="C" -->
3581 * GVariantBuilder builder;
3582 * guint32 some_number = get_number ();
3583 * g_autoptr (GHashTable) some_dict = get_dict ();
3584 * GHashTableIter iter;
3586 * const GVariant *value;
3587 * g_autoptr (GVariant) output = NULL;
3589 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3590 * g_variant_builder_add (&builder, "u", some_number);
3591 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3593 * g_hash_table_iter_init (&iter, some_dict);
3594 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3596 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3597 * g_variant_builder_add (&builder, "s", key);
3598 * g_variant_builder_add (&builder, "v", value);
3599 * g_variant_builder_close (&builder);
3602 * g_variant_builder_close (&builder);
3604 * output = g_variant_builder_end (&builder);
3610 g_variant_builder_open (GVariantBuilder *builder,
3611 const GVariantType *type)
3613 GVariantBuilder *parent;
3615 return_if_invalid_builder (builder);
3616 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3617 g_return_if_fail (!GVSB(builder)->expected_type ||
3618 g_variant_type_is_subtype_of (type,
3619 GVSB(builder)->expected_type));
3620 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3621 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3624 parent = g_slice_dup (GVariantBuilder, builder);
3625 g_variant_builder_init (builder, type);
3626 GVSB(builder)->parent = parent;
3628 /* push the prev_item_type down into the subcontainer */
3629 if (GVSB(parent)->prev_item_type)
3631 if (!GVSB(builder)->uniform_item_types)
3632 /* tuples and dict entries */
3633 GVSB(builder)->prev_item_type =
3634 g_variant_type_first (GVSB(parent)->prev_item_type);
3636 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3637 /* maybes and arrays */
3638 GVSB(builder)->prev_item_type =
3639 g_variant_type_element (GVSB(parent)->prev_item_type);
3644 * g_variant_builder_close:
3645 * @builder: a #GVariantBuilder
3647 * Closes the subcontainer inside the given @builder that was opened by
3648 * the most recent call to g_variant_builder_open().
3650 * It is an error to call this function in any way that would create an
3651 * inconsistent value to be constructed (ie: too few values added to the
3657 g_variant_builder_close (GVariantBuilder *builder)
3659 GVariantBuilder *parent;
3661 return_if_invalid_builder (builder);
3662 g_return_if_fail (GVSB(builder)->parent != NULL);
3664 parent = GVSB(builder)->parent;
3665 GVSB(builder)->parent = NULL;
3667 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3670 g_slice_free (GVariantBuilder, parent);
3674 * g_variant_make_maybe_type:
3675 * @element: a #GVariant
3677 * Return the type of a maybe containing @element.
3679 static GVariantType *
3680 g_variant_make_maybe_type (GVariant *element)
3682 return g_variant_type_new_maybe (g_variant_get_type (element));
3686 * g_variant_make_array_type:
3687 * @element: a #GVariant
3689 * Return the type of an array containing @element.
3691 static GVariantType *
3692 g_variant_make_array_type (GVariant *element)
3694 return g_variant_type_new_array (g_variant_get_type (element));
3698 * g_variant_builder_end:
3699 * @builder: a #GVariantBuilder
3701 * Ends the builder process and returns the constructed value.
3703 * It is not permissible to use @builder in any way after this call
3704 * except for reference counting operations (in the case of a
3705 * heap-allocated #GVariantBuilder) or by reinitialising it with
3706 * g_variant_builder_init() (in the case of stack-allocated). This
3707 * means that for the stack-allocated builders there is no need to
3708 * call g_variant_builder_clear() after the call to
3709 * g_variant_builder_end().
3711 * It is an error to call this function in any way that would create an
3712 * inconsistent value to be constructed (ie: insufficient number of
3713 * items added to a container with a specific number of children
3714 * required). It is also an error to call this function if the builder
3715 * was created with an indefinite array or maybe type and no children
3716 * have been added; in this case it is impossible to infer the type of
3719 * Returns: (transfer none): a new, floating, #GVariant
3724 g_variant_builder_end (GVariantBuilder *builder)
3726 GVariantType *my_type;
3729 return_val_if_invalid_builder (builder, NULL);
3730 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3732 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3733 GVSB(builder)->prev_item_type != NULL ||
3734 g_variant_type_is_definite (GVSB(builder)->type),
3737 if (g_variant_type_is_definite (GVSB(builder)->type))
3738 my_type = g_variant_type_copy (GVSB(builder)->type);
3740 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3741 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3743 else if (g_variant_type_is_array (GVSB(builder)->type))
3744 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3746 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3747 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3748 GVSB(builder)->offset);
3750 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3751 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3752 GVSB(builder)->children[1]);
3754 g_assert_not_reached ();
3756 value = g_variant_new_from_children (my_type,
3757 g_renew (GVariant *,
3758 GVSB(builder)->children,
3759 GVSB(builder)->offset),
3760 GVSB(builder)->offset,
3761 GVSB(builder)->trusted);
3762 GVSB(builder)->children = NULL;
3763 GVSB(builder)->offset = 0;
3765 g_variant_builder_clear (builder);
3766 g_variant_type_free (my_type);
3771 /* GVariantDict {{{1 */
3776 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3778 * It can be used for doing a sequence of dictionary lookups in an
3779 * efficient way on an existing #GVariant dictionary or it can be used
3780 * to construct new dictionaries with a hashtable-like interface. It
3781 * can also be used for taking existing dictionaries and modifying them
3782 * in order to create new ones.
3784 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3787 * It is possible to use #GVariantDict allocated on the stack or on the
3788 * heap. When using a stack-allocated #GVariantDict, you begin with a
3789 * call to g_variant_dict_init() and free the resources with a call to
3790 * g_variant_dict_clear().
3792 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3793 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3794 * and g_variant_dict_unref().
3796 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3797 * dictionary-type #GVariant. When used with stack-allocated instances,
3798 * this also implicitly frees all associated memory, but for
3799 * heap-allocated instances, you must still call g_variant_dict_unref()
3802 * You will typically want to use a heap-allocated #GVariantDict when
3803 * you expose it as part of an API. For most other uses, the
3804 * stack-allocated form will be more convenient.
3806 * Consider the following two examples that do the same thing in each
3807 * style: take an existing dictionary and look up the "count" uint32
3808 * key, adding 1 to it if it is found, or returning an error if the
3809 * key is not found. Each returns the new dictionary as a floating
3812 * ## Using a stack-allocated GVariantDict
3814 * |[<!-- language="C" -->
3816 * add_to_count (GVariant *orig,
3819 * GVariantDict dict;
3822 * g_variant_dict_init (&dict, orig);
3823 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3825 * g_set_error (...);
3826 * g_variant_dict_clear (&dict);
3830 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3832 * return g_variant_dict_end (&dict);
3836 * ## Using heap-allocated GVariantDict
3838 * |[<!-- language="C" -->
3840 * add_to_count (GVariant *orig,
3843 * GVariantDict *dict;
3847 * dict = g_variant_dict_new (orig);
3849 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3851 * g_variant_dict_insert (dict, "count", "u", count + 1);
3852 * result = g_variant_dict_end (dict);
3856 * g_set_error (...);
3860 * g_variant_dict_unref (dict);
3874 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3878 struct stack_dict dict;
3883 #define GVSD(d) ((struct stack_dict *) (d))
3884 #define GVHD(d) ((struct heap_dict *) (d))
3885 #define GVSD_MAGIC ((gsize) 2579507750u)
3886 #define GVSD_MAGIC_PARTIAL ((gsize) 3488698669u)
3887 #define GVHD_MAGIC ((gsize) 2450270775u)
3888 #define is_valid_dict(d) (GVSD(d)->magic == GVSD_MAGIC)
3889 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3891 /* Just to make sure that by adding a union to GVariantDict, we didn't
3892 * accidentally change ABI. */
3893 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3896 ensure_valid_dict (GVariantDict *dict)
3900 else if (is_valid_dict (dict))
3902 if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3904 static GVariantDict cleared_dict;
3906 /* Make sure that only first two fields were set and the rest is
3907 * zeroed to avoid messing up the builder that had parent
3908 * address equal to GVSB_MAGIC_PARTIAL. */
3909 if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3912 g_variant_dict_init (dict, dict->u.s.asv);
3914 return is_valid_dict (dict);
3917 /* return_if_invalid_dict (d) is like
3918 * g_return_if_fail (ensure_valid_dict (d)), except that
3919 * the side effects of ensure_valid_dict are evaluated
3920 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3921 #define return_if_invalid_dict(d) G_STMT_START { \
3922 gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d); \
3923 g_return_if_fail (valid_dict); \
3926 /* return_val_if_invalid_dict (d, val) is like
3927 * g_return_val_if_fail (ensure_valid_dict (d), val), except that
3928 * the side effects of ensure_valid_dict are evaluated
3929 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3930 #define return_val_if_invalid_dict(d, val) G_STMT_START { \
3931 gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d); \
3932 g_return_val_if_fail (valid_dict, val); \
3936 * g_variant_dict_new:
3937 * @from_asv: (nullable): the #GVariant with which to initialise the
3940 * Allocates and initialises a new #GVariantDict.
3942 * You should call g_variant_dict_unref() on the return value when it
3943 * is no longer needed. The memory will not be automatically freed by
3946 * In some cases it may be easier to place a #GVariantDict directly on
3947 * the stack of the calling function and initialise it with
3948 * g_variant_dict_init(). This is particularly useful when you are
3949 * using #GVariantDict to construct a #GVariant.
3951 * Returns: (transfer full): a #GVariantDict
3956 g_variant_dict_new (GVariant *from_asv)
3960 dict = g_slice_alloc (sizeof (struct heap_dict));
3961 g_variant_dict_init (dict, from_asv);
3962 GVHD(dict)->magic = GVHD_MAGIC;
3963 GVHD(dict)->ref_count = 1;
3969 * g_variant_dict_init: (skip)
3970 * @dict: a #GVariantDict
3971 * @from_asv: (nullable): the initial value for @dict
3973 * Initialises a #GVariantDict structure.
3975 * If @from_asv is given, it is used to initialise the dictionary.
3977 * This function completely ignores the previous contents of @dict. On
3978 * one hand this means that it is valid to pass in completely
3979 * uninitialised memory. On the other hand, this means that if you are
3980 * initialising over top of an existing #GVariantDict you need to first
3981 * call g_variant_dict_clear() in order to avoid leaking memory.
3983 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3984 * #GVariantDict that was initialised with this function. If you ever
3985 * pass a reference to a #GVariantDict outside of the control of your
3986 * own code then you should assume that the person receiving that
3987 * reference may try to use reference counting; you should use
3988 * g_variant_dict_new() instead of this function.
3993 g_variant_dict_init (GVariantDict *dict,
4000 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
4001 GVSD(dict)->magic = GVSD_MAGIC;
4005 g_variant_iter_init (&iter, from_asv);
4006 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4007 g_hash_table_insert (GVSD(dict)->values, key, value);
4012 * g_variant_dict_lookup:
4013 * @dict: a #GVariantDict
4014 * @key: the key to look up in the dictionary
4015 * @format_string: a GVariant format string
4016 * @...: the arguments to unpack the value into
4018 * Looks up a value in a #GVariantDict.
4020 * This function is a wrapper around g_variant_dict_lookup_value() and
4021 * g_variant_get(). In the case that %NULL would have been returned,
4022 * this function returns %FALSE. Otherwise, it unpacks the returned
4023 * value and returns %TRUE.
4025 * @format_string determines the C types that are used for unpacking the
4026 * values and also determines if the values are copied or borrowed, see the
4027 * section on [GVariant format strings][gvariant-format-strings-pointers].
4029 * Returns: %TRUE if a value was unpacked
4034 g_variant_dict_lookup (GVariantDict *dict,
4036 const gchar *format_string,
4042 return_val_if_invalid_dict (dict, FALSE);
4043 g_return_val_if_fail (key != NULL, FALSE);
4044 g_return_val_if_fail (format_string != NULL, FALSE);
4046 value = g_hash_table_lookup (GVSD(dict)->values, key);
4048 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
4051 va_start (ap, format_string);
4052 g_variant_get_va (value, format_string, NULL, &ap);
4059 * g_variant_dict_lookup_value:
4060 * @dict: a #GVariantDict
4061 * @key: the key to look up in the dictionary
4062 * @expected_type: (nullable): a #GVariantType, or %NULL
4064 * Looks up a value in a #GVariantDict.
4066 * If @key is not found in @dictionary, %NULL is returned.
4068 * The @expected_type string specifies what type of value is expected.
4069 * If the value associated with @key has a different type then %NULL is
4072 * If the key is found and the value has the correct type, it is
4073 * returned. If @expected_type was specified then any non-%NULL return
4074 * value will have this type.
4076 * Returns: (transfer full) (nullable): the value of the dictionary key, or %NULL
4081 g_variant_dict_lookup_value (GVariantDict *dict,
4083 const GVariantType *expected_type)
4087 return_val_if_invalid_dict (dict, NULL);
4088 g_return_val_if_fail (key != NULL, NULL);
4090 result = g_hash_table_lookup (GVSD(dict)->values, key);
4092 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4093 return g_variant_ref (result);
4099 * g_variant_dict_contains:
4100 * @dict: a #GVariantDict
4101 * @key: the key to look up in the dictionary
4103 * Checks if @key exists in @dict.
4105 * Returns: %TRUE if @key is in @dict
4110 g_variant_dict_contains (GVariantDict *dict,
4113 return_val_if_invalid_dict (dict, FALSE);
4114 g_return_val_if_fail (key != NULL, FALSE);
4116 return g_hash_table_contains (GVSD(dict)->values, key);
4120 * g_variant_dict_insert:
4121 * @dict: a #GVariantDict
4122 * @key: the key to insert a value for
4123 * @format_string: a #GVariant varargs format string
4124 * @...: arguments, as per @format_string
4126 * Inserts a value into a #GVariantDict.
4128 * This call is a convenience wrapper that is exactly equivalent to
4129 * calling g_variant_new() followed by g_variant_dict_insert_value().
4134 g_variant_dict_insert (GVariantDict *dict,
4136 const gchar *format_string,
4141 return_if_invalid_dict (dict);
4142 g_return_if_fail (key != NULL);
4143 g_return_if_fail (format_string != NULL);
4145 va_start (ap, format_string);
4146 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4151 * g_variant_dict_insert_value:
4152 * @dict: a #GVariantDict
4153 * @key: the key to insert a value for
4154 * @value: the value to insert
4156 * Inserts (or replaces) a key in a #GVariantDict.
4158 * @value is consumed if it is floating.
4163 g_variant_dict_insert_value (GVariantDict *dict,
4167 return_if_invalid_dict (dict);
4168 g_return_if_fail (key != NULL);
4169 g_return_if_fail (value != NULL);
4171 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4175 * g_variant_dict_remove:
4176 * @dict: a #GVariantDict
4177 * @key: the key to remove
4179 * Removes a key and its associated value from a #GVariantDict.
4181 * Returns: %TRUE if the key was found and removed
4186 g_variant_dict_remove (GVariantDict *dict,
4189 return_val_if_invalid_dict (dict, FALSE);
4190 g_return_val_if_fail (key != NULL, FALSE);
4192 return g_hash_table_remove (GVSD(dict)->values, key);
4196 * g_variant_dict_clear:
4197 * @dict: a #GVariantDict
4199 * Releases all memory associated with a #GVariantDict without freeing
4200 * the #GVariantDict structure itself.
4202 * It typically only makes sense to do this on a stack-allocated
4203 * #GVariantDict if you want to abort building the value part-way
4204 * through. This function need not be called if you call
4205 * g_variant_dict_end() and it also doesn't need to be called on dicts
4206 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4209 * It is valid to call this function on either an initialised
4210 * #GVariantDict or one that was previously cleared by an earlier call
4211 * to g_variant_dict_clear() but it is not valid to call this function
4212 * on uninitialised memory.
4217 g_variant_dict_clear (GVariantDict *dict)
4219 if (GVSD(dict)->magic == 0)
4220 /* all-zeros case */
4223 return_if_invalid_dict (dict);
4225 g_hash_table_unref (GVSD(dict)->values);
4226 GVSD(dict)->values = NULL;
4228 GVSD(dict)->magic = 0;
4232 * g_variant_dict_end:
4233 * @dict: a #GVariantDict
4235 * Returns the current value of @dict as a #GVariant of type
4236 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4238 * It is not permissible to use @dict in any way after this call except
4239 * for reference counting operations (in the case of a heap-allocated
4240 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4241 * the case of stack-allocated).
4243 * Returns: (transfer none): a new, floating, #GVariant
4248 g_variant_dict_end (GVariantDict *dict)
4250 GVariantBuilder builder;
4251 GHashTableIter iter;
4252 gpointer key, value;
4254 return_val_if_invalid_dict (dict, NULL);
4256 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4258 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4259 while (g_hash_table_iter_next (&iter, &key, &value))
4260 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4262 g_variant_dict_clear (dict);
4264 return g_variant_builder_end (&builder);
4268 * g_variant_dict_ref:
4269 * @dict: a heap-allocated #GVariantDict
4271 * Increases the reference count on @dict.
4273 * Don't call this on stack-allocated #GVariantDict instances or bad
4274 * things will happen.
4276 * Returns: (transfer full): a new reference to @dict
4281 g_variant_dict_ref (GVariantDict *dict)
4283 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4285 GVHD(dict)->ref_count++;
4291 * g_variant_dict_unref:
4292 * @dict: (transfer full): a heap-allocated #GVariantDict
4294 * Decreases the reference count on @dict.
4296 * In the event that there are no more references, releases all memory
4297 * associated with the #GVariantDict.
4299 * Don't call this on stack-allocated #GVariantDict instances or bad
4300 * things will happen.
4305 g_variant_dict_unref (GVariantDict *dict)
4307 g_return_if_fail (is_valid_heap_dict (dict));
4309 if (--GVHD(dict)->ref_count == 0)
4311 g_variant_dict_clear (dict);
4312 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4317 /* Format strings {{{1 */
4319 * g_variant_format_string_scan:
4320 * @string: a string that may be prefixed with a format string
4321 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4323 * @endptr: (nullable) (default NULL): location to store the end pointer,
4326 * Checks the string pointed to by @string for starting with a properly
4327 * formed #GVariant varargs format string. If no valid format string is
4328 * found then %FALSE is returned.
4330 * If @string does start with a valid format string then %TRUE is
4331 * returned. If @endptr is non-%NULL then it is updated to point to the
4332 * first character after the format string.
4334 * If @limit is non-%NULL then @limit (and any character after it) will
4335 * not be accessed and the effect is otherwise equivalent to if the
4336 * character at @limit were nul.
4338 * See the section on [GVariant format strings][gvariant-format-strings].
4340 * Returns: %TRUE if there was a valid format string
4345 g_variant_format_string_scan (const gchar *string,
4347 const gchar **endptr)
4349 #define next_char() (string == limit ? '\0' : *(string++))
4350 #define peek_char() (string == limit ? '\0' : *string)
4353 switch (next_char())
4355 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4356 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4357 case 'g': case 'v': case '*': case '?': case 'r':
4361 return g_variant_format_string_scan (string, limit, endptr);
4365 return g_variant_type_string_scan (string, limit, endptr);
4368 while (peek_char() != ')')
4369 if (!g_variant_format_string_scan (string, limit, &string))
4372 next_char(); /* consume ')' */
4382 if (c != 's' && c != 'o' && c != 'g')
4390 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4391 * The terminating null character is considered to be
4392 * part of the string.
4394 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4398 if (!g_variant_format_string_scan (string, limit, &string))
4401 if (next_char() != '}')
4407 if ((c = next_char()) == 'a')
4409 if ((c = next_char()) == '&')
4411 if ((c = next_char()) == 'a')
4413 if ((c = next_char()) == 'y')
4414 break; /* '^a&ay' */
4417 else if (c == 's' || c == 'o')
4418 break; /* '^a&s', '^a&o' */
4423 if ((c = next_char()) == 'y')
4427 else if (c == 's' || c == 'o')
4428 break; /* '^as', '^ao' */
4435 if ((c = next_char()) == 'a')
4437 if ((c = next_char()) == 'y')
4447 if (c != 's' && c != 'o' && c != 'g')
4466 * g_variant_check_format_string:
4467 * @value: a #GVariant
4468 * @format_string: a valid #GVariant format string
4469 * @copy_only: %TRUE to ensure the format string makes deep copies
4471 * Checks if calling g_variant_get() with @format_string on @value would
4472 * be valid from a type-compatibility standpoint. @format_string is
4473 * assumed to be a valid format string (from a syntactic standpoint).
4475 * If @copy_only is %TRUE then this function additionally checks that it
4476 * would be safe to call g_variant_unref() on @value immediately after
4477 * the call to g_variant_get() without invalidating the result. This is
4478 * only possible if deep copies are made (ie: there are no pointers to
4479 * the data inside of the soon-to-be-freed #GVariant instance). If this
4480 * check fails then a g_critical() is printed and %FALSE is returned.
4482 * This function is meant to be used by functions that wish to provide
4483 * varargs accessors to #GVariant values of uncertain values (eg:
4484 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4486 * Returns: %TRUE if @format_string is safe to use
4491 g_variant_check_format_string (GVariant *value,
4492 const gchar *format_string,
4495 const gchar *original_format = format_string;
4496 const gchar *type_string;
4498 /* Interesting factoid: assuming a format string is valid, it can be
4499 * converted to a type string by removing all '@' '&' and '^'
4502 * Instead of doing that, we can just skip those characters when
4503 * comparing it to the type string of @value.
4505 * For the copy-only case we can just drop the '&' from the list of
4506 * characters to skip over. A '&' will never appear in a type string
4507 * so we know that it won't be possible to return %TRUE if it is in a
4510 type_string = g_variant_get_type_string (value);
4512 while (*type_string || *format_string)
4514 gchar format = *format_string++;
4519 if G_UNLIKELY (copy_only)
4521 /* for the love of all that is good, please don't mark this string for translation... */
4522 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4523 "interface to validate the passed format string for type safety. The passed format "
4524 "(%s) contains a '&' character which would result in a pointer being returned to the "
4525 "data inside of a GVariant instance that may no longer exist by the time the function "
4526 "returns. Modify your code to use a format string without '&'.", original_format);
4533 /* ignore these 2 (or 3) */
4537 /* attempt to consume one of 'bynqiuxthdsog' */
4539 char s = *type_string++;
4541 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4547 /* ensure it's a tuple */
4548 if (*type_string != '(')
4553 /* consume a full type string for the '*' or 'r' */
4554 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4560 /* attempt to consume exactly one character equal to the format */
4561 if (format != *type_string++)
4570 * g_variant_format_string_scan_type:
4571 * @string: a string that may be prefixed with a format string
4572 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4574 * @endptr: (nullable) (default NULL): location to store the end pointer,
4577 * If @string starts with a valid format string then this function will
4578 * return the type that the format string corresponds to. Otherwise
4579 * this function returns %NULL.
4581 * Use g_variant_type_free() to free the return value when you no longer
4584 * This function is otherwise exactly like
4585 * g_variant_format_string_scan().
4587 * Returns: (nullable): a #GVariantType if there was a valid format string
4592 g_variant_format_string_scan_type (const gchar *string,
4594 const gchar **endptr)
4596 const gchar *my_end;
4603 if (!g_variant_format_string_scan (string, limit, endptr))
4606 dest = new = g_malloc (*endptr - string + 1);
4607 while (string != *endptr)
4609 if (*string != '@' && *string != '&' && *string != '^')
4615 return (GVariantType *) G_VARIANT_TYPE (new);
4619 valid_format_string (const gchar *format_string,
4623 const gchar *endptr;
4626 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4628 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4631 g_critical ("'%s' is not a valid GVariant format string",
4634 g_critical ("'%s' does not have a valid GVariant format "
4635 "string as a prefix", format_string);
4638 g_variant_type_free (type);
4643 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4648 fragment = g_strndup (format_string, endptr - format_string);
4649 typestr = g_variant_type_dup_string (type);
4651 g_critical ("the GVariant format string '%s' has a type of "
4652 "'%s' but the given value has a type of '%s'",
4653 fragment, typestr, g_variant_get_type_string (value));
4655 g_variant_type_free (type);
4662 g_variant_type_free (type);
4667 /* Variable Arguments {{{1 */
4668 /* We consider 2 main classes of format strings:
4670 * - recursive format strings
4671 * these are ones that result in recursion and the collection of
4672 * possibly more than one argument. Maybe types, tuples,
4673 * dictionary entries.
4675 * - leaf format string
4676 * these result in the collection of a single argument.
4678 * Leaf format strings are further subdivided into two categories:
4680 * - single non-null pointer ("nnp")
4681 * these either collect or return a single non-null pointer.
4684 * these collect or return something else (bool, number, etc).
4686 * Based on the above, the varargs handling code is split into 4 main parts:
4688 * - nnp handling code
4689 * - leaf handling code (which may invoke nnp code)
4690 * - generic handling code (may be recursive, may invoke leaf code)
4691 * - user-facing API (which invokes the generic code)
4693 * Each section implements some of the following functions:
4696 * collect the arguments for the format string as if
4697 * g_variant_new() had been called, but do nothing with them. used
4698 * for skipping over arguments when constructing a Nothing maybe
4702 * create a GVariant *
4705 * unpack a GVariant *
4707 * - free (nnp only):
4708 * free a previously allocated item
4712 g_variant_format_string_is_leaf (const gchar *str)
4714 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4718 g_variant_format_string_is_nnp (const gchar *str)
4720 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4721 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4722 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4725 /* Single non-null pointer ("nnp") {{{2 */
4727 g_variant_valist_free_nnp (const gchar *str,
4733 g_variant_iter_free (ptr);
4737 if (g_str_has_suffix (str, "y"))
4739 if (str[2] != 'a') /* '^a&ay', '^ay' */
4741 else if (str[1] == 'a') /* '^aay' */
4745 else if (str[2] != '&') /* '^as', '^ao' */
4747 else /* '^a&s', '^a&o' */
4761 g_variant_unref (ptr);
4768 g_assert_not_reached ();
4773 g_variant_scan_convenience (const gchar **str,
4796 g_variant_valist_new_nnp (const gchar **str,
4807 const GVariantType *type;
4810 value = g_variant_builder_end (ptr);
4811 type = g_variant_get_type (value);
4813 if G_UNLIKELY (!g_variant_type_is_array (type))
4814 g_error ("g_variant_new: expected array GVariantBuilder but "
4815 "the built value has type '%s'",
4816 g_variant_get_type_string (value));
4818 type = g_variant_type_element (type);
4820 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4822 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4823 g_error ("g_variant_new: expected GVariantBuilder array element "
4824 "type '%s' but the built value has element type '%s'",
4825 type_string, g_variant_get_type_string (value) + 1);
4826 g_free (type_string);
4829 g_variant_type_string_scan (*str, NULL, str);
4835 /* special case: NULL pointer for empty array */
4837 const GVariantType *type = (GVariantType *) *str;
4839 g_variant_type_string_scan (*str, NULL, str);
4841 if G_UNLIKELY (!g_variant_type_is_definite (type))
4842 g_error ("g_variant_new: NULL pointer given with indefinite "
4843 "array type; unable to determine which type of empty "
4844 "array to construct.");
4846 return g_variant_new_array (type, NULL, 0);
4853 value = g_variant_new_string (ptr);
4856 value = g_variant_new_string ("[Invalid UTF-8]");
4862 return g_variant_new_object_path (ptr);
4865 return g_variant_new_signature (ptr);
4873 type = g_variant_scan_convenience (str, &constant, &arrays);
4876 return g_variant_new_strv (ptr, -1);
4879 return g_variant_new_objv (ptr, -1);
4882 return g_variant_new_bytestring_array (ptr, -1);
4884 return g_variant_new_bytestring (ptr);
4888 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4890 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4891 g_error ("g_variant_new: expected GVariant of type '%s' but "
4892 "received value has type '%s'",
4893 type_string, g_variant_get_type_string (ptr));
4894 g_free (type_string);
4897 g_variant_type_string_scan (*str, NULL, str);
4905 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4906 g_error ("g_variant_new: format string '?' expects basic-typed "
4907 "GVariant, but received value has type '%s'",
4908 g_variant_get_type_string (ptr));
4913 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4914 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4915 "GVariant, but received value has type '%s'",
4916 g_variant_get_type_string (ptr));
4921 return g_variant_new_variant (ptr);
4924 g_assert_not_reached ();
4929 g_variant_valist_get_nnp (const gchar **str,
4935 g_variant_type_string_scan (*str, NULL, str);
4936 return g_variant_iter_new (value);
4940 return (gchar *) g_variant_get_string (value, NULL);
4945 return g_variant_dup_string (value, NULL);
4953 type = g_variant_scan_convenience (str, &constant, &arrays);
4958 return g_variant_get_strv (value, NULL);
4960 return g_variant_dup_strv (value, NULL);
4963 else if (type == 'o')
4966 return g_variant_get_objv (value, NULL);
4968 return g_variant_dup_objv (value, NULL);
4971 else if (arrays > 1)
4974 return g_variant_get_bytestring_array (value, NULL);
4976 return g_variant_dup_bytestring_array (value, NULL);
4982 return (gchar *) g_variant_get_bytestring (value);
4984 return g_variant_dup_bytestring (value, NULL);
4989 g_variant_type_string_scan (*str, NULL, str);
4995 return g_variant_ref (value);
4998 return g_variant_get_variant (value);
5001 g_assert_not_reached ();
5007 g_variant_valist_skip_leaf (const gchar **str,
5010 if (g_variant_format_string_is_nnp (*str))
5012 g_variant_format_string_scan (*str, NULL, str);
5013 va_arg (*app, gpointer);
5031 va_arg (*app, guint64);
5035 va_arg (*app, gdouble);
5039 g_assert_not_reached ();
5044 g_variant_valist_new_leaf (const gchar **str,
5047 if (g_variant_format_string_is_nnp (*str))
5048 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
5053 return g_variant_new_boolean (va_arg (*app, gboolean));
5056 return g_variant_new_byte (va_arg (*app, guint));
5059 return g_variant_new_int16 (va_arg (*app, gint));
5062 return g_variant_new_uint16 (va_arg (*app, guint));
5065 return g_variant_new_int32 (va_arg (*app, gint));
5068 return g_variant_new_uint32 (va_arg (*app, guint));
5071 return g_variant_new_int64 (va_arg (*app, gint64));
5074 return g_variant_new_uint64 (va_arg (*app, guint64));
5077 return g_variant_new_handle (va_arg (*app, gint));
5080 return g_variant_new_double (va_arg (*app, gdouble));
5083 g_assert_not_reached ();
5087 /* The code below assumes this */
5088 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5089 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5092 g_variant_valist_get_leaf (const gchar **str,
5097 gpointer ptr = va_arg (*app, gpointer);
5101 g_variant_format_string_scan (*str, NULL, str);
5105 if (g_variant_format_string_is_nnp (*str))
5107 gpointer *nnp = (gpointer *) ptr;
5109 if (free && *nnp != NULL)
5110 g_variant_valist_free_nnp (*str, *nnp);
5115 *nnp = g_variant_valist_get_nnp (str, value);
5117 g_variant_format_string_scan (*str, NULL, str);
5127 *(gboolean *) ptr = g_variant_get_boolean (value);
5131 *(guint8 *) ptr = g_variant_get_byte (value);
5135 *(gint16 *) ptr = g_variant_get_int16 (value);
5139 *(guint16 *) ptr = g_variant_get_uint16 (value);
5143 *(gint32 *) ptr = g_variant_get_int32 (value);
5147 *(guint32 *) ptr = g_variant_get_uint32 (value);
5151 *(gint64 *) ptr = g_variant_get_int64 (value);
5155 *(guint64 *) ptr = g_variant_get_uint64 (value);
5159 *(gint32 *) ptr = g_variant_get_handle (value);
5163 *(gdouble *) ptr = g_variant_get_double (value);
5172 *(guint8 *) ptr = 0;
5177 *(guint16 *) ptr = 0;
5184 *(guint32 *) ptr = 0;
5190 *(guint64 *) ptr = 0;
5195 g_assert_not_reached ();
5198 /* Generic (recursive) {{{2 */
5200 g_variant_valist_skip (const gchar **str,
5203 if (g_variant_format_string_is_leaf (*str))
5204 g_variant_valist_skip_leaf (str, app);
5206 else if (**str == 'm') /* maybe */
5210 if (!g_variant_format_string_is_nnp (*str))
5211 va_arg (*app, gboolean);
5213 g_variant_valist_skip (str, app);
5215 else /* tuple, dictionary entry */
5217 g_assert (**str == '(' || **str == '{');
5219 while (**str != ')' && **str != '}')
5220 g_variant_valist_skip (str, app);
5226 g_variant_valist_new (const gchar **str,
5229 if (g_variant_format_string_is_leaf (*str))
5230 return g_variant_valist_new_leaf (str, app);
5232 if (**str == 'm') /* maybe */
5234 GVariantType *type = NULL;
5235 GVariant *value = NULL;
5239 if (g_variant_format_string_is_nnp (*str))
5241 gpointer nnp = va_arg (*app, gpointer);
5244 value = g_variant_valist_new_nnp (str, nnp);
5246 type = g_variant_format_string_scan_type (*str, NULL, str);
5250 gboolean just = va_arg (*app, gboolean);
5253 value = g_variant_valist_new (str, app);
5256 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5257 g_variant_valist_skip (str, app);
5261 value = g_variant_new_maybe (type, value);
5264 g_variant_type_free (type);
5268 else /* tuple, dictionary entry */
5273 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5276 g_assert (**str == '{');
5277 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5281 while (**str != ')' && **str != '}')
5282 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5285 return g_variant_builder_end (&b);
5290 g_variant_valist_get (const gchar **str,
5295 if (g_variant_format_string_is_leaf (*str))
5296 g_variant_valist_get_leaf (str, value, free, app);
5298 else if (**str == 'm')
5303 value = g_variant_get_maybe (value);
5305 if (!g_variant_format_string_is_nnp (*str))
5307 gboolean *ptr = va_arg (*app, gboolean *);
5310 *ptr = value != NULL;
5313 g_variant_valist_get (str, value, free, app);
5316 g_variant_unref (value);
5319 else /* tuple, dictionary entry */
5323 g_assert (**str == '(' || **str == '{');
5326 while (**str != ')' && **str != '}')
5330 GVariant *child = g_variant_get_child_value (value, index++);
5331 g_variant_valist_get (str, child, free, app);
5332 g_variant_unref (child);
5335 g_variant_valist_get (str, NULL, free, app);
5341 /* User-facing API {{{2 */
5343 * g_variant_new: (skip)
5344 * @format_string: a #GVariant format string
5345 * @...: arguments, as per @format_string
5347 * Creates a new #GVariant instance.
5349 * Think of this function as an analogue to g_strdup_printf().
5351 * The type of the created instance and the arguments that are expected
5352 * by this function are determined by @format_string. See the section on
5353 * [GVariant format strings][gvariant-format-strings]. Please note that
5354 * the syntax of the format string is very likely to be extended in the
5357 * The first character of the format string must not be '*' '?' '@' or
5358 * 'r'; in essence, a new #GVariant must always be constructed by this
5359 * function (and not merely passed through it unmodified).
5361 * Note that the arguments must be of the correct width for their types
5362 * specified in @format_string. This can be achieved by casting them. See
5363 * the [GVariant varargs documentation][gvariant-varargs].
5365 * |[<!-- language="C" -->
5366 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5367 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5368 * GVariant *new_variant;
5370 * new_variant = g_variant_new ("(t^as)",
5371 * // This cast is required.
5372 * (guint64) some_flags,
5376 * Returns: a new floating #GVariant instance
5381 g_variant_new (const gchar *format_string,
5387 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5388 format_string[0] != '?' && format_string[0] != '@' &&
5389 format_string[0] != '*' && format_string[0] != 'r',
5392 va_start (ap, format_string);
5393 value = g_variant_new_va (format_string, NULL, &ap);
5400 * g_variant_new_va: (skip)
5401 * @format_string: a string that is prefixed with a format string
5402 * @endptr: (nullable) (default NULL): location to store the end pointer,
5404 * @app: a pointer to a #va_list
5406 * This function is intended to be used by libraries based on
5407 * #GVariant that want to provide g_variant_new()-like functionality
5410 * The API is more general than g_variant_new() to allow a wider range
5413 * @format_string must still point to a valid format string, but it only
5414 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5415 * non-%NULL then it is updated to point to the first character past the
5416 * end of the format string.
5418 * @app is a pointer to a #va_list. The arguments, according to
5419 * @format_string, are collected from this #va_list and the list is left
5420 * pointing to the argument following the last.
5422 * Note that the arguments in @app must be of the correct width for their
5423 * types specified in @format_string when collected into the #va_list.
5424 * See the [GVariant varargs documentation][gvariant-varargs].
5426 * These two generalisations allow mixing of multiple calls to
5427 * g_variant_new_va() and g_variant_get_va() within a single actual
5428 * varargs call by the user.
5430 * The return value will be floating if it was a newly created GVariant
5431 * instance (for example, if the format string was "(ii)"). In the case
5432 * that the format_string was '*', '?', 'r', or a format starting with
5433 * '@' then the collected #GVariant pointer will be returned unmodified,
5434 * without adding any additional references.
5436 * In order to behave correctly in all cases it is necessary for the
5437 * calling function to g_variant_ref_sink() the return result before
5438 * returning control to the user that originally provided the pointer.
5439 * At this point, the caller will have their own full reference to the
5440 * result. This can also be done by adding the result to a container,
5441 * or by passing it to another g_variant_new() call.
5443 * Returns: a new, usually floating, #GVariant
5448 g_variant_new_va (const gchar *format_string,
5449 const gchar **endptr,
5454 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5456 g_return_val_if_fail (app != NULL, NULL);
5458 value = g_variant_valist_new (&format_string, app);
5461 *endptr = format_string;
5467 * g_variant_get: (skip)
5468 * @value: a #GVariant instance
5469 * @format_string: a #GVariant format string
5470 * @...: arguments, as per @format_string
5472 * Deconstructs a #GVariant instance.
5474 * Think of this function as an analogue to scanf().
5476 * The arguments that are expected by this function are entirely
5477 * determined by @format_string. @format_string also restricts the
5478 * permissible types of @value. It is an error to give a value with
5479 * an incompatible type. See the section on
5480 * [GVariant format strings][gvariant-format-strings].
5481 * Please note that the syntax of the format string is very likely to be
5482 * extended in the future.
5484 * @format_string determines the C types that are used for unpacking
5485 * the values and also determines if the values are copied or borrowed,
5486 * see the section on
5487 * [GVariant format strings][gvariant-format-strings-pointers].
5492 g_variant_get (GVariant *value,
5493 const gchar *format_string,
5498 g_return_if_fail (value != NULL);
5499 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5501 /* if any direct-pointer-access formats are in use, flatten first */
5502 if (strchr (format_string, '&'))
5503 g_variant_get_data (value);
5505 va_start (ap, format_string);
5506 g_variant_get_va (value, format_string, NULL, &ap);
5511 * g_variant_get_va: (skip)
5512 * @value: a #GVariant
5513 * @format_string: a string that is prefixed with a format string
5514 * @endptr: (nullable) (default NULL): location to store the end pointer,
5516 * @app: a pointer to a #va_list
5518 * This function is intended to be used by libraries based on #GVariant
5519 * that want to provide g_variant_get()-like functionality to their
5522 * The API is more general than g_variant_get() to allow a wider range
5525 * @format_string must still point to a valid format string, but it only
5526 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5527 * non-%NULL then it is updated to point to the first character past the
5528 * end of the format string.
5530 * @app is a pointer to a #va_list. The arguments, according to
5531 * @format_string, are collected from this #va_list and the list is left
5532 * pointing to the argument following the last.
5534 * These two generalisations allow mixing of multiple calls to
5535 * g_variant_new_va() and g_variant_get_va() within a single actual
5536 * varargs call by the user.
5538 * @format_string determines the C types that are used for unpacking
5539 * the values and also determines if the values are copied or borrowed,
5540 * see the section on
5541 * [GVariant format strings][gvariant-format-strings-pointers].
5546 g_variant_get_va (GVariant *value,
5547 const gchar *format_string,
5548 const gchar **endptr,
5551 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5552 g_return_if_fail (value != NULL);
5553 g_return_if_fail (app != NULL);
5555 /* if any direct-pointer-access formats are in use, flatten first */
5556 if (strchr (format_string, '&'))
5557 g_variant_get_data (value);
5559 g_variant_valist_get (&format_string, value, FALSE, app);
5562 *endptr = format_string;
5565 /* Varargs-enabled Utility Functions {{{1 */
5568 * g_variant_builder_add: (skip)
5569 * @builder: a #GVariantBuilder
5570 * @format_string: a #GVariant varargs format string
5571 * @...: arguments, as per @format_string
5573 * Adds to a #GVariantBuilder.
5575 * This call is a convenience wrapper that is exactly equivalent to
5576 * calling g_variant_new() followed by g_variant_builder_add_value().
5578 * Note that the arguments must be of the correct width for their types
5579 * specified in @format_string. This can be achieved by casting them. See
5580 * the [GVariant varargs documentation][gvariant-varargs].
5582 * This function might be used as follows:
5584 * |[<!-- language="C" -->
5586 * make_pointless_dictionary (void)
5588 * GVariantBuilder builder;
5591 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5592 * for (i = 0; i < 16; i++)
5596 * sprintf (buf, "%d", i);
5597 * g_variant_builder_add (&builder, "{is}", i, buf);
5600 * return g_variant_builder_end (&builder);
5607 g_variant_builder_add (GVariantBuilder *builder,
5608 const gchar *format_string,
5614 va_start (ap, format_string);
5615 variant = g_variant_new_va (format_string, NULL, &ap);
5618 g_variant_builder_add_value (builder, variant);
5622 * g_variant_get_child: (skip)
5623 * @value: a container #GVariant
5624 * @index_: the index of the child to deconstruct
5625 * @format_string: a #GVariant format string
5626 * @...: arguments, as per @format_string
5628 * Reads a child item out of a container #GVariant instance and
5629 * deconstructs it according to @format_string. This call is
5630 * essentially a combination of g_variant_get_child_value() and
5633 * @format_string determines the C types that are used for unpacking
5634 * the values and also determines if the values are copied or borrowed,
5635 * see the section on
5636 * [GVariant format strings][gvariant-format-strings-pointers].
5641 g_variant_get_child (GVariant *value,
5643 const gchar *format_string,
5649 /* if any direct-pointer-access formats are in use, flatten first */
5650 if (strchr (format_string, '&'))
5651 g_variant_get_data (value);
5653 child = g_variant_get_child_value (value, index_);
5654 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5656 va_start (ap, format_string);
5657 g_variant_get_va (child, format_string, NULL, &ap);
5660 g_variant_unref (child);
5664 * g_variant_iter_next: (skip)
5665 * @iter: a #GVariantIter
5666 * @format_string: a GVariant format string
5667 * @...: the arguments to unpack the value into
5669 * Gets the next item in the container and unpacks it into the variable
5670 * argument list according to @format_string, returning %TRUE.
5672 * If no more items remain then %FALSE is returned.
5674 * All of the pointers given on the variable arguments list of this
5675 * function are assumed to point at uninitialised memory. It is the
5676 * responsibility of the caller to free all of the values returned by
5677 * the unpacking process.
5679 * Here is an example for memory management with g_variant_iter_next():
5680 * |[<!-- language="C" -->
5681 * // Iterates a dictionary of type 'a{sv}'
5683 * iterate_dictionary (GVariant *dictionary)
5685 * GVariantIter iter;
5689 * g_variant_iter_init (&iter, dictionary);
5690 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5692 * g_print ("Item '%s' has type '%s'\n", key,
5693 * g_variant_get_type_string (value));
5695 * // must free data for ourselves
5696 * g_variant_unref (value);
5702 * For a solution that is likely to be more convenient to C programmers
5703 * when dealing with loops, see g_variant_iter_loop().
5705 * @format_string determines the C types that are used for unpacking
5706 * the values and also determines if the values are copied or borrowed.
5708 * See the section on
5709 * [GVariant format strings][gvariant-format-strings-pointers].
5711 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5716 g_variant_iter_next (GVariantIter *iter,
5717 const gchar *format_string,
5722 value = g_variant_iter_next_value (iter);
5724 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5731 va_start (ap, format_string);
5732 g_variant_valist_get (&format_string, value, FALSE, &ap);
5735 g_variant_unref (value);
5738 return value != NULL;
5742 * g_variant_iter_loop: (skip)
5743 * @iter: a #GVariantIter
5744 * @format_string: a GVariant format string
5745 * @...: the arguments to unpack the value into
5747 * Gets the next item in the container and unpacks it into the variable
5748 * argument list according to @format_string, returning %TRUE.
5750 * If no more items remain then %FALSE is returned.
5752 * On the first call to this function, the pointers appearing on the
5753 * variable argument list are assumed to point at uninitialised memory.
5754 * On the second and later calls, it is assumed that the same pointers
5755 * will be given and that they will point to the memory as set by the
5756 * previous call to this function. This allows the previous values to
5757 * be freed, as appropriate.
5759 * This function is intended to be used with a while loop as
5760 * demonstrated in the following example. This function can only be
5761 * used when iterating over an array. It is only valid to call this
5762 * function with a string constant for the format string and the same
5763 * string constant must be used each time. Mixing calls to this
5764 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5765 * the same iterator causes undefined behavior.
5767 * If you break out of a such a while loop using g_variant_iter_loop() then
5768 * you must free or unreference all the unpacked values as you would with
5769 * g_variant_get(). Failure to do so will cause a memory leak.
5771 * Here is an example for memory management with g_variant_iter_loop():
5772 * |[<!-- language="C" -->
5773 * // Iterates a dictionary of type 'a{sv}'
5775 * iterate_dictionary (GVariant *dictionary)
5777 * GVariantIter iter;
5781 * g_variant_iter_init (&iter, dictionary);
5782 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5784 * g_print ("Item '%s' has type '%s'\n", key,
5785 * g_variant_get_type_string (value));
5787 * // no need to free 'key' and 'value' here
5788 * // unless breaking out of this loop
5793 * For most cases you should use g_variant_iter_next().
5795 * This function is really only useful when unpacking into #GVariant or
5796 * #GVariantIter in order to allow you to skip the call to
5797 * g_variant_unref() or g_variant_iter_free().
5799 * For example, if you are only looping over simple integer and string
5800 * types, g_variant_iter_next() is definitely preferred. For string
5801 * types, use the '&' prefix to avoid allocating any memory at all (and
5802 * thereby avoiding the need to free anything as well).
5804 * @format_string determines the C types that are used for unpacking
5805 * the values and also determines if the values are copied or borrowed.
5807 * See the section on
5808 * [GVariant format strings][gvariant-format-strings-pointers].
5810 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5816 g_variant_iter_loop (GVariantIter *iter,
5817 const gchar *format_string,
5820 gboolean first_time = GVSI(iter)->loop_format == NULL;
5824 g_return_val_if_fail (first_time ||
5825 format_string == GVSI(iter)->loop_format,
5830 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5831 GVSI(iter)->loop_format = format_string;
5833 if (strchr (format_string, '&'))
5834 g_variant_get_data (GVSI(iter)->value);
5837 value = g_variant_iter_next_value (iter);
5839 g_return_val_if_fail (!first_time ||
5840 valid_format_string (format_string, TRUE, value),
5843 va_start (ap, format_string);
5844 g_variant_valist_get (&format_string, value, !first_time, &ap);
5848 g_variant_unref (value);
5850 return value != NULL;
5853 /* Serialized data {{{1 */
5855 g_variant_deep_copy (GVariant *value)
5857 switch (g_variant_classify (value))
5859 case G_VARIANT_CLASS_MAYBE:
5860 case G_VARIANT_CLASS_ARRAY:
5861 case G_VARIANT_CLASS_TUPLE:
5862 case G_VARIANT_CLASS_DICT_ENTRY:
5863 case G_VARIANT_CLASS_VARIANT:
5865 GVariantBuilder builder;
5869 g_variant_builder_init (&builder, g_variant_get_type (value));
5870 g_variant_iter_init (&iter, value);
5872 while ((child = g_variant_iter_next_value (&iter)))
5874 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5875 g_variant_unref (child);
5878 return g_variant_builder_end (&builder);
5881 case G_VARIANT_CLASS_BOOLEAN:
5882 return g_variant_new_boolean (g_variant_get_boolean (value));
5884 case G_VARIANT_CLASS_BYTE:
5885 return g_variant_new_byte (g_variant_get_byte (value));
5887 case G_VARIANT_CLASS_INT16:
5888 return g_variant_new_int16 (g_variant_get_int16 (value));
5890 case G_VARIANT_CLASS_UINT16:
5891 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5893 case G_VARIANT_CLASS_INT32:
5894 return g_variant_new_int32 (g_variant_get_int32 (value));
5896 case G_VARIANT_CLASS_UINT32:
5897 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5899 case G_VARIANT_CLASS_INT64:
5900 return g_variant_new_int64 (g_variant_get_int64 (value));
5902 case G_VARIANT_CLASS_UINT64:
5903 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5905 case G_VARIANT_CLASS_HANDLE:
5906 return g_variant_new_handle (g_variant_get_handle (value));
5908 case G_VARIANT_CLASS_DOUBLE:
5909 return g_variant_new_double (g_variant_get_double (value));
5911 case G_VARIANT_CLASS_STRING:
5912 return g_variant_new_string (g_variant_get_string (value, NULL));
5914 case G_VARIANT_CLASS_OBJECT_PATH:
5915 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5917 case G_VARIANT_CLASS_SIGNATURE:
5918 return g_variant_new_signature (g_variant_get_string (value, NULL));
5921 g_assert_not_reached ();
5925 * g_variant_get_normal_form:
5926 * @value: a #GVariant
5928 * Gets a #GVariant instance that has the same value as @value and is
5929 * trusted to be in normal form.
5931 * If @value is already trusted to be in normal form then a new
5932 * reference to @value is returned.
5934 * If @value is not already trusted, then it is scanned to check if it
5935 * is in normal form. If it is found to be in normal form then it is
5936 * marked as trusted and a new reference to it is returned.
5938 * If @value is found not to be in normal form then a new trusted
5939 * #GVariant is created with the same value as @value.
5941 * It makes sense to call this function if you've received #GVariant
5942 * data from untrusted sources and you want to ensure your serialized
5943 * output is definitely in normal form.
5945 * If @value is already in normal form, a new reference will be returned
5946 * (which will be floating if @value is floating). If it is not in normal form,
5947 * the newly created #GVariant will be returned with a single non-floating
5948 * reference. Typically, g_variant_take_ref() should be called on the return
5949 * value from this function to guarantee ownership of a single non-floating
5952 * Returns: (transfer full): a trusted #GVariant
5957 g_variant_get_normal_form (GVariant *value)
5961 if (g_variant_is_normal_form (value))
5962 return g_variant_ref (value);
5964 trusted = g_variant_deep_copy (value);
5965 g_assert (g_variant_is_trusted (trusted));
5967 return g_variant_ref_sink (trusted);
5971 * g_variant_byteswap:
5972 * @value: a #GVariant
5974 * Performs a byteswapping operation on the contents of @value. The
5975 * result is that all multi-byte numeric data contained in @value is
5976 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5977 * integers as well as file handles and double precision floating point
5980 * This function is an identity mapping on any value that does not
5981 * contain multi-byte numeric data. That include strings, booleans,
5982 * bytes and containers containing only these things (recursively).
5984 * The returned value is always in normal form and is marked as trusted.
5986 * Returns: (transfer full): the byteswapped form of @value
5991 g_variant_byteswap (GVariant *value)
5993 GVariantTypeInfo *type_info;
5997 type_info = g_variant_get_type_info (value);
5999 g_variant_type_info_query (type_info, &alignment, NULL);
6002 /* (potentially) contains multi-byte numeric data */
6004 GVariantSerialised serialised;
6008 trusted = g_variant_get_normal_form (value);
6009 serialised.type_info = g_variant_get_type_info (trusted);
6010 serialised.size = g_variant_get_size (trusted);
6011 serialised.data = g_malloc (serialised.size);
6012 serialised.depth = g_variant_get_depth (trusted);
6013 g_variant_store (trusted, serialised.data);
6014 g_variant_unref (trusted);
6016 g_variant_serialised_byteswap (serialised);
6018 bytes = g_bytes_new_take (serialised.data, serialised.size);
6019 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
6020 g_bytes_unref (bytes);
6023 /* contains no multi-byte data */
6026 return g_variant_ref_sink (new);
6030 * g_variant_new_from_data:
6031 * @type: a definite #GVariantType
6032 * @data: (array length=size) (element-type guint8): the serialized data
6033 * @size: the size of @data
6034 * @trusted: %TRUE if @data is definitely in normal form
6035 * @notify: (scope async): function to call when @data is no longer needed
6036 * @user_data: data for @notify
6038 * Creates a new #GVariant instance from serialized data.
6040 * @type is the type of #GVariant instance that will be constructed.
6041 * The interpretation of @data depends on knowing the type.
6043 * @data is not modified by this function and must remain valid with an
6044 * unchanging value until such a time as @notify is called with
6045 * @user_data. If the contents of @data change before that time then
6046 * the result is undefined.
6048 * If @data is trusted to be serialized data in normal form then
6049 * @trusted should be %TRUE. This applies to serialized data created
6050 * within this process or read from a trusted location on the disk (such
6051 * as a file installed in /usr/lib alongside your application). You
6052 * should set trusted to %FALSE if @data is read from the network, a
6053 * file in the user's home directory, etc.
6055 * If @data was not stored in this machine's native endianness, any multi-byte
6056 * numeric values in the returned variant will also be in non-native
6057 * endianness. g_variant_byteswap() can be used to recover the original values.
6059 * @notify will be called with @user_data when @data is no longer
6060 * needed. The exact time of this call is unspecified and might even be
6061 * before this function returns.
6063 * Note: @data must be backed by memory that is aligned appropriately for the
6064 * @type being loaded. Otherwise this function will internally create a copy of
6065 * the memory (since GLib 2.60) or (in older versions) fail and exit the
6068 * Returns: (transfer none): a new floating #GVariant of type @type
6073 g_variant_new_from_data (const GVariantType *type,
6077 GDestroyNotify notify,
6083 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6084 g_return_val_if_fail (data != NULL || size == 0, NULL);
6087 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6089 bytes = g_bytes_new_static (data, size);
6091 value = g_variant_new_from_bytes (type, bytes, trusted);
6092 g_bytes_unref (bytes);
6098 /* vim:set foldmethod=marker: */