2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: Ryan Lortie <desrt@desrt.ca>
25 #include <glib/gvariant-serialiser.h>
26 #include "gvariant-internal.h"
27 #include <glib/gvariant-core.h>
28 #include <glib/gtestutils.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gslice.h>
31 #include <glib/ghash.h>
32 #include <glib/gmem.h>
36 #include "gstrfuncsprivate.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 DBus, 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 serialised
89 * form. It works particularly well with data located in memory-mapped
90 * files. It can perform nearly all deserialisation operations in a
91 * small constant time, usually touching only a single memory page.
92 * Serialised #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 serialisation format is not the same
97 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
98 * in the gio library, for those.)
100 * For space-efficiency, the #GVariant serialisation 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 serialised data, memory for the type
131 * information cache, buffer management memory and memory for the
132 * #GVariant structure itself.
134 * ## Serialised Data Memory
136 * This is the memory that is used for storing GVariant data in
137 * serialised 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 deserialisation.
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 serialised 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 * serialised 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 * serialised 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 serialised data and the buffer
270 * management structure for that serialised 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 serialised 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 serialised 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 TYPE_CHECK (children[i], child_type, NULL);
805 my_children[i] = g_variant_ref_sink (children[i]);
806 trusted &= g_variant_is_trusted (children[i]);
809 value = g_variant_new_from_children (array_type, my_children,
810 n_children, trusted);
811 g_variant_type_free (array_type);
817 * g_variant_make_tuple_type:
818 * @children: (array length=n_children): an array of GVariant *
819 * @n_children: the length of @children
821 * Return the type of a tuple containing @children as its items.
823 static GVariantType *
824 g_variant_make_tuple_type (GVariant * const *children,
827 const GVariantType **types;
831 types = g_new (const GVariantType *, n_children);
833 for (i = 0; i < n_children; i++)
834 types[i] = g_variant_get_type (children[i]);
836 type = g_variant_type_new_tuple (types, n_children);
843 * g_variant_new_tuple:
844 * @children: (array length=n_children): the items to make the tuple out of
845 * @n_children: the length of @children
847 * Creates a new tuple #GVariant out of the items in @children. The
848 * type is determined from the types of @children. No entry in the
849 * @children array may be %NULL.
851 * If @n_children is 0 then the unit tuple is constructed.
853 * If the @children are floating references (see g_variant_ref_sink()), the
854 * new instance takes ownership of them as if via g_variant_ref_sink().
856 * Returns: (transfer none): a floating reference to a new #GVariant tuple
861 g_variant_new_tuple (GVariant * const *children,
864 GVariantType *tuple_type;
865 GVariant **my_children;
870 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
872 my_children = g_new (GVariant *, n_children);
875 for (i = 0; i < n_children; i++)
877 my_children[i] = g_variant_ref_sink (children[i]);
878 trusted &= g_variant_is_trusted (children[i]);
881 tuple_type = g_variant_make_tuple_type (children, n_children);
882 value = g_variant_new_from_children (tuple_type, my_children,
883 n_children, trusted);
884 g_variant_type_free (tuple_type);
890 * g_variant_make_dict_entry_type:
891 * @key: a #GVariant, the key
892 * @val: a #GVariant, the value
894 * Return the type of a dictionary entry containing @key and @val as its
897 static GVariantType *
898 g_variant_make_dict_entry_type (GVariant *key,
901 return g_variant_type_new_dict_entry (g_variant_get_type (key),
902 g_variant_get_type (val));
906 * g_variant_new_dict_entry: (constructor)
907 * @key: a basic #GVariant, the key
908 * @value: a #GVariant, the value
910 * Creates a new dictionary entry #GVariant. @key and @value must be
911 * non-%NULL. @key must be a value of a basic type (ie: not a container).
913 * If the @key or @value are floating references (see g_variant_ref_sink()),
914 * the new instance takes ownership of them as if via g_variant_ref_sink().
916 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
921 g_variant_new_dict_entry (GVariant *key,
924 GVariantType *dict_type;
928 g_return_val_if_fail (key != NULL && value != NULL, NULL);
929 g_return_val_if_fail (!g_variant_is_container (key), NULL);
931 children = g_new (GVariant *, 2);
932 children[0] = g_variant_ref_sink (key);
933 children[1] = g_variant_ref_sink (value);
934 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
936 dict_type = g_variant_make_dict_entry_type (key, value);
937 value = g_variant_new_from_children (dict_type, children, 2, trusted);
938 g_variant_type_free (dict_type);
944 * g_variant_lookup: (skip)
945 * @dictionary: a dictionary #GVariant
946 * @key: the key to look up in the dictionary
947 * @format_string: a GVariant format string
948 * @...: the arguments to unpack the value into
950 * Looks up a value in a dictionary #GVariant.
952 * This function is a wrapper around g_variant_lookup_value() and
953 * g_variant_get(). In the case that %NULL would have been returned,
954 * this function returns %FALSE. Otherwise, it unpacks the returned
955 * value and returns %TRUE.
957 * @format_string determines the C types that are used for unpacking
958 * the values and also determines if the values are copied or borrowed,
960 * [GVariant format strings][gvariant-format-strings-pointers].
962 * This function is currently implemented with a linear scan. If you
963 * plan to do many lookups then #GVariantDict may be more efficient.
965 * Returns: %TRUE if a value was unpacked
970 g_variant_lookup (GVariant *dictionary,
972 const gchar *format_string,
979 g_variant_get_data (dictionary);
981 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
982 value = g_variant_lookup_value (dictionary, key, type);
983 g_variant_type_free (type);
989 va_start (ap, format_string);
990 g_variant_get_va (value, format_string, NULL, &ap);
991 g_variant_unref (value);
1002 * g_variant_lookup_value:
1003 * @dictionary: a dictionary #GVariant
1004 * @key: the key to look up in the dictionary
1005 * @expected_type: (nullable): a #GVariantType, or %NULL
1007 * Looks up a value in a dictionary #GVariant.
1009 * This function works with dictionaries of the type a{s*} (and equally
1010 * well with type a{o*}, but we only further discuss the string case
1011 * for sake of clarity).
1013 * In the event that @dictionary has the type a{sv}, the @expected_type
1014 * string specifies what type of value is expected to be inside of the
1015 * variant. If the value inside the variant has a different type then
1016 * %NULL is returned. In the event that @dictionary has a value type other
1017 * than v then @expected_type must directly match the value type and it is
1018 * used to unpack the value directly or an error occurs.
1020 * In either case, if @key is not found in @dictionary, %NULL is returned.
1022 * If the key is found and the value has the correct type, it is
1023 * returned. If @expected_type was specified then any non-%NULL return
1024 * value will have this type.
1026 * This function is currently implemented with a linear scan. If you
1027 * plan to do many lookups then #GVariantDict may be more efficient.
1029 * Returns: (transfer full): the value of the dictionary key, or %NULL
1034 g_variant_lookup_value (GVariant *dictionary,
1036 const GVariantType *expected_type)
1042 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1043 G_VARIANT_TYPE ("a{s*}")) ||
1044 g_variant_is_of_type (dictionary,
1045 G_VARIANT_TYPE ("a{o*}")),
1048 g_variant_iter_init (&iter, dictionary);
1050 while ((entry = g_variant_iter_next_value (&iter)))
1052 GVariant *entry_key;
1055 entry_key = g_variant_get_child_value (entry, 0);
1056 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1057 g_variant_unref (entry_key);
1062 g_variant_unref (entry);
1068 value = g_variant_get_child_value (entry, 1);
1069 g_variant_unref (entry);
1071 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1075 tmp = g_variant_get_variant (value);
1076 g_variant_unref (value);
1078 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1080 g_variant_unref (tmp);
1087 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1088 g_variant_is_of_type (value, expected_type), NULL);
1094 * g_variant_get_fixed_array:
1095 * @value: a #GVariant array with fixed-sized elements
1096 * @n_elements: (out): a pointer to the location to store the number of items
1097 * @element_size: the size of each element
1099 * Provides access to the serialised data for an array of fixed-sized
1102 * @value must be an array with fixed-sized elements. Numeric types are
1103 * fixed-size, as are tuples containing only other fixed-sized types.
1105 * @element_size must be the size of a single element in the array,
1106 * as given by the section on
1107 * [serialized data memory][gvariant-serialised-data-memory].
1109 * In particular, arrays of these fixed-sized types can be interpreted
1110 * as an array of the given C type, with @element_size set to the size
1111 * the appropriate type:
1112 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1113 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1114 * - %G_VARIANT_TYPE_BYTE: #guint8
1115 * - %G_VARIANT_TYPE_HANDLE: #guint32
1116 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1118 * For example, if calling this function for an array of 32-bit integers,
1119 * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1120 * of a double-check that the form of the serialised data matches the caller's
1123 * @n_elements, which must be non-%NULL, is set equal to the number of
1124 * items in the array.
1126 * Returns: (array length=n_elements) (transfer none): a pointer to
1132 g_variant_get_fixed_array (GVariant *value,
1136 GVariantTypeInfo *array_info;
1137 gsize array_element_size;
1141 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1143 g_return_val_if_fail (n_elements != NULL, NULL);
1144 g_return_val_if_fail (element_size > 0, NULL);
1146 array_info = g_variant_get_type_info (value);
1147 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1149 g_return_val_if_fail (array_element_size, NULL);
1151 if G_UNLIKELY (array_element_size != element_size)
1153 if (array_element_size)
1154 g_critical ("g_variant_get_fixed_array: assertion "
1155 "'g_variant_array_has_fixed_size (value, element_size)' "
1156 "failed: array size %"G_GSIZE_FORMAT" does not match "
1157 "given element_size %"G_GSIZE_FORMAT".",
1158 array_element_size, element_size);
1160 g_critical ("g_variant_get_fixed_array: assertion "
1161 "'g_variant_array_has_fixed_size (value, element_size)' "
1162 "failed: array does not have fixed size.");
1165 data = g_variant_get_data (value);
1166 size = g_variant_get_size (value);
1168 if (size % element_size)
1171 *n_elements = size / element_size;
1180 * g_variant_new_fixed_array:
1181 * @element_type: the #GVariantType of each element
1182 * @elements: a pointer to the fixed array of contiguous elements
1183 * @n_elements: the number of elements
1184 * @element_size: the size of each element
1186 * Constructs a new array #GVariant instance, where the elements are
1187 * of @element_type type.
1189 * @elements must be an array with fixed-sized elements. Numeric types are
1190 * fixed-size as are tuples containing only other fixed-sized types.
1192 * @element_size must be the size of a single element in the array.
1193 * For example, if calling this function for an array of 32-bit integers,
1194 * you might say sizeof(gint32). This value isn't used except for the purpose
1195 * of a double-check that the form of the serialised data matches the caller's
1198 * @n_elements must be the length of the @elements array.
1200 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1205 g_variant_new_fixed_array (const GVariantType *element_type,
1206 gconstpointer elements,
1210 GVariantType *array_type;
1211 gsize array_element_size;
1212 GVariantTypeInfo *array_info;
1216 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1217 g_return_val_if_fail (element_size > 0, NULL);
1219 array_type = g_variant_type_new_array (element_type);
1220 array_info = g_variant_type_info_get (array_type);
1221 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1222 if G_UNLIKELY (array_element_size != element_size)
1224 if (array_element_size)
1225 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1226 " does not match given element_size %" G_GSIZE_FORMAT ".",
1227 array_element_size, element_size);
1229 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1233 data = g_memdup2 (elements, n_elements * element_size);
1234 value = g_variant_new_from_data (array_type, data,
1235 n_elements * element_size,
1236 FALSE, g_free, data);
1238 g_variant_type_free (array_type);
1239 g_variant_type_info_unref (array_info);
1244 /* String type constructor/getters/validation {{{1 */
1246 * g_variant_new_string:
1247 * @string: a normal UTF-8 nul-terminated string
1249 * Creates a string #GVariant with the contents of @string.
1251 * @string must be valid UTF-8, and must not be %NULL. To encode
1252 * potentially-%NULL strings, use g_variant_new() with `ms` as the
1253 * [format string][gvariant-format-strings-maybe-types].
1255 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1260 g_variant_new_string (const gchar *string)
1262 g_return_val_if_fail (string != NULL, NULL);
1263 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1265 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1266 string, strlen (string) + 1);
1270 * g_variant_new_take_string: (skip)
1271 * @string: a normal UTF-8 nul-terminated string
1273 * Creates a string #GVariant with the contents of @string.
1275 * @string must be valid UTF-8, and must not be %NULL. To encode
1276 * potentially-%NULL strings, use this with g_variant_new_maybe().
1278 * This function consumes @string. g_free() will be called on @string
1279 * when it is no longer required.
1281 * You must not modify or access @string in any other way after passing
1282 * it to this function. It is even possible that @string is immediately
1285 * Returns: (transfer none): a floating reference to a new string
1286 * #GVariant instance
1291 g_variant_new_take_string (gchar *string)
1296 g_return_val_if_fail (string != NULL, NULL);
1297 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1299 bytes = g_bytes_new_take (string, strlen (string) + 1);
1300 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1301 g_bytes_unref (bytes);
1307 * g_variant_new_printf: (skip)
1308 * @format_string: a printf-style format string
1309 * @...: arguments for @format_string
1311 * Creates a string-type GVariant using printf formatting.
1313 * This is similar to calling g_strdup_printf() and then
1314 * g_variant_new_string() but it saves a temporary variable and an
1317 * Returns: (transfer none): a floating reference to a new string
1318 * #GVariant instance
1323 g_variant_new_printf (const gchar *format_string,
1331 g_return_val_if_fail (format_string != NULL, NULL);
1333 va_start (ap, format_string);
1334 string = g_strdup_vprintf (format_string, ap);
1337 bytes = g_bytes_new_take (string, strlen (string) + 1);
1338 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1339 g_bytes_unref (bytes);
1345 * g_variant_new_object_path:
1346 * @object_path: a normal C nul-terminated string
1348 * Creates a D-Bus object path #GVariant with the contents of @string.
1349 * @string must be a valid D-Bus object path. Use
1350 * g_variant_is_object_path() if you're not sure.
1352 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1357 g_variant_new_object_path (const gchar *object_path)
1359 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1361 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1362 object_path, strlen (object_path) + 1);
1366 * g_variant_is_object_path:
1367 * @string: a normal C nul-terminated string
1369 * Determines if a given string is a valid D-Bus object path. You
1370 * should ensure that a string is a valid D-Bus object path before
1371 * passing it to g_variant_new_object_path().
1373 * A valid object path starts with `/` followed by zero or more
1374 * sequences of characters separated by `/` characters. Each sequence
1375 * must contain only the characters `[A-Z][a-z][0-9]_`. No sequence
1376 * (including the one following the final `/` character) may be empty.
1378 * Returns: %TRUE if @string is a D-Bus object path
1383 g_variant_is_object_path (const gchar *string)
1385 g_return_val_if_fail (string != NULL, FALSE);
1387 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1391 * g_variant_new_signature:
1392 * @signature: a normal C nul-terminated string
1394 * Creates a D-Bus type signature #GVariant with the contents of
1395 * @string. @string must be a valid D-Bus type signature. Use
1396 * g_variant_is_signature() if you're not sure.
1398 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1403 g_variant_new_signature (const gchar *signature)
1405 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1407 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1408 signature, strlen (signature) + 1);
1412 * g_variant_is_signature:
1413 * @string: a normal C nul-terminated string
1415 * Determines if a given string is a valid D-Bus type signature. You
1416 * should ensure that a string is a valid D-Bus type signature before
1417 * passing it to g_variant_new_signature().
1419 * D-Bus type signatures consist of zero or more definite #GVariantType
1420 * strings in sequence.
1422 * Returns: %TRUE if @string is a D-Bus type signature
1427 g_variant_is_signature (const gchar *string)
1429 g_return_val_if_fail (string != NULL, FALSE);
1431 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1435 * g_variant_get_string:
1436 * @value: a string #GVariant instance
1437 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1438 * to store the length
1440 * Returns the string value of a #GVariant instance with a string
1441 * type. This includes the types %G_VARIANT_TYPE_STRING,
1442 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1444 * The string will always be UTF-8 encoded, will never be %NULL, and will never
1445 * contain nul bytes.
1447 * If @length is non-%NULL then the length of the string (in bytes) is
1448 * returned there. For trusted values, this information is already
1449 * known. Untrusted values will be validated and, if valid, a strlen() will be
1450 * performed. If invalid, a default value will be returned — for
1451 * %G_VARIANT_TYPE_OBJECT_PATH, this is `"/"`, and for other types it is the
1454 * It is an error to call this function with a @value of any type
1455 * other than those three.
1457 * The return value remains valid as long as @value exists.
1459 * Returns: (transfer none): the constant string, UTF-8 encoded
1464 g_variant_get_string (GVariant *value,
1470 g_return_val_if_fail (value != NULL, NULL);
1471 g_return_val_if_fail (
1472 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1473 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1474 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1476 data = g_variant_get_data (value);
1477 size = g_variant_get_size (value);
1479 if (!g_variant_is_trusted (value))
1481 switch (g_variant_classify (value))
1483 case G_VARIANT_CLASS_STRING:
1484 if (g_variant_serialiser_is_string (data, size))
1491 case G_VARIANT_CLASS_OBJECT_PATH:
1492 if (g_variant_serialiser_is_object_path (data, size))
1499 case G_VARIANT_CLASS_SIGNATURE:
1500 if (g_variant_serialiser_is_signature (data, size))
1508 g_assert_not_reached ();
1519 * g_variant_dup_string:
1520 * @value: a string #GVariant instance
1521 * @length: (out): a pointer to a #gsize, to store the length
1523 * Similar to g_variant_get_string() except that instead of returning
1524 * a constant string, the string is duplicated.
1526 * The string will always be UTF-8 encoded.
1528 * The return value must be freed using g_free().
1530 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1535 g_variant_dup_string (GVariant *value,
1538 return g_strdup (g_variant_get_string (value, length));
1542 * g_variant_new_strv:
1543 * @strv: (array length=length) (element-type utf8): an array of strings
1544 * @length: the length of @strv, or -1
1546 * Constructs an array of strings #GVariant from the given array of
1549 * If @length is -1 then @strv is %NULL-terminated.
1551 * Returns: (transfer none): a new floating #GVariant instance
1556 g_variant_new_strv (const gchar * const *strv,
1560 gsize i, length_unsigned;
1562 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1565 length = g_strv_length ((gchar **) strv);
1566 length_unsigned = length;
1568 strings = g_new (GVariant *, length_unsigned);
1569 for (i = 0; i < length_unsigned; i++)
1570 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1572 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1573 strings, length_unsigned, TRUE);
1577 * g_variant_get_strv:
1578 * @value: an array of strings #GVariant
1579 * @length: (out) (optional): the length of the result, or %NULL
1581 * Gets the contents of an array of strings #GVariant. This call
1582 * makes a shallow copy; the return result should be released with
1583 * g_free(), but the individual strings must not be modified.
1585 * If @length is non-%NULL then the number of elements in the result
1586 * is stored there. In any case, the resulting array will be
1589 * For an empty array, @length will be set to 0 and a pointer to a
1590 * %NULL pointer will be returned.
1592 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1597 g_variant_get_strv (GVariant *value,
1604 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1606 g_variant_get_data (value);
1607 n = g_variant_n_children (value);
1608 strv = g_new (const gchar *, n + 1);
1610 for (i = 0; i < n; i++)
1614 string = g_variant_get_child_value (value, i);
1615 strv[i] = g_variant_get_string (string, NULL);
1616 g_variant_unref (string);
1627 * g_variant_dup_strv:
1628 * @value: an array of strings #GVariant
1629 * @length: (out) (optional): the length of the result, or %NULL
1631 * Gets the contents of an array of strings #GVariant. This call
1632 * makes a deep copy; the return result should be released with
1635 * If @length is non-%NULL then the number of elements in the result
1636 * is stored there. In any case, the resulting array will be
1639 * For an empty array, @length will be set to 0 and a pointer to a
1640 * %NULL pointer will be returned.
1642 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1647 g_variant_dup_strv (GVariant *value,
1654 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1656 n = g_variant_n_children (value);
1657 strv = g_new (gchar *, n + 1);
1659 for (i = 0; i < n; i++)
1663 string = g_variant_get_child_value (value, i);
1664 strv[i] = g_variant_dup_string (string, NULL);
1665 g_variant_unref (string);
1676 * g_variant_new_objv:
1677 * @strv: (array length=length) (element-type utf8): an array of strings
1678 * @length: the length of @strv, or -1
1680 * Constructs an array of object paths #GVariant from the given array of
1683 * Each string must be a valid #GVariant object path; see
1684 * g_variant_is_object_path().
1686 * If @length is -1 then @strv is %NULL-terminated.
1688 * Returns: (transfer none): a new floating #GVariant instance
1693 g_variant_new_objv (const gchar * const *strv,
1697 gsize i, length_unsigned;
1699 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1702 length = g_strv_length ((gchar **) strv);
1703 length_unsigned = length;
1705 strings = g_new (GVariant *, length_unsigned);
1706 for (i = 0; i < length_unsigned; i++)
1707 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1709 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1710 strings, length_unsigned, TRUE);
1714 * g_variant_get_objv:
1715 * @value: an array of object paths #GVariant
1716 * @length: (out) (optional): the length of the result, or %NULL
1718 * Gets the contents of an array of object paths #GVariant. This call
1719 * makes a shallow copy; the return result should be released with
1720 * g_free(), but the individual strings must not be modified.
1722 * If @length is non-%NULL then the number of elements in the result
1723 * is stored there. In any case, the resulting array will be
1726 * For an empty array, @length will be set to 0 and a pointer to a
1727 * %NULL pointer will be returned.
1729 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1734 g_variant_get_objv (GVariant *value,
1741 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1743 g_variant_get_data (value);
1744 n = g_variant_n_children (value);
1745 strv = g_new (const gchar *, n + 1);
1747 for (i = 0; i < n; i++)
1751 string = g_variant_get_child_value (value, i);
1752 strv[i] = g_variant_get_string (string, NULL);
1753 g_variant_unref (string);
1764 * g_variant_dup_objv:
1765 * @value: an array of object paths #GVariant
1766 * @length: (out) (optional): the length of the result, or %NULL
1768 * Gets the contents of an array of object paths #GVariant. This call
1769 * makes a deep copy; the return result should be released with
1772 * If @length is non-%NULL then the number of elements in the result
1773 * is stored there. In any case, the resulting array will be
1776 * For an empty array, @length will be set to 0 and a pointer to a
1777 * %NULL pointer will be returned.
1779 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1784 g_variant_dup_objv (GVariant *value,
1791 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1793 n = g_variant_n_children (value);
1794 strv = g_new (gchar *, n + 1);
1796 for (i = 0; i < n; i++)
1800 string = g_variant_get_child_value (value, i);
1801 strv[i] = g_variant_dup_string (string, NULL);
1802 g_variant_unref (string);
1814 * g_variant_new_bytestring:
1815 * @string: (array zero-terminated=1) (element-type guint8): a normal
1816 * nul-terminated string in no particular encoding
1818 * Creates an array-of-bytes #GVariant with the contents of @string.
1819 * This function is just like g_variant_new_string() except that the
1820 * string need not be valid UTF-8.
1822 * The nul terminator character at the end of the string is stored in
1825 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1830 g_variant_new_bytestring (const gchar *string)
1832 g_return_val_if_fail (string != NULL, NULL);
1834 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1835 string, strlen (string) + 1);
1839 * g_variant_get_bytestring:
1840 * @value: an array-of-bytes #GVariant instance
1842 * Returns the string value of a #GVariant instance with an
1843 * array-of-bytes type. The string has no particular encoding.
1845 * If the array does not end with a nul terminator character, the empty
1846 * string is returned. For this reason, you can always trust that a
1847 * non-%NULL nul-terminated string will be returned by this function.
1849 * If the array contains a nul terminator character somewhere other than
1850 * the last byte then the returned string is the string, up to the first
1851 * such nul character.
1853 * g_variant_get_fixed_array() should be used instead if the array contains
1854 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1856 * It is an error to call this function with a @value that is not an
1859 * The return value remains valid as long as @value exists.
1861 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1862 * the constant string
1867 g_variant_get_bytestring (GVariant *value)
1869 const gchar *string;
1872 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1874 /* Won't be NULL since this is an array type */
1875 string = g_variant_get_data (value);
1876 size = g_variant_get_size (value);
1878 if (size && string[size - 1] == '\0')
1885 * g_variant_dup_bytestring:
1886 * @value: an array-of-bytes #GVariant instance
1887 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1888 * the length (not including the nul terminator)
1890 * Similar to g_variant_get_bytestring() except that instead of
1891 * returning a constant string, the string is duplicated.
1893 * The return value must be freed using g_free().
1895 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1896 * a newly allocated string
1901 g_variant_dup_bytestring (GVariant *value,
1904 const gchar *original = g_variant_get_bytestring (value);
1907 /* don't crash in case get_bytestring() had an assert failure */
1908 if (original == NULL)
1911 size = strlen (original);
1916 return g_memdup2 (original, size + 1);
1920 * g_variant_new_bytestring_array:
1921 * @strv: (array length=length): an array of strings
1922 * @length: the length of @strv, or -1
1924 * Constructs an array of bytestring #GVariant from the given array of
1927 * If @length is -1 then @strv is %NULL-terminated.
1929 * Returns: (transfer none): a new floating #GVariant instance
1934 g_variant_new_bytestring_array (const gchar * const *strv,
1938 gsize i, length_unsigned;
1940 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1943 length = g_strv_length ((gchar **) strv);
1944 length_unsigned = length;
1946 strings = g_new (GVariant *, length_unsigned);
1947 for (i = 0; i < length_unsigned; i++)
1948 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1950 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1951 strings, length_unsigned, TRUE);
1955 * g_variant_get_bytestring_array:
1956 * @value: an array of array of bytes #GVariant ('aay')
1957 * @length: (out) (optional): the length of the result, or %NULL
1959 * Gets the contents of an array of array of bytes #GVariant. This call
1960 * makes a shallow copy; the return result should be released with
1961 * g_free(), but the individual strings must not be modified.
1963 * If @length is non-%NULL then the number of elements in the result is
1964 * stored there. In any case, the resulting array will be
1967 * For an empty array, @length will be set to 0 and a pointer to a
1968 * %NULL pointer will be returned.
1970 * Returns: (array length=length) (transfer container): an array of constant strings
1975 g_variant_get_bytestring_array (GVariant *value,
1982 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1984 g_variant_get_data (value);
1985 n = g_variant_n_children (value);
1986 strv = g_new (const gchar *, n + 1);
1988 for (i = 0; i < n; i++)
1992 string = g_variant_get_child_value (value, i);
1993 strv[i] = g_variant_get_bytestring (string);
1994 g_variant_unref (string);
2005 * g_variant_dup_bytestring_array:
2006 * @value: an array of array of bytes #GVariant ('aay')
2007 * @length: (out) (optional): the length of the result, or %NULL
2009 * Gets the contents of an array of array of bytes #GVariant. This call
2010 * makes a deep copy; the return result should be released with
2013 * If @length is non-%NULL then the number of elements in the result is
2014 * stored there. In any case, the resulting array will be
2017 * For an empty array, @length will be set to 0 and a pointer to a
2018 * %NULL pointer will be returned.
2020 * Returns: (array length=length) (transfer full): an array of strings
2025 g_variant_dup_bytestring_array (GVariant *value,
2032 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2034 g_variant_get_data (value);
2035 n = g_variant_n_children (value);
2036 strv = g_new (gchar *, n + 1);
2038 for (i = 0; i < n; i++)
2042 string = g_variant_get_child_value (value, i);
2043 strv[i] = g_variant_dup_bytestring (string, NULL);
2044 g_variant_unref (string);
2054 /* Type checking and querying {{{1 */
2056 * g_variant_get_type:
2057 * @value: a #GVariant
2059 * Determines the type of @value.
2061 * The return value is valid for the lifetime of @value and must not
2064 * Returns: a #GVariantType
2068 const GVariantType *
2069 g_variant_get_type (GVariant *value)
2071 GVariantTypeInfo *type_info;
2073 g_return_val_if_fail (value != NULL, NULL);
2075 type_info = g_variant_get_type_info (value);
2077 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2081 * g_variant_get_type_string:
2082 * @value: a #GVariant
2084 * Returns the type string of @value. Unlike the result of calling
2085 * g_variant_type_peek_string(), this string is nul-terminated. This
2086 * string belongs to #GVariant and must not be freed.
2088 * Returns: the type string for the type of @value
2093 g_variant_get_type_string (GVariant *value)
2095 GVariantTypeInfo *type_info;
2097 g_return_val_if_fail (value != NULL, NULL);
2099 type_info = g_variant_get_type_info (value);
2101 return g_variant_type_info_get_type_string (type_info);
2105 * g_variant_is_of_type:
2106 * @value: a #GVariant instance
2107 * @type: a #GVariantType
2109 * Checks if a value has a type matching the provided type.
2111 * Returns: %TRUE if the type of @value matches @type
2116 g_variant_is_of_type (GVariant *value,
2117 const GVariantType *type)
2119 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2123 * g_variant_is_container:
2124 * @value: a #GVariant instance
2126 * Checks if @value is a container.
2128 * Returns: %TRUE if @value is a container
2133 g_variant_is_container (GVariant *value)
2135 return g_variant_type_is_container (g_variant_get_type (value));
2140 * g_variant_classify:
2141 * @value: a #GVariant
2143 * Classifies @value according to its top-level type.
2145 * Returns: the #GVariantClass of @value
2151 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2152 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2153 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2154 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2155 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2156 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2157 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2158 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2159 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2160 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2162 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2163 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2165 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2166 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2167 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2168 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2169 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2170 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2172 * The range of possible top-level types of #GVariant instances.
2177 g_variant_classify (GVariant *value)
2179 g_return_val_if_fail (value != NULL, 0);
2181 return *g_variant_get_type_string (value);
2184 /* Pretty printer {{{1 */
2185 /* This function is not introspectable because if @string is NULL,
2186 @returns is (transfer full), otherwise it is (transfer none), which
2187 is not supported by GObjectIntrospection */
2189 * g_variant_print_string: (skip)
2190 * @value: a #GVariant
2191 * @string: (nullable) (default NULL): a #GString, or %NULL
2192 * @type_annotate: %TRUE if type information should be included in
2195 * Behaves as g_variant_print(), but operates on a #GString.
2197 * If @string is non-%NULL then it is appended to and returned. Else,
2198 * a new empty #GString is allocated and it is returned.
2200 * Returns: a #GString containing the string
2205 g_variant_print_string (GVariant *value,
2207 gboolean type_annotate)
2209 if G_UNLIKELY (string == NULL)
2210 string = g_string_new (NULL);
2212 switch (g_variant_classify (value))
2214 case G_VARIANT_CLASS_MAYBE:
2216 g_string_append_printf (string, "@%s ",
2217 g_variant_get_type_string (value));
2219 if (g_variant_n_children (value))
2221 gchar *printed_child;
2226 * Consider the case of the type "mmi". In this case we could
2227 * write "just just 4", but "4" alone is totally unambiguous,
2228 * so we try to drop "just" where possible.
2230 * We have to be careful not to always drop "just", though,
2231 * since "nothing" needs to be distinguishable from "just
2232 * nothing". The case where we need to ensure we keep the
2233 * "just" is actually exactly the case where we have a nested
2236 * Instead of searching for that nested Nothing, we just print
2237 * the contained value into a separate string and see if we
2238 * end up with "nothing" at the end of it. If so, we need to
2239 * add "just" at our level.
2241 element = g_variant_get_child_value (value, 0);
2242 printed_child = g_variant_print (element, FALSE);
2243 g_variant_unref (element);
2245 if (g_str_has_suffix (printed_child, "nothing"))
2246 g_string_append (string, "just ");
2247 g_string_append (string, printed_child);
2248 g_free (printed_child);
2251 g_string_append (string, "nothing");
2255 case G_VARIANT_CLASS_ARRAY:
2256 /* it's an array so the first character of the type string is 'a'
2258 * if the first two characters are 'ay' then it's a bytestring.
2259 * under certain conditions we print those as strings.
2261 if (g_variant_get_type_string (value)[1] == 'y')
2267 /* first determine if it is a byte string.
2268 * that's when there's a single nul character: at the end.
2270 str = g_variant_get_data (value);
2271 size = g_variant_get_size (value);
2273 for (i = 0; i < size; i++)
2277 /* first nul byte is the last byte -> it's a byte string. */
2280 gchar *escaped = g_strescape (str, NULL);
2282 /* use double quotes only if a ' is in the string */
2283 if (strchr (str, '\''))
2284 g_string_append_printf (string, "b\"%s\"", escaped);
2286 g_string_append_printf (string, "b'%s'", escaped);
2294 /* fall through and handle normally... */
2299 * if the first two characters are 'a{' then it's an array of
2300 * dictionary entries (ie: a dictionary) so we print that
2303 if (g_variant_get_type_string (value)[1] == '{')
2306 const gchar *comma = "";
2309 if ((n = g_variant_n_children (value)) == 0)
2312 g_string_append_printf (string, "@%s ",
2313 g_variant_get_type_string (value));
2314 g_string_append (string, "{}");
2318 g_string_append_c (string, '{');
2319 for (i = 0; i < n; i++)
2321 GVariant *entry, *key, *val;
2323 g_string_append (string, comma);
2326 entry = g_variant_get_child_value (value, i);
2327 key = g_variant_get_child_value (entry, 0);
2328 val = g_variant_get_child_value (entry, 1);
2329 g_variant_unref (entry);
2331 g_variant_print_string (key, string, type_annotate);
2332 g_variant_unref (key);
2333 g_string_append (string, ": ");
2334 g_variant_print_string (val, string, type_annotate);
2335 g_variant_unref (val);
2336 type_annotate = FALSE;
2338 g_string_append_c (string, '}');
2341 /* normal (non-dictionary) array */
2343 const gchar *comma = "";
2346 if ((n = g_variant_n_children (value)) == 0)
2349 g_string_append_printf (string, "@%s ",
2350 g_variant_get_type_string (value));
2351 g_string_append (string, "[]");
2355 g_string_append_c (string, '[');
2356 for (i = 0; i < n; i++)
2360 g_string_append (string, comma);
2363 element = g_variant_get_child_value (value, i);
2365 g_variant_print_string (element, string, type_annotate);
2366 g_variant_unref (element);
2367 type_annotate = FALSE;
2369 g_string_append_c (string, ']');
2374 case G_VARIANT_CLASS_TUPLE:
2378 n = g_variant_n_children (value);
2380 g_string_append_c (string, '(');
2381 for (i = 0; i < n; i++)
2385 element = g_variant_get_child_value (value, i);
2386 g_variant_print_string (element, string, type_annotate);
2387 g_string_append (string, ", ");
2388 g_variant_unref (element);
2391 /* for >1 item: remove final ", "
2392 * for 1 item: remove final " ", but leave the ","
2393 * for 0 items: there is only "(", so remove nothing
2395 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2396 g_string_append_c (string, ')');
2400 case G_VARIANT_CLASS_DICT_ENTRY:
2404 g_string_append_c (string, '{');
2406 element = g_variant_get_child_value (value, 0);
2407 g_variant_print_string (element, string, type_annotate);
2408 g_variant_unref (element);
2410 g_string_append (string, ", ");
2412 element = g_variant_get_child_value (value, 1);
2413 g_variant_print_string (element, string, type_annotate);
2414 g_variant_unref (element);
2416 g_string_append_c (string, '}');
2420 case G_VARIANT_CLASS_VARIANT:
2422 GVariant *child = g_variant_get_variant (value);
2424 /* Always annotate types in nested variants, because they are
2425 * (by nature) of variable type.
2427 g_string_append_c (string, '<');
2428 g_variant_print_string (child, string, TRUE);
2429 g_string_append_c (string, '>');
2431 g_variant_unref (child);
2435 case G_VARIANT_CLASS_BOOLEAN:
2436 if (g_variant_get_boolean (value))
2437 g_string_append (string, "true");
2439 g_string_append (string, "false");
2442 case G_VARIANT_CLASS_STRING:
2444 const gchar *str = g_variant_get_string (value, NULL);
2445 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2447 g_string_append_c (string, quote);
2451 gunichar c = g_utf8_get_char (str);
2453 if (c == quote || c == '\\')
2454 g_string_append_c (string, '\\');
2456 if (g_unichar_isprint (c))
2457 g_string_append_unichar (string, c);
2461 g_string_append_c (string, '\\');
2466 g_string_append_c (string, 'a');
2470 g_string_append_c (string, 'b');
2474 g_string_append_c (string, 'f');
2478 g_string_append_c (string, 'n');
2482 g_string_append_c (string, 'r');
2486 g_string_append_c (string, 't');
2490 g_string_append_c (string, 'v');
2494 g_string_append_printf (string, "u%04x", c);
2498 g_string_append_printf (string, "U%08x", c);
2501 str = g_utf8_next_char (str);
2504 g_string_append_c (string, quote);
2508 case G_VARIANT_CLASS_BYTE:
2510 g_string_append (string, "byte ");
2511 g_string_append_printf (string, "0x%02x",
2512 g_variant_get_byte (value));
2515 case G_VARIANT_CLASS_INT16:
2517 g_string_append (string, "int16 ");
2518 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2519 g_variant_get_int16 (value));
2522 case G_VARIANT_CLASS_UINT16:
2524 g_string_append (string, "uint16 ");
2525 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2526 g_variant_get_uint16 (value));
2529 case G_VARIANT_CLASS_INT32:
2530 /* Never annotate this type because it is the default for numbers
2531 * (and this is a *pretty* printer)
2533 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2534 g_variant_get_int32 (value));
2537 case G_VARIANT_CLASS_HANDLE:
2539 g_string_append (string, "handle ");
2540 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2541 g_variant_get_handle (value));
2544 case G_VARIANT_CLASS_UINT32:
2546 g_string_append (string, "uint32 ");
2547 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2548 g_variant_get_uint32 (value));
2551 case G_VARIANT_CLASS_INT64:
2553 g_string_append (string, "int64 ");
2554 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2555 g_variant_get_int64 (value));
2558 case G_VARIANT_CLASS_UINT64:
2560 g_string_append (string, "uint64 ");
2561 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2562 g_variant_get_uint64 (value));
2565 case G_VARIANT_CLASS_DOUBLE:
2570 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2572 for (i = 0; buffer[i]; i++)
2573 if (buffer[i] == '.' || buffer[i] == 'e' ||
2574 buffer[i] == 'n' || buffer[i] == 'N')
2577 /* if there is no '.' or 'e' in the float then add one */
2578 if (buffer[i] == '\0')
2585 g_string_append (string, buffer);
2589 case G_VARIANT_CLASS_OBJECT_PATH:
2591 g_string_append (string, "objectpath ");
2592 g_string_append_printf (string, "\'%s\'",
2593 g_variant_get_string (value, NULL));
2596 case G_VARIANT_CLASS_SIGNATURE:
2598 g_string_append (string, "signature ");
2599 g_string_append_printf (string, "\'%s\'",
2600 g_variant_get_string (value, NULL));
2604 g_assert_not_reached ();
2612 * @value: a #GVariant
2613 * @type_annotate: %TRUE if type information should be included in
2616 * Pretty-prints @value in the format understood by g_variant_parse().
2618 * The format is described [here][gvariant-text].
2620 * If @type_annotate is %TRUE, then type information is included in
2623 * Returns: (transfer full): a newly-allocated string holding the result.
2628 g_variant_print (GVariant *value,
2629 gboolean type_annotate)
2631 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2635 /* Hash, Equal, Compare {{{1 */
2638 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2640 * Generates a hash value for a #GVariant instance.
2642 * The output of this function is guaranteed to be the same for a given
2643 * value only per-process. It may change between different processor
2644 * architectures or even different versions of GLib. Do not use this
2645 * function as a basis for building protocols or file formats.
2647 * The type of @value is #gconstpointer only to allow use of this
2648 * function with #GHashTable. @value must be a #GVariant.
2650 * Returns: a hash value corresponding to @value
2655 g_variant_hash (gconstpointer value_)
2657 GVariant *value = (GVariant *) value_;
2659 switch (g_variant_classify (value))
2661 case G_VARIANT_CLASS_STRING:
2662 case G_VARIANT_CLASS_OBJECT_PATH:
2663 case G_VARIANT_CLASS_SIGNATURE:
2664 return g_str_hash (g_variant_get_string (value, NULL));
2666 case G_VARIANT_CLASS_BOOLEAN:
2667 /* this is a very odd thing to hash... */
2668 return g_variant_get_boolean (value);
2670 case G_VARIANT_CLASS_BYTE:
2671 return g_variant_get_byte (value);
2673 case G_VARIANT_CLASS_INT16:
2674 case G_VARIANT_CLASS_UINT16:
2678 ptr = g_variant_get_data (value);
2686 case G_VARIANT_CLASS_INT32:
2687 case G_VARIANT_CLASS_UINT32:
2688 case G_VARIANT_CLASS_HANDLE:
2692 ptr = g_variant_get_data (value);
2700 case G_VARIANT_CLASS_INT64:
2701 case G_VARIANT_CLASS_UINT64:
2702 case G_VARIANT_CLASS_DOUBLE:
2703 /* need a separate case for these guys because otherwise
2704 * performance could be quite bad on big endian systems
2709 ptr = g_variant_get_data (value);
2712 return ptr[0] + ptr[1];
2718 g_return_val_if_fail (!g_variant_is_container (value), 0);
2719 g_assert_not_reached ();
2725 * @one: (type GVariant): a #GVariant instance
2726 * @two: (type GVariant): a #GVariant instance
2728 * Checks if @one and @two have the same type and value.
2730 * The types of @one and @two are #gconstpointer only to allow use of
2731 * this function with #GHashTable. They must each be a #GVariant.
2733 * Returns: %TRUE if @one and @two are equal
2738 g_variant_equal (gconstpointer one,
2743 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2745 if (g_variant_get_type_info ((GVariant *) one) !=
2746 g_variant_get_type_info ((GVariant *) two))
2749 /* if both values are trusted to be in their canonical serialised form
2750 * then a simple memcmp() of their serialised data will answer the
2753 * if not, then this might generate a false negative (since it is
2754 * possible for two different byte sequences to represent the same
2755 * value). for now we solve this by pretty-printing both values and
2756 * comparing the result.
2758 if (g_variant_is_trusted ((GVariant *) one) &&
2759 g_variant_is_trusted ((GVariant *) two))
2761 gconstpointer data_one, data_two;
2762 gsize size_one, size_two;
2764 size_one = g_variant_get_size ((GVariant *) one);
2765 size_two = g_variant_get_size ((GVariant *) two);
2767 if (size_one != size_two)
2770 data_one = g_variant_get_data ((GVariant *) one);
2771 data_two = g_variant_get_data ((GVariant *) two);
2774 equal = memcmp (data_one, data_two, size_one) == 0;
2780 gchar *strone, *strtwo;
2782 strone = g_variant_print ((GVariant *) one, FALSE);
2783 strtwo = g_variant_print ((GVariant *) two, FALSE);
2784 equal = strcmp (strone, strtwo) == 0;
2793 * g_variant_compare:
2794 * @one: (type GVariant): a basic-typed #GVariant instance
2795 * @two: (type GVariant): a #GVariant instance of the same type
2797 * Compares @one and @two.
2799 * The types of @one and @two are #gconstpointer only to allow use of
2800 * this function with #GTree, #GPtrArray, etc. They must each be a
2803 * Comparison is only defined for basic types (ie: booleans, numbers,
2804 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2805 * ordered in the usual way. Strings are in ASCII lexographical order.
2807 * It is a programmer error to attempt to compare container values or
2808 * two values that have types that are not exactly equal. For example,
2809 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2810 * integer. Also note that this function is not particularly
2811 * well-behaved when it comes to comparison of doubles; in particular,
2812 * the handling of incomparable values (ie: NaN) is undefined.
2814 * If you only require an equality comparison, g_variant_equal() is more
2817 * Returns: negative value if a < b;
2819 * positive value if a > b.
2824 g_variant_compare (gconstpointer one,
2827 GVariant *a = (GVariant *) one;
2828 GVariant *b = (GVariant *) two;
2830 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2832 switch (g_variant_classify (a))
2834 case G_VARIANT_CLASS_BOOLEAN:
2835 return g_variant_get_boolean (a) -
2836 g_variant_get_boolean (b);
2838 case G_VARIANT_CLASS_BYTE:
2839 return ((gint) g_variant_get_byte (a)) -
2840 ((gint) g_variant_get_byte (b));
2842 case G_VARIANT_CLASS_INT16:
2843 return ((gint) g_variant_get_int16 (a)) -
2844 ((gint) g_variant_get_int16 (b));
2846 case G_VARIANT_CLASS_UINT16:
2847 return ((gint) g_variant_get_uint16 (a)) -
2848 ((gint) g_variant_get_uint16 (b));
2850 case G_VARIANT_CLASS_INT32:
2852 gint32 a_val = g_variant_get_int32 (a);
2853 gint32 b_val = g_variant_get_int32 (b);
2855 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2858 case G_VARIANT_CLASS_UINT32:
2860 guint32 a_val = g_variant_get_uint32 (a);
2861 guint32 b_val = g_variant_get_uint32 (b);
2863 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2866 case G_VARIANT_CLASS_INT64:
2868 gint64 a_val = g_variant_get_int64 (a);
2869 gint64 b_val = g_variant_get_int64 (b);
2871 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2874 case G_VARIANT_CLASS_UINT64:
2876 guint64 a_val = g_variant_get_uint64 (a);
2877 guint64 b_val = g_variant_get_uint64 (b);
2879 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2882 case G_VARIANT_CLASS_DOUBLE:
2884 gdouble a_val = g_variant_get_double (a);
2885 gdouble b_val = g_variant_get_double (b);
2887 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2890 case G_VARIANT_CLASS_STRING:
2891 case G_VARIANT_CLASS_OBJECT_PATH:
2892 case G_VARIANT_CLASS_SIGNATURE:
2893 return strcmp (g_variant_get_string (a, NULL),
2894 g_variant_get_string (b, NULL));
2897 g_return_val_if_fail (!g_variant_is_container (a), 0);
2898 g_assert_not_reached ();
2902 /* GVariantIter {{{1 */
2904 * GVariantIter: (skip)
2906 * #GVariantIter is an opaque data structure and can only be accessed
2907 * using the following functions.
2914 const gchar *loop_format;
2920 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2924 struct stack_iter iter;
2926 GVariant *value_ref;
2930 #define GVSI(i) ((struct stack_iter *) (i))
2931 #define GVHI(i) ((struct heap_iter *) (i))
2932 #define GVSI_MAGIC ((gsize) 3579507750u)
2933 #define GVHI_MAGIC ((gsize) 1450270775u)
2934 #define is_valid_iter(i) (i != NULL && \
2935 GVSI(i)->magic == GVSI_MAGIC)
2936 #define is_valid_heap_iter(i) (is_valid_iter(i) && \
2937 GVHI(i)->magic == GVHI_MAGIC)
2940 * g_variant_iter_new:
2941 * @value: a container #GVariant
2943 * Creates a heap-allocated #GVariantIter for iterating over the items
2946 * Use g_variant_iter_free() to free the return value when you no longer
2949 * A reference is taken to @value and will be released only when
2950 * g_variant_iter_free() is called.
2952 * Returns: (transfer full): a new heap-allocated #GVariantIter
2957 g_variant_iter_new (GVariant *value)
2961 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2962 GVHI(iter)->value_ref = g_variant_ref (value);
2963 GVHI(iter)->magic = GVHI_MAGIC;
2965 g_variant_iter_init (iter, value);
2971 * g_variant_iter_init: (skip)
2972 * @iter: a pointer to a #GVariantIter
2973 * @value: a container #GVariant
2975 * Initialises (without allocating) a #GVariantIter. @iter may be
2976 * completely uninitialised prior to this call; its old value is
2979 * The iterator remains valid for as long as @value exists, and need not
2980 * be freed in any way.
2982 * Returns: the number of items in @value
2987 g_variant_iter_init (GVariantIter *iter,
2990 GVSI(iter)->magic = GVSI_MAGIC;
2991 GVSI(iter)->value = value;
2992 GVSI(iter)->n = g_variant_n_children (value);
2994 GVSI(iter)->loop_format = NULL;
2996 return GVSI(iter)->n;
3000 * g_variant_iter_copy:
3001 * @iter: a #GVariantIter
3003 * Creates a new heap-allocated #GVariantIter to iterate over the
3004 * container that was being iterated over by @iter. Iteration begins on
3005 * the new iterator from the current position of the old iterator but
3006 * the two copies are independent past that point.
3008 * Use g_variant_iter_free() to free the return value when you no longer
3011 * A reference is taken to the container that @iter is iterating over
3012 * and will be related only when g_variant_iter_free() is called.
3014 * Returns: (transfer full): a new heap-allocated #GVariantIter
3019 g_variant_iter_copy (GVariantIter *iter)
3023 g_return_val_if_fail (is_valid_iter (iter), 0);
3025 copy = g_variant_iter_new (GVSI(iter)->value);
3026 GVSI(copy)->i = GVSI(iter)->i;
3032 * g_variant_iter_n_children:
3033 * @iter: a #GVariantIter
3035 * Queries the number of child items in the container that we are
3036 * iterating over. This is the total number of items -- not the number
3037 * of items remaining.
3039 * This function might be useful for preallocation of arrays.
3041 * Returns: the number of children in the container
3046 g_variant_iter_n_children (GVariantIter *iter)
3048 g_return_val_if_fail (is_valid_iter (iter), 0);
3050 return GVSI(iter)->n;
3054 * g_variant_iter_free:
3055 * @iter: (transfer full): a heap-allocated #GVariantIter
3057 * Frees a heap-allocated #GVariantIter. Only call this function on
3058 * iterators that were returned by g_variant_iter_new() or
3059 * g_variant_iter_copy().
3064 g_variant_iter_free (GVariantIter *iter)
3066 g_return_if_fail (is_valid_heap_iter (iter));
3068 g_variant_unref (GVHI(iter)->value_ref);
3069 GVHI(iter)->magic = 0;
3071 g_slice_free (struct heap_iter, GVHI(iter));
3075 * g_variant_iter_next_value:
3076 * @iter: a #GVariantIter
3078 * Gets the next item in the container. If no more items remain then
3079 * %NULL is returned.
3081 * Use g_variant_unref() to drop your reference on the return value when
3082 * you no longer need it.
3084 * Here is an example for iterating with g_variant_iter_next_value():
3085 * |[<!-- language="C" -->
3086 * // recursively iterate a container
3088 * iterate_container_recursive (GVariant *container)
3090 * GVariantIter iter;
3093 * g_variant_iter_init (&iter, container);
3094 * while ((child = g_variant_iter_next_value (&iter)))
3096 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3098 * if (g_variant_is_container (child))
3099 * iterate_container_recursive (child);
3101 * g_variant_unref (child);
3106 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3111 g_variant_iter_next_value (GVariantIter *iter)
3113 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3115 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3117 g_critical ("g_variant_iter_next_value: must not be called again "
3118 "after NULL has already been returned.");
3124 if (GVSI(iter)->i < GVSI(iter)->n)
3125 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3130 /* GVariantBuilder {{{1 */
3134 * A utility type for constructing container-type #GVariant instances.
3136 * This is an opaque structure and may only be accessed using the
3137 * following functions.
3139 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3140 * access it from more than one thread.
3143 struct stack_builder
3145 GVariantBuilder *parent;
3148 /* type constraint explicitly specified by 'type'.
3149 * for tuple types, this moves along as we add more items.
3151 const GVariantType *expected_type;
3153 /* type constraint implied by previous array item.
3155 const GVariantType *prev_item_type;
3157 /* constraints on the number of children. max = -1 for unlimited. */
3161 /* dynamically-growing pointer array */
3162 GVariant **children;
3163 gsize allocated_children;
3166 /* set to '1' if all items in the container will have the same type
3167 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3169 guint uniform_item_types : 1;
3171 /* set to '1' initially and changed to '0' if an untrusted value is
3179 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3183 GVariantBuilder builder;
3189 #define GVSB(b) ((struct stack_builder *) (b))
3190 #define GVHB(b) ((struct heap_builder *) (b))
3191 #define GVSB_MAGIC ((gsize) 1033660112u)
3192 #define GVSB_MAGIC_PARTIAL ((gsize) 2942751021u)
3193 #define GVHB_MAGIC ((gsize) 3087242682u)
3194 #define is_valid_builder(b) (b != NULL && \
3195 GVSB(b)->magic == GVSB_MAGIC)
3196 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3198 /* Just to make sure that by adding a union to GVariantBuilder, we
3199 * didn't accidentally change ABI. */
3200 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3203 ensure_valid_builder (GVariantBuilder *builder)
3205 if (is_valid_builder (builder))
3207 if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3209 static GVariantBuilder cleared_builder;
3211 /* Make sure that only first two fields were set and the rest is
3212 * zeroed to avoid messing up the builder that had parent
3213 * address equal to GVSB_MAGIC_PARTIAL. */
3214 if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3217 g_variant_builder_init (builder, builder->u.s.type);
3219 return is_valid_builder (builder);
3223 * g_variant_builder_new:
3224 * @type: a container type
3226 * Allocates and initialises a new #GVariantBuilder.
3228 * You should call g_variant_builder_unref() on the return value when it
3229 * is no longer needed. The memory will not be automatically freed by
3232 * In most cases it is easier to place a #GVariantBuilder directly on
3233 * the stack of the calling function and initialise it with
3234 * g_variant_builder_init().
3236 * Returns: (transfer full): a #GVariantBuilder
3241 g_variant_builder_new (const GVariantType *type)
3243 GVariantBuilder *builder;
3245 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3246 g_variant_builder_init (builder, type);
3247 GVHB(builder)->magic = GVHB_MAGIC;
3248 GVHB(builder)->ref_count = 1;
3254 * g_variant_builder_unref:
3255 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3257 * Decreases the reference count on @builder.
3259 * In the event that there are no more references, releases all memory
3260 * associated with the #GVariantBuilder.
3262 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3263 * things will happen.
3268 g_variant_builder_unref (GVariantBuilder *builder)
3270 g_return_if_fail (is_valid_heap_builder (builder));
3272 if (--GVHB(builder)->ref_count)
3275 g_variant_builder_clear (builder);
3276 GVHB(builder)->magic = 0;
3278 g_slice_free (struct heap_builder, GVHB(builder));
3282 * g_variant_builder_ref:
3283 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3285 * Increases the reference count on @builder.
3287 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3288 * things will happen.
3290 * Returns: (transfer full): a new reference to @builder
3295 g_variant_builder_ref (GVariantBuilder *builder)
3297 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3299 GVHB(builder)->ref_count++;
3305 * g_variant_builder_clear: (skip)
3306 * @builder: a #GVariantBuilder
3308 * Releases all memory associated with a #GVariantBuilder without
3309 * freeing the #GVariantBuilder structure itself.
3311 * It typically only makes sense to do this on a stack-allocated
3312 * #GVariantBuilder if you want to abort building the value part-way
3313 * through. This function need not be called if you call
3314 * g_variant_builder_end() and it also doesn't need to be called on
3315 * builders allocated with g_variant_builder_new() (see
3316 * g_variant_builder_unref() for that).
3318 * This function leaves the #GVariantBuilder structure set to all-zeros.
3319 * It is valid to call this function on either an initialised
3320 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3321 * to call this function on uninitialised memory.
3326 g_variant_builder_clear (GVariantBuilder *builder)
3330 if (GVSB(builder)->magic == 0)
3331 /* all-zeros or partial case */
3334 g_return_if_fail (ensure_valid_builder (builder));
3336 g_variant_type_free (GVSB(builder)->type);
3338 for (i = 0; i < GVSB(builder)->offset; i++)
3339 g_variant_unref (GVSB(builder)->children[i]);
3341 g_free (GVSB(builder)->children);
3343 if (GVSB(builder)->parent)
3345 g_variant_builder_clear (GVSB(builder)->parent);
3346 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3349 memset (builder, 0, sizeof (GVariantBuilder));
3353 * g_variant_builder_init: (skip)
3354 * @builder: a #GVariantBuilder
3355 * @type: a container type
3357 * Initialises a #GVariantBuilder structure.
3359 * @type must be non-%NULL. It specifies the type of container to
3360 * construct. It can be an indefinite type such as
3361 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3362 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3365 * After the builder is initialised, values are added using
3366 * g_variant_builder_add_value() or g_variant_builder_add().
3368 * After all the child values are added, g_variant_builder_end() frees
3369 * the memory associated with the builder and returns the #GVariant that
3372 * This function completely ignores the previous contents of @builder.
3373 * On one hand this means that it is valid to pass in completely
3374 * uninitialised memory. On the other hand, this means that if you are
3375 * initialising over top of an existing #GVariantBuilder you need to
3376 * first call g_variant_builder_clear() in order to avoid leaking
3379 * You must not call g_variant_builder_ref() or
3380 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3381 * with this function. If you ever pass a reference to a
3382 * #GVariantBuilder outside of the control of your own code then you
3383 * should assume that the person receiving that reference may try to use
3384 * reference counting; you should use g_variant_builder_new() instead of
3390 g_variant_builder_init (GVariantBuilder *builder,
3391 const GVariantType *type)
3393 g_return_if_fail (type != NULL);
3394 g_return_if_fail (g_variant_type_is_container (type));
3396 memset (builder, 0, sizeof (GVariantBuilder));
3398 GVSB(builder)->type = g_variant_type_copy (type);
3399 GVSB(builder)->magic = GVSB_MAGIC;
3400 GVSB(builder)->trusted = TRUE;
3402 switch (*(const gchar *) type)
3404 case G_VARIANT_CLASS_VARIANT:
3405 GVSB(builder)->uniform_item_types = TRUE;
3406 GVSB(builder)->allocated_children = 1;
3407 GVSB(builder)->expected_type = NULL;
3408 GVSB(builder)->min_items = 1;
3409 GVSB(builder)->max_items = 1;
3412 case G_VARIANT_CLASS_ARRAY:
3413 GVSB(builder)->uniform_item_types = TRUE;
3414 GVSB(builder)->allocated_children = 8;
3415 GVSB(builder)->expected_type =
3416 g_variant_type_element (GVSB(builder)->type);
3417 GVSB(builder)->min_items = 0;
3418 GVSB(builder)->max_items = -1;
3421 case G_VARIANT_CLASS_MAYBE:
3422 GVSB(builder)->uniform_item_types = TRUE;
3423 GVSB(builder)->allocated_children = 1;
3424 GVSB(builder)->expected_type =
3425 g_variant_type_element (GVSB(builder)->type);
3426 GVSB(builder)->min_items = 0;
3427 GVSB(builder)->max_items = 1;
3430 case G_VARIANT_CLASS_DICT_ENTRY:
3431 GVSB(builder)->uniform_item_types = FALSE;
3432 GVSB(builder)->allocated_children = 2;
3433 GVSB(builder)->expected_type =
3434 g_variant_type_key (GVSB(builder)->type);
3435 GVSB(builder)->min_items = 2;
3436 GVSB(builder)->max_items = 2;
3439 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3440 GVSB(builder)->uniform_item_types = FALSE;
3441 GVSB(builder)->allocated_children = 8;
3442 GVSB(builder)->expected_type = NULL;
3443 GVSB(builder)->min_items = 0;
3444 GVSB(builder)->max_items = -1;
3447 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3448 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3449 GVSB(builder)->expected_type =
3450 g_variant_type_first (GVSB(builder)->type);
3451 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3452 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3453 GVSB(builder)->uniform_item_types = FALSE;
3457 g_assert_not_reached ();
3460 GVSB(builder)->children = g_new (GVariant *,
3461 GVSB(builder)->allocated_children);
3465 g_variant_builder_make_room (struct stack_builder *builder)
3467 if (builder->offset == builder->allocated_children)
3469 builder->allocated_children *= 2;
3470 builder->children = g_renew (GVariant *, builder->children,
3471 builder->allocated_children);
3476 * g_variant_builder_add_value:
3477 * @builder: a #GVariantBuilder
3478 * @value: a #GVariant
3480 * Adds @value to @builder.
3482 * It is an error to call this function in any way that would create an
3483 * inconsistent value to be constructed. Some examples of this are
3484 * putting different types of items into an array, putting the wrong
3485 * types or number of items in a tuple, putting more than one value into
3488 * If @value is a floating reference (see g_variant_ref_sink()),
3489 * the @builder instance takes ownership of @value.
3494 g_variant_builder_add_value (GVariantBuilder *builder,
3497 g_return_if_fail (ensure_valid_builder (builder));
3498 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3499 g_return_if_fail (!GVSB(builder)->expected_type ||
3500 g_variant_is_of_type (value,
3501 GVSB(builder)->expected_type));
3502 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3503 g_variant_is_of_type (value,
3504 GVSB(builder)->prev_item_type));
3506 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3508 if (!GVSB(builder)->uniform_item_types)
3510 /* advance our expected type pointers */
3511 if (GVSB(builder)->expected_type)
3512 GVSB(builder)->expected_type =
3513 g_variant_type_next (GVSB(builder)->expected_type);
3515 if (GVSB(builder)->prev_item_type)
3516 GVSB(builder)->prev_item_type =
3517 g_variant_type_next (GVSB(builder)->prev_item_type);
3520 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3522 g_variant_builder_make_room (GVSB(builder));
3524 GVSB(builder)->children[GVSB(builder)->offset++] =
3525 g_variant_ref_sink (value);
3529 * g_variant_builder_open:
3530 * @builder: a #GVariantBuilder
3531 * @type: the #GVariantType of the container
3533 * Opens a subcontainer inside the given @builder. When done adding
3534 * items to the subcontainer, g_variant_builder_close() must be called. @type
3535 * is the type of the container: so to build a tuple of several values, @type
3536 * must include the tuple itself.
3538 * It is an error to call this function in any way that would cause an
3539 * inconsistent value to be constructed (ie: adding too many values or
3540 * a value of an incorrect type).
3542 * Example of building a nested variant:
3543 * |[<!-- language="C" -->
3544 * GVariantBuilder builder;
3545 * guint32 some_number = get_number ();
3546 * g_autoptr (GHashTable) some_dict = get_dict ();
3547 * GHashTableIter iter;
3549 * const GVariant *value;
3550 * g_autoptr (GVariant) output = NULL;
3552 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3553 * g_variant_builder_add (&builder, "u", some_number);
3554 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3556 * g_hash_table_iter_init (&iter, some_dict);
3557 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3559 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3560 * g_variant_builder_add (&builder, "s", key);
3561 * g_variant_builder_add (&builder, "v", value);
3562 * g_variant_builder_close (&builder);
3565 * g_variant_builder_close (&builder);
3567 * output = g_variant_builder_end (&builder);
3573 g_variant_builder_open (GVariantBuilder *builder,
3574 const GVariantType *type)
3576 GVariantBuilder *parent;
3578 g_return_if_fail (ensure_valid_builder (builder));
3579 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3580 g_return_if_fail (!GVSB(builder)->expected_type ||
3581 g_variant_type_is_subtype_of (type,
3582 GVSB(builder)->expected_type));
3583 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3584 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3587 parent = g_slice_dup (GVariantBuilder, builder);
3588 g_variant_builder_init (builder, type);
3589 GVSB(builder)->parent = parent;
3591 /* push the prev_item_type down into the subcontainer */
3592 if (GVSB(parent)->prev_item_type)
3594 if (!GVSB(builder)->uniform_item_types)
3595 /* tuples and dict entries */
3596 GVSB(builder)->prev_item_type =
3597 g_variant_type_first (GVSB(parent)->prev_item_type);
3599 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3600 /* maybes and arrays */
3601 GVSB(builder)->prev_item_type =
3602 g_variant_type_element (GVSB(parent)->prev_item_type);
3607 * g_variant_builder_close:
3608 * @builder: a #GVariantBuilder
3610 * Closes the subcontainer inside the given @builder that was opened by
3611 * the most recent call to g_variant_builder_open().
3613 * It is an error to call this function in any way that would create an
3614 * inconsistent value to be constructed (ie: too few values added to the
3620 g_variant_builder_close (GVariantBuilder *builder)
3622 GVariantBuilder *parent;
3624 g_return_if_fail (ensure_valid_builder (builder));
3625 g_return_if_fail (GVSB(builder)->parent != NULL);
3627 parent = GVSB(builder)->parent;
3628 GVSB(builder)->parent = NULL;
3630 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3633 g_slice_free (GVariantBuilder, parent);
3637 * g_variant_make_maybe_type:
3638 * @element: a #GVariant
3640 * Return the type of a maybe containing @element.
3642 static GVariantType *
3643 g_variant_make_maybe_type (GVariant *element)
3645 return g_variant_type_new_maybe (g_variant_get_type (element));
3649 * g_variant_make_array_type:
3650 * @element: a #GVariant
3652 * Return the type of an array containing @element.
3654 static GVariantType *
3655 g_variant_make_array_type (GVariant *element)
3657 return g_variant_type_new_array (g_variant_get_type (element));
3661 * g_variant_builder_end:
3662 * @builder: a #GVariantBuilder
3664 * Ends the builder process and returns the constructed value.
3666 * It is not permissible to use @builder in any way after this call
3667 * except for reference counting operations (in the case of a
3668 * heap-allocated #GVariantBuilder) or by reinitialising it with
3669 * g_variant_builder_init() (in the case of stack-allocated). This
3670 * means that for the stack-allocated builders there is no need to
3671 * call g_variant_builder_clear() after the call to
3672 * g_variant_builder_end().
3674 * It is an error to call this function in any way that would create an
3675 * inconsistent value to be constructed (ie: insufficient number of
3676 * items added to a container with a specific number of children
3677 * required). It is also an error to call this function if the builder
3678 * was created with an indefinite array or maybe type and no children
3679 * have been added; in this case it is impossible to infer the type of
3682 * Returns: (transfer none): a new, floating, #GVariant
3687 g_variant_builder_end (GVariantBuilder *builder)
3689 GVariantType *my_type;
3692 g_return_val_if_fail (ensure_valid_builder (builder), NULL);
3693 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3695 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3696 GVSB(builder)->prev_item_type != NULL ||
3697 g_variant_type_is_definite (GVSB(builder)->type),
3700 if (g_variant_type_is_definite (GVSB(builder)->type))
3701 my_type = g_variant_type_copy (GVSB(builder)->type);
3703 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3704 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3706 else if (g_variant_type_is_array (GVSB(builder)->type))
3707 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3709 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3710 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3711 GVSB(builder)->offset);
3713 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3714 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3715 GVSB(builder)->children[1]);
3717 g_assert_not_reached ();
3719 value = g_variant_new_from_children (my_type,
3720 g_renew (GVariant *,
3721 GVSB(builder)->children,
3722 GVSB(builder)->offset),
3723 GVSB(builder)->offset,
3724 GVSB(builder)->trusted);
3725 GVSB(builder)->children = NULL;
3726 GVSB(builder)->offset = 0;
3728 g_variant_builder_clear (builder);
3729 g_variant_type_free (my_type);
3734 /* GVariantDict {{{1 */
3739 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3741 * It can be used for doing a sequence of dictionary lookups in an
3742 * efficient way on an existing #GVariant dictionary or it can be used
3743 * to construct new dictionaries with a hashtable-like interface. It
3744 * can also be used for taking existing dictionaries and modifying them
3745 * in order to create new ones.
3747 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3750 * It is possible to use #GVariantDict allocated on the stack or on the
3751 * heap. When using a stack-allocated #GVariantDict, you begin with a
3752 * call to g_variant_dict_init() and free the resources with a call to
3753 * g_variant_dict_clear().
3755 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3756 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3757 * and g_variant_dict_unref().
3759 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3760 * dictionary-type #GVariant. When used with stack-allocated instances,
3761 * this also implicitly frees all associated memory, but for
3762 * heap-allocated instances, you must still call g_variant_dict_unref()
3765 * You will typically want to use a heap-allocated #GVariantDict when
3766 * you expose it as part of an API. For most other uses, the
3767 * stack-allocated form will be more convenient.
3769 * Consider the following two examples that do the same thing in each
3770 * style: take an existing dictionary and look up the "count" uint32
3771 * key, adding 1 to it if it is found, or returning an error if the
3772 * key is not found. Each returns the new dictionary as a floating
3775 * ## Using a stack-allocated GVariantDict
3777 * |[<!-- language="C" -->
3779 * add_to_count (GVariant *orig,
3782 * GVariantDict dict;
3785 * g_variant_dict_init (&dict, orig);
3786 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3788 * g_set_error (...);
3789 * g_variant_dict_clear (&dict);
3793 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3795 * return g_variant_dict_end (&dict);
3799 * ## Using heap-allocated GVariantDict
3801 * |[<!-- language="C" -->
3803 * add_to_count (GVariant *orig,
3806 * GVariantDict *dict;
3810 * dict = g_variant_dict_new (orig);
3812 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3814 * g_variant_dict_insert (dict, "count", "u", count + 1);
3815 * result = g_variant_dict_end (dict);
3819 * g_set_error (...);
3823 * g_variant_dict_unref (dict);
3837 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3841 struct stack_dict dict;
3846 #define GVSD(d) ((struct stack_dict *) (d))
3847 #define GVHD(d) ((struct heap_dict *) (d))
3848 #define GVSD_MAGIC ((gsize) 2579507750u)
3849 #define GVSD_MAGIC_PARTIAL ((gsize) 3488698669u)
3850 #define GVHD_MAGIC ((gsize) 2450270775u)
3851 #define is_valid_dict(d) (d != NULL && \
3852 GVSD(d)->magic == GVSD_MAGIC)
3853 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3855 /* Just to make sure that by adding a union to GVariantDict, we didn't
3856 * accidentally change ABI. */
3857 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3860 ensure_valid_dict (GVariantDict *dict)
3862 if (is_valid_dict (dict))
3864 if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3866 static GVariantDict cleared_dict;
3868 /* Make sure that only first two fields were set and the rest is
3869 * zeroed to avoid messing up the builder that had parent
3870 * address equal to GVSB_MAGIC_PARTIAL. */
3871 if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3874 g_variant_dict_init (dict, dict->u.s.asv);
3876 return is_valid_dict (dict);
3880 * g_variant_dict_new:
3881 * @from_asv: (nullable): the #GVariant with which to initialise the
3884 * Allocates and initialises a new #GVariantDict.
3886 * You should call g_variant_dict_unref() on the return value when it
3887 * is no longer needed. The memory will not be automatically freed by
3890 * In some cases it may be easier to place a #GVariantDict directly on
3891 * the stack of the calling function and initialise it with
3892 * g_variant_dict_init(). This is particularly useful when you are
3893 * using #GVariantDict to construct a #GVariant.
3895 * Returns: (transfer full): a #GVariantDict
3900 g_variant_dict_new (GVariant *from_asv)
3904 dict = g_slice_alloc (sizeof (struct heap_dict));
3905 g_variant_dict_init (dict, from_asv);
3906 GVHD(dict)->magic = GVHD_MAGIC;
3907 GVHD(dict)->ref_count = 1;
3913 * g_variant_dict_init: (skip)
3914 * @dict: a #GVariantDict
3915 * @from_asv: (nullable): the initial value for @dict
3917 * Initialises a #GVariantDict structure.
3919 * If @from_asv is given, it is used to initialise the dictionary.
3921 * This function completely ignores the previous contents of @dict. On
3922 * one hand this means that it is valid to pass in completely
3923 * uninitialised memory. On the other hand, this means that if you are
3924 * initialising over top of an existing #GVariantDict you need to first
3925 * call g_variant_dict_clear() in order to avoid leaking memory.
3927 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3928 * #GVariantDict that was initialised with this function. If you ever
3929 * pass a reference to a #GVariantDict outside of the control of your
3930 * own code then you should assume that the person receiving that
3931 * reference may try to use reference counting; you should use
3932 * g_variant_dict_new() instead of this function.
3937 g_variant_dict_init (GVariantDict *dict,
3944 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3945 GVSD(dict)->magic = GVSD_MAGIC;
3949 g_variant_iter_init (&iter, from_asv);
3950 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3951 g_hash_table_insert (GVSD(dict)->values, key, value);
3956 * g_variant_dict_lookup:
3957 * @dict: a #GVariantDict
3958 * @key: the key to look up in the dictionary
3959 * @format_string: a GVariant format string
3960 * @...: the arguments to unpack the value into
3962 * Looks up a value in a #GVariantDict.
3964 * This function is a wrapper around g_variant_dict_lookup_value() and
3965 * g_variant_get(). In the case that %NULL would have been returned,
3966 * this function returns %FALSE. Otherwise, it unpacks the returned
3967 * value and returns %TRUE.
3969 * @format_string determines the C types that are used for unpacking the
3970 * values and also determines if the values are copied or borrowed, see the
3971 * section on [GVariant format strings][gvariant-format-strings-pointers].
3973 * Returns: %TRUE if a value was unpacked
3978 g_variant_dict_lookup (GVariantDict *dict,
3980 const gchar *format_string,
3986 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
3987 g_return_val_if_fail (key != NULL, FALSE);
3988 g_return_val_if_fail (format_string != NULL, FALSE);
3990 value = g_hash_table_lookup (GVSD(dict)->values, key);
3992 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3995 va_start (ap, format_string);
3996 g_variant_get_va (value, format_string, NULL, &ap);
4003 * g_variant_dict_lookup_value:
4004 * @dict: a #GVariantDict
4005 * @key: the key to look up in the dictionary
4006 * @expected_type: (nullable): a #GVariantType, or %NULL
4008 * Looks up a value in a #GVariantDict.
4010 * If @key is not found in @dictionary, %NULL is returned.
4012 * The @expected_type string specifies what type of value is expected.
4013 * If the value associated with @key has a different type then %NULL is
4016 * If the key is found and the value has the correct type, it is
4017 * returned. If @expected_type was specified then any non-%NULL return
4018 * value will have this type.
4020 * Returns: (transfer full): the value of the dictionary key, or %NULL
4025 g_variant_dict_lookup_value (GVariantDict *dict,
4027 const GVariantType *expected_type)
4031 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4032 g_return_val_if_fail (key != NULL, NULL);
4034 result = g_hash_table_lookup (GVSD(dict)->values, key);
4036 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4037 return g_variant_ref (result);
4043 * g_variant_dict_contains:
4044 * @dict: a #GVariantDict
4045 * @key: the key to look up in the dictionary
4047 * Checks if @key exists in @dict.
4049 * Returns: %TRUE if @key is in @dict
4054 g_variant_dict_contains (GVariantDict *dict,
4057 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4058 g_return_val_if_fail (key != NULL, FALSE);
4060 return g_hash_table_contains (GVSD(dict)->values, key);
4064 * g_variant_dict_insert:
4065 * @dict: a #GVariantDict
4066 * @key: the key to insert a value for
4067 * @format_string: a #GVariant varargs format string
4068 * @...: arguments, as per @format_string
4070 * Inserts a value into a #GVariantDict.
4072 * This call is a convenience wrapper that is exactly equivalent to
4073 * calling g_variant_new() followed by g_variant_dict_insert_value().
4078 g_variant_dict_insert (GVariantDict *dict,
4080 const gchar *format_string,
4085 g_return_if_fail (ensure_valid_dict (dict));
4086 g_return_if_fail (key != NULL);
4087 g_return_if_fail (format_string != NULL);
4089 va_start (ap, format_string);
4090 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4095 * g_variant_dict_insert_value:
4096 * @dict: a #GVariantDict
4097 * @key: the key to insert a value for
4098 * @value: the value to insert
4100 * Inserts (or replaces) a key in a #GVariantDict.
4102 * @value is consumed if it is floating.
4107 g_variant_dict_insert_value (GVariantDict *dict,
4111 g_return_if_fail (ensure_valid_dict (dict));
4112 g_return_if_fail (key != NULL);
4113 g_return_if_fail (value != NULL);
4115 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4119 * g_variant_dict_remove:
4120 * @dict: a #GVariantDict
4121 * @key: the key to remove
4123 * Removes a key and its associated value from a #GVariantDict.
4125 * Returns: %TRUE if the key was found and removed
4130 g_variant_dict_remove (GVariantDict *dict,
4133 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4134 g_return_val_if_fail (key != NULL, FALSE);
4136 return g_hash_table_remove (GVSD(dict)->values, key);
4140 * g_variant_dict_clear:
4141 * @dict: a #GVariantDict
4143 * Releases all memory associated with a #GVariantDict without freeing
4144 * the #GVariantDict structure itself.
4146 * It typically only makes sense to do this on a stack-allocated
4147 * #GVariantDict if you want to abort building the value part-way
4148 * through. This function need not be called if you call
4149 * g_variant_dict_end() and it also doesn't need to be called on dicts
4150 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4153 * It is valid to call this function on either an initialised
4154 * #GVariantDict or one that was previously cleared by an earlier call
4155 * to g_variant_dict_clear() but it is not valid to call this function
4156 * on uninitialised memory.
4161 g_variant_dict_clear (GVariantDict *dict)
4163 if (GVSD(dict)->magic == 0)
4164 /* all-zeros case */
4167 g_return_if_fail (ensure_valid_dict (dict));
4169 g_hash_table_unref (GVSD(dict)->values);
4170 GVSD(dict)->values = NULL;
4172 GVSD(dict)->magic = 0;
4176 * g_variant_dict_end:
4177 * @dict: a #GVariantDict
4179 * Returns the current value of @dict as a #GVariant of type
4180 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4182 * It is not permissible to use @dict in any way after this call except
4183 * for reference counting operations (in the case of a heap-allocated
4184 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4185 * the case of stack-allocated).
4187 * Returns: (transfer none): a new, floating, #GVariant
4192 g_variant_dict_end (GVariantDict *dict)
4194 GVariantBuilder builder;
4195 GHashTableIter iter;
4196 gpointer key, value;
4198 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4200 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4202 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4203 while (g_hash_table_iter_next (&iter, &key, &value))
4204 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4206 g_variant_dict_clear (dict);
4208 return g_variant_builder_end (&builder);
4212 * g_variant_dict_ref:
4213 * @dict: a heap-allocated #GVariantDict
4215 * Increases the reference count on @dict.
4217 * Don't call this on stack-allocated #GVariantDict instances or bad
4218 * things will happen.
4220 * Returns: (transfer full): a new reference to @dict
4225 g_variant_dict_ref (GVariantDict *dict)
4227 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4229 GVHD(dict)->ref_count++;
4235 * g_variant_dict_unref:
4236 * @dict: (transfer full): a heap-allocated #GVariantDict
4238 * Decreases the reference count on @dict.
4240 * In the event that there are no more references, releases all memory
4241 * associated with the #GVariantDict.
4243 * Don't call this on stack-allocated #GVariantDict instances or bad
4244 * things will happen.
4249 g_variant_dict_unref (GVariantDict *dict)
4251 g_return_if_fail (is_valid_heap_dict (dict));
4253 if (--GVHD(dict)->ref_count == 0)
4255 g_variant_dict_clear (dict);
4256 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4261 /* Format strings {{{1 */
4263 * g_variant_format_string_scan:
4264 * @string: a string that may be prefixed with a format string
4265 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4267 * @endptr: (nullable) (default NULL): location to store the end pointer,
4270 * Checks the string pointed to by @string for starting with a properly
4271 * formed #GVariant varargs format string. If no valid format string is
4272 * found then %FALSE is returned.
4274 * If @string does start with a valid format string then %TRUE is
4275 * returned. If @endptr is non-%NULL then it is updated to point to the
4276 * first character after the format string.
4278 * If @limit is non-%NULL then @limit (and any character after it) will
4279 * not be accessed and the effect is otherwise equivalent to if the
4280 * character at @limit were nul.
4282 * See the section on [GVariant format strings][gvariant-format-strings].
4284 * Returns: %TRUE if there was a valid format string
4289 g_variant_format_string_scan (const gchar *string,
4291 const gchar **endptr)
4293 #define next_char() (string == limit ? '\0' : *string++)
4294 #define peek_char() (string == limit ? '\0' : *string)
4297 switch (next_char())
4299 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4300 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4301 case 'g': case 'v': case '*': case '?': case 'r':
4305 return g_variant_format_string_scan (string, limit, endptr);
4309 return g_variant_type_string_scan (string, limit, endptr);
4312 while (peek_char() != ')')
4313 if (!g_variant_format_string_scan (string, limit, &string))
4316 next_char(); /* consume ')' */
4326 if (c != 's' && c != 'o' && c != 'g')
4334 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4335 * The terminating null character is considered to be
4336 * part of the string.
4338 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4342 if (!g_variant_format_string_scan (string, limit, &string))
4345 if (next_char() != '}')
4351 if ((c = next_char()) == 'a')
4353 if ((c = next_char()) == '&')
4355 if ((c = next_char()) == 'a')
4357 if ((c = next_char()) == 'y')
4358 break; /* '^a&ay' */
4361 else if (c == 's' || c == 'o')
4362 break; /* '^a&s', '^a&o' */
4367 if ((c = next_char()) == 'y')
4371 else if (c == 's' || c == 'o')
4372 break; /* '^as', '^ao' */
4379 if ((c = next_char()) == 'a')
4381 if ((c = next_char()) == 'y')
4391 if (c != 's' && c != 'o' && c != 'g')
4410 * g_variant_check_format_string:
4411 * @value: a #GVariant
4412 * @format_string: a valid #GVariant format string
4413 * @copy_only: %TRUE to ensure the format string makes deep copies
4415 * Checks if calling g_variant_get() with @format_string on @value would
4416 * be valid from a type-compatibility standpoint. @format_string is
4417 * assumed to be a valid format string (from a syntactic standpoint).
4419 * If @copy_only is %TRUE then this function additionally checks that it
4420 * would be safe to call g_variant_unref() on @value immediately after
4421 * the call to g_variant_get() without invalidating the result. This is
4422 * only possible if deep copies are made (ie: there are no pointers to
4423 * the data inside of the soon-to-be-freed #GVariant instance). If this
4424 * check fails then a g_critical() is printed and %FALSE is returned.
4426 * This function is meant to be used by functions that wish to provide
4427 * varargs accessors to #GVariant values of uncertain values (eg:
4428 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4430 * Returns: %TRUE if @format_string is safe to use
4435 g_variant_check_format_string (GVariant *value,
4436 const gchar *format_string,
4439 const gchar *original_format = format_string;
4440 const gchar *type_string;
4442 /* Interesting factoid: assuming a format string is valid, it can be
4443 * converted to a type string by removing all '@' '&' and '^'
4446 * Instead of doing that, we can just skip those characters when
4447 * comparing it to the type string of @value.
4449 * For the copy-only case we can just drop the '&' from the list of
4450 * characters to skip over. A '&' will never appear in a type string
4451 * so we know that it won't be possible to return %TRUE if it is in a
4454 type_string = g_variant_get_type_string (value);
4456 while (*type_string || *format_string)
4458 gchar format = *format_string++;
4463 if G_UNLIKELY (copy_only)
4465 /* for the love of all that is good, please don't mark this string for translation... */
4466 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4467 "interface to validate the passed format string for type safety. The passed format "
4468 "(%s) contains a '&' character which would result in a pointer being returned to the "
4469 "data inside of a GVariant instance that may no longer exist by the time the function "
4470 "returns. Modify your code to use a format string without '&'.", original_format);
4477 /* ignore these 2 (or 3) */
4481 /* attempt to consume one of 'bynqiuxthdsog' */
4483 char s = *type_string++;
4485 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4491 /* ensure it's a tuple */
4492 if (*type_string != '(')
4497 /* consume a full type string for the '*' or 'r' */
4498 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4504 /* attempt to consume exactly one character equal to the format */
4505 if (format != *type_string++)
4514 * g_variant_format_string_scan_type:
4515 * @string: a string that may be prefixed with a format string
4516 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4518 * @endptr: (nullable) (default NULL): location to store the end pointer,
4521 * If @string starts with a valid format string then this function will
4522 * return the type that the format string corresponds to. Otherwise
4523 * this function returns %NULL.
4525 * Use g_variant_type_free() to free the return value when you no longer
4528 * This function is otherwise exactly like
4529 * g_variant_format_string_scan().
4531 * Returns: (nullable): a #GVariantType if there was a valid format string
4536 g_variant_format_string_scan_type (const gchar *string,
4538 const gchar **endptr)
4540 const gchar *my_end;
4547 if (!g_variant_format_string_scan (string, limit, endptr))
4550 dest = new = g_malloc (*endptr - string + 1);
4551 while (string != *endptr)
4553 if (*string != '@' && *string != '&' && *string != '^')
4559 return (GVariantType *) G_VARIANT_TYPE (new);
4563 valid_format_string (const gchar *format_string,
4567 const gchar *endptr;
4570 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4572 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4575 g_critical ("'%s' is not a valid GVariant format string",
4578 g_critical ("'%s' does not have a valid GVariant format "
4579 "string as a prefix", format_string);
4582 g_variant_type_free (type);
4587 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4592 fragment = g_strndup (format_string, endptr - format_string);
4593 typestr = g_variant_type_dup_string (type);
4595 g_critical ("the GVariant format string '%s' has a type of "
4596 "'%s' but the given value has a type of '%s'",
4597 fragment, typestr, g_variant_get_type_string (value));
4599 g_variant_type_free (type);
4606 g_variant_type_free (type);
4611 /* Variable Arguments {{{1 */
4612 /* We consider 2 main classes of format strings:
4614 * - recursive format strings
4615 * these are ones that result in recursion and the collection of
4616 * possibly more than one argument. Maybe types, tuples,
4617 * dictionary entries.
4619 * - leaf format string
4620 * these result in the collection of a single argument.
4622 * Leaf format strings are further subdivided into two categories:
4624 * - single non-null pointer ("nnp")
4625 * these either collect or return a single non-null pointer.
4628 * these collect or return something else (bool, number, etc).
4630 * Based on the above, the varargs handling code is split into 4 main parts:
4632 * - nnp handling code
4633 * - leaf handling code (which may invoke nnp code)
4634 * - generic handling code (may be recursive, may invoke leaf code)
4635 * - user-facing API (which invokes the generic code)
4637 * Each section implements some of the following functions:
4640 * collect the arguments for the format string as if
4641 * g_variant_new() had been called, but do nothing with them. used
4642 * for skipping over arguments when constructing a Nothing maybe
4646 * create a GVariant *
4649 * unpack a GVariant *
4651 * - free (nnp only):
4652 * free a previously allocated item
4656 g_variant_format_string_is_leaf (const gchar *str)
4658 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4662 g_variant_format_string_is_nnp (const gchar *str)
4664 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4665 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4666 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4669 /* Single non-null pointer ("nnp") {{{2 */
4671 g_variant_valist_free_nnp (const gchar *str,
4677 g_variant_iter_free (ptr);
4681 if (g_str_has_suffix (str, "y"))
4683 if (str[2] != 'a') /* '^a&ay', '^ay' */
4685 else if (str[1] == 'a') /* '^aay' */
4689 else if (str[2] != '&') /* '^as', '^ao' */
4691 else /* '^a&s', '^a&o' */
4705 g_variant_unref (ptr);
4712 g_assert_not_reached ();
4717 g_variant_scan_convenience (const gchar **str,
4740 g_variant_valist_new_nnp (const gchar **str,
4751 const GVariantType *type;
4754 value = g_variant_builder_end (ptr);
4755 type = g_variant_get_type (value);
4757 if G_UNLIKELY (!g_variant_type_is_array (type))
4758 g_error ("g_variant_new: expected array GVariantBuilder but "
4759 "the built value has type '%s'",
4760 g_variant_get_type_string (value));
4762 type = g_variant_type_element (type);
4764 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4766 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4767 g_error ("g_variant_new: expected GVariantBuilder array element "
4768 "type '%s' but the built value has element type '%s'",
4769 type_string, g_variant_get_type_string (value) + 1);
4770 g_free (type_string);
4773 g_variant_type_string_scan (*str, NULL, str);
4779 /* special case: NULL pointer for empty array */
4781 const GVariantType *type = (GVariantType *) *str;
4783 g_variant_type_string_scan (*str, NULL, str);
4785 if G_UNLIKELY (!g_variant_type_is_definite (type))
4786 g_error ("g_variant_new: NULL pointer given with indefinite "
4787 "array type; unable to determine which type of empty "
4788 "array to construct.");
4790 return g_variant_new_array (type, NULL, 0);
4797 value = g_variant_new_string (ptr);
4800 value = g_variant_new_string ("[Invalid UTF-8]");
4806 return g_variant_new_object_path (ptr);
4809 return g_variant_new_signature (ptr);
4817 type = g_variant_scan_convenience (str, &constant, &arrays);
4820 return g_variant_new_strv (ptr, -1);
4823 return g_variant_new_objv (ptr, -1);
4826 return g_variant_new_bytestring_array (ptr, -1);
4828 return g_variant_new_bytestring (ptr);
4832 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4834 gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4835 g_error ("g_variant_new: expected GVariant of type '%s' but "
4836 "received value has type '%s'",
4837 type_string, g_variant_get_type_string (ptr));
4838 g_free (type_string);
4841 g_variant_type_string_scan (*str, NULL, str);
4849 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4850 g_error ("g_variant_new: format string '?' expects basic-typed "
4851 "GVariant, but received value has type '%s'",
4852 g_variant_get_type_string (ptr));
4857 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4858 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4859 "GVariant, but received value has type '%s'",
4860 g_variant_get_type_string (ptr));
4865 return g_variant_new_variant (ptr);
4868 g_assert_not_reached ();
4873 g_variant_valist_get_nnp (const gchar **str,
4879 g_variant_type_string_scan (*str, NULL, str);
4880 return g_variant_iter_new (value);
4884 return (gchar *) g_variant_get_string (value, NULL);
4889 return g_variant_dup_string (value, NULL);
4897 type = g_variant_scan_convenience (str, &constant, &arrays);
4902 return g_variant_get_strv (value, NULL);
4904 return g_variant_dup_strv (value, NULL);
4907 else if (type == 'o')
4910 return g_variant_get_objv (value, NULL);
4912 return g_variant_dup_objv (value, NULL);
4915 else if (arrays > 1)
4918 return g_variant_get_bytestring_array (value, NULL);
4920 return g_variant_dup_bytestring_array (value, NULL);
4926 return (gchar *) g_variant_get_bytestring (value);
4928 return g_variant_dup_bytestring (value, NULL);
4933 g_variant_type_string_scan (*str, NULL, str);
4939 return g_variant_ref (value);
4942 return g_variant_get_variant (value);
4945 g_assert_not_reached ();
4951 g_variant_valist_skip_leaf (const gchar **str,
4954 if (g_variant_format_string_is_nnp (*str))
4956 g_variant_format_string_scan (*str, NULL, str);
4957 va_arg (*app, gpointer);
4975 va_arg (*app, guint64);
4979 va_arg (*app, gdouble);
4983 g_assert_not_reached ();
4988 g_variant_valist_new_leaf (const gchar **str,
4991 if (g_variant_format_string_is_nnp (*str))
4992 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4997 return g_variant_new_boolean (va_arg (*app, gboolean));
5000 return g_variant_new_byte (va_arg (*app, guint));
5003 return g_variant_new_int16 (va_arg (*app, gint));
5006 return g_variant_new_uint16 (va_arg (*app, guint));
5009 return g_variant_new_int32 (va_arg (*app, gint));
5012 return g_variant_new_uint32 (va_arg (*app, guint));
5015 return g_variant_new_int64 (va_arg (*app, gint64));
5018 return g_variant_new_uint64 (va_arg (*app, guint64));
5021 return g_variant_new_handle (va_arg (*app, gint));
5024 return g_variant_new_double (va_arg (*app, gdouble));
5027 g_assert_not_reached ();
5031 /* The code below assumes this */
5032 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5033 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5036 g_variant_valist_get_leaf (const gchar **str,
5041 gpointer ptr = va_arg (*app, gpointer);
5045 g_variant_format_string_scan (*str, NULL, str);
5049 if (g_variant_format_string_is_nnp (*str))
5051 gpointer *nnp = (gpointer *) ptr;
5053 if (free && *nnp != NULL)
5054 g_variant_valist_free_nnp (*str, *nnp);
5059 *nnp = g_variant_valist_get_nnp (str, value);
5061 g_variant_format_string_scan (*str, NULL, str);
5071 *(gboolean *) ptr = g_variant_get_boolean (value);
5075 *(guint8 *) ptr = g_variant_get_byte (value);
5079 *(gint16 *) ptr = g_variant_get_int16 (value);
5083 *(guint16 *) ptr = g_variant_get_uint16 (value);
5087 *(gint32 *) ptr = g_variant_get_int32 (value);
5091 *(guint32 *) ptr = g_variant_get_uint32 (value);
5095 *(gint64 *) ptr = g_variant_get_int64 (value);
5099 *(guint64 *) ptr = g_variant_get_uint64 (value);
5103 *(gint32 *) ptr = g_variant_get_handle (value);
5107 *(gdouble *) ptr = g_variant_get_double (value);
5116 *(guint8 *) ptr = 0;
5121 *(guint16 *) ptr = 0;
5128 *(guint32 *) ptr = 0;
5134 *(guint64 *) ptr = 0;
5139 g_assert_not_reached ();
5142 /* Generic (recursive) {{{2 */
5144 g_variant_valist_skip (const gchar **str,
5147 if (g_variant_format_string_is_leaf (*str))
5148 g_variant_valist_skip_leaf (str, app);
5150 else if (**str == 'm') /* maybe */
5154 if (!g_variant_format_string_is_nnp (*str))
5155 va_arg (*app, gboolean);
5157 g_variant_valist_skip (str, app);
5159 else /* tuple, dictionary entry */
5161 g_assert (**str == '(' || **str == '{');
5163 while (**str != ')' && **str != '}')
5164 g_variant_valist_skip (str, app);
5170 g_variant_valist_new (const gchar **str,
5173 if (g_variant_format_string_is_leaf (*str))
5174 return g_variant_valist_new_leaf (str, app);
5176 if (**str == 'm') /* maybe */
5178 GVariantType *type = NULL;
5179 GVariant *value = NULL;
5183 if (g_variant_format_string_is_nnp (*str))
5185 gpointer nnp = va_arg (*app, gpointer);
5188 value = g_variant_valist_new_nnp (str, nnp);
5190 type = g_variant_format_string_scan_type (*str, NULL, str);
5194 gboolean just = va_arg (*app, gboolean);
5197 value = g_variant_valist_new (str, app);
5200 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5201 g_variant_valist_skip (str, app);
5205 value = g_variant_new_maybe (type, value);
5208 g_variant_type_free (type);
5212 else /* tuple, dictionary entry */
5217 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5220 g_assert (**str == '{');
5221 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5225 while (**str != ')' && **str != '}')
5226 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5229 return g_variant_builder_end (&b);
5234 g_variant_valist_get (const gchar **str,
5239 if (g_variant_format_string_is_leaf (*str))
5240 g_variant_valist_get_leaf (str, value, free, app);
5242 else if (**str == 'm')
5247 value = g_variant_get_maybe (value);
5249 if (!g_variant_format_string_is_nnp (*str))
5251 gboolean *ptr = va_arg (*app, gboolean *);
5254 *ptr = value != NULL;
5257 g_variant_valist_get (str, value, free, app);
5260 g_variant_unref (value);
5263 else /* tuple, dictionary entry */
5267 g_assert (**str == '(' || **str == '{');
5270 while (**str != ')' && **str != '}')
5274 GVariant *child = g_variant_get_child_value (value, index++);
5275 g_variant_valist_get (str, child, free, app);
5276 g_variant_unref (child);
5279 g_variant_valist_get (str, NULL, free, app);
5285 /* User-facing API {{{2 */
5287 * g_variant_new: (skip)
5288 * @format_string: a #GVariant format string
5289 * @...: arguments, as per @format_string
5291 * Creates a new #GVariant instance.
5293 * Think of this function as an analogue to g_strdup_printf().
5295 * The type of the created instance and the arguments that are expected
5296 * by this function are determined by @format_string. See the section on
5297 * [GVariant format strings][gvariant-format-strings]. Please note that
5298 * the syntax of the format string is very likely to be extended in the
5301 * The first character of the format string must not be '*' '?' '@' or
5302 * 'r'; in essence, a new #GVariant must always be constructed by this
5303 * function (and not merely passed through it unmodified).
5305 * Note that the arguments must be of the correct width for their types
5306 * specified in @format_string. This can be achieved by casting them. See
5307 * the [GVariant varargs documentation][gvariant-varargs].
5309 * |[<!-- language="C" -->
5310 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5311 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5312 * GVariant *new_variant;
5314 * new_variant = g_variant_new ("(t^as)",
5315 * // This cast is required.
5316 * (guint64) some_flags,
5320 * Returns: a new floating #GVariant instance
5325 g_variant_new (const gchar *format_string,
5331 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5332 format_string[0] != '?' && format_string[0] != '@' &&
5333 format_string[0] != '*' && format_string[0] != 'r',
5336 va_start (ap, format_string);
5337 value = g_variant_new_va (format_string, NULL, &ap);
5344 * g_variant_new_va: (skip)
5345 * @format_string: a string that is prefixed with a format string
5346 * @endptr: (nullable) (default NULL): location to store the end pointer,
5348 * @app: a pointer to a #va_list
5350 * This function is intended to be used by libraries based on
5351 * #GVariant that want to provide g_variant_new()-like functionality
5354 * The API is more general than g_variant_new() to allow a wider range
5357 * @format_string must still point to a valid format string, but it only
5358 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5359 * non-%NULL then it is updated to point to the first character past the
5360 * end of the format string.
5362 * @app is a pointer to a #va_list. The arguments, according to
5363 * @format_string, are collected from this #va_list and the list is left
5364 * pointing to the argument following the last.
5366 * Note that the arguments in @app must be of the correct width for their
5367 * types specified in @format_string when collected into the #va_list.
5368 * See the [GVariant varargs documentation][gvariant-varargs].
5370 * These two generalisations allow mixing of multiple calls to
5371 * g_variant_new_va() and g_variant_get_va() within a single actual
5372 * varargs call by the user.
5374 * The return value will be floating if it was a newly created GVariant
5375 * instance (for example, if the format string was "(ii)"). In the case
5376 * that the format_string was '*', '?', 'r', or a format starting with
5377 * '@' then the collected #GVariant pointer will be returned unmodified,
5378 * without adding any additional references.
5380 * In order to behave correctly in all cases it is necessary for the
5381 * calling function to g_variant_ref_sink() the return result before
5382 * returning control to the user that originally provided the pointer.
5383 * At this point, the caller will have their own full reference to the
5384 * result. This can also be done by adding the result to a container,
5385 * or by passing it to another g_variant_new() call.
5387 * Returns: a new, usually floating, #GVariant
5392 g_variant_new_va (const gchar *format_string,
5393 const gchar **endptr,
5398 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5400 g_return_val_if_fail (app != NULL, NULL);
5402 value = g_variant_valist_new (&format_string, app);
5405 *endptr = format_string;
5411 * g_variant_get: (skip)
5412 * @value: a #GVariant instance
5413 * @format_string: a #GVariant format string
5414 * @...: arguments, as per @format_string
5416 * Deconstructs a #GVariant instance.
5418 * Think of this function as an analogue to scanf().
5420 * The arguments that are expected by this function are entirely
5421 * determined by @format_string. @format_string also restricts the
5422 * permissible types of @value. It is an error to give a value with
5423 * an incompatible type. See the section on
5424 * [GVariant format strings][gvariant-format-strings].
5425 * Please note that the syntax of the format string is very likely to be
5426 * extended in the future.
5428 * @format_string determines the C types that are used for unpacking
5429 * the values and also determines if the values are copied or borrowed,
5430 * see the section on
5431 * [GVariant format strings][gvariant-format-strings-pointers].
5436 g_variant_get (GVariant *value,
5437 const gchar *format_string,
5442 g_return_if_fail (value != NULL);
5443 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5445 /* if any direct-pointer-access formats are in use, flatten first */
5446 if (strchr (format_string, '&'))
5447 g_variant_get_data (value);
5449 va_start (ap, format_string);
5450 g_variant_get_va (value, format_string, NULL, &ap);
5455 * g_variant_get_va: (skip)
5456 * @value: a #GVariant
5457 * @format_string: a string that is prefixed with a format string
5458 * @endptr: (nullable) (default NULL): location to store the end pointer,
5460 * @app: a pointer to a #va_list
5462 * This function is intended to be used by libraries based on #GVariant
5463 * that want to provide g_variant_get()-like functionality to their
5466 * The API is more general than g_variant_get() to allow a wider range
5469 * @format_string must still point to a valid format string, but it only
5470 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5471 * non-%NULL then it is updated to point to the first character past the
5472 * end of the format string.
5474 * @app is a pointer to a #va_list. The arguments, according to
5475 * @format_string, are collected from this #va_list and the list is left
5476 * pointing to the argument following the last.
5478 * These two generalisations allow mixing of multiple calls to
5479 * g_variant_new_va() and g_variant_get_va() within a single actual
5480 * varargs call by the user.
5482 * @format_string determines the C types that are used for unpacking
5483 * the values and also determines if the values are copied or borrowed,
5484 * see the section on
5485 * [GVariant format strings][gvariant-format-strings-pointers].
5490 g_variant_get_va (GVariant *value,
5491 const gchar *format_string,
5492 const gchar **endptr,
5495 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5496 g_return_if_fail (value != NULL);
5497 g_return_if_fail (app != NULL);
5499 /* if any direct-pointer-access formats are in use, flatten first */
5500 if (strchr (format_string, '&'))
5501 g_variant_get_data (value);
5503 g_variant_valist_get (&format_string, value, FALSE, app);
5506 *endptr = format_string;
5509 /* Varargs-enabled Utility Functions {{{1 */
5512 * g_variant_builder_add: (skip)
5513 * @builder: a #GVariantBuilder
5514 * @format_string: a #GVariant varargs format string
5515 * @...: arguments, as per @format_string
5517 * Adds to a #GVariantBuilder.
5519 * This call is a convenience wrapper that is exactly equivalent to
5520 * calling g_variant_new() followed by g_variant_builder_add_value().
5522 * Note that the arguments must be of the correct width for their types
5523 * specified in @format_string. This can be achieved by casting them. See
5524 * the [GVariant varargs documentation][gvariant-varargs].
5526 * This function might be used as follows:
5528 * |[<!-- language="C" -->
5530 * make_pointless_dictionary (void)
5532 * GVariantBuilder builder;
5535 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5536 * for (i = 0; i < 16; i++)
5540 * sprintf (buf, "%d", i);
5541 * g_variant_builder_add (&builder, "{is}", i, buf);
5544 * return g_variant_builder_end (&builder);
5551 g_variant_builder_add (GVariantBuilder *builder,
5552 const gchar *format_string,
5558 va_start (ap, format_string);
5559 variant = g_variant_new_va (format_string, NULL, &ap);
5562 g_variant_builder_add_value (builder, variant);
5566 * g_variant_get_child: (skip)
5567 * @value: a container #GVariant
5568 * @index_: the index of the child to deconstruct
5569 * @format_string: a #GVariant format string
5570 * @...: arguments, as per @format_string
5572 * Reads a child item out of a container #GVariant instance and
5573 * deconstructs it according to @format_string. This call is
5574 * essentially a combination of g_variant_get_child_value() and
5577 * @format_string determines the C types that are used for unpacking
5578 * the values and also determines if the values are copied or borrowed,
5579 * see the section on
5580 * [GVariant format strings][gvariant-format-strings-pointers].
5585 g_variant_get_child (GVariant *value,
5587 const gchar *format_string,
5593 /* if any direct-pointer-access formats are in use, flatten first */
5594 if (strchr (format_string, '&'))
5595 g_variant_get_data (value);
5597 child = g_variant_get_child_value (value, index_);
5598 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5600 va_start (ap, format_string);
5601 g_variant_get_va (child, format_string, NULL, &ap);
5604 g_variant_unref (child);
5608 * g_variant_iter_next: (skip)
5609 * @iter: a #GVariantIter
5610 * @format_string: a GVariant format string
5611 * @...: the arguments to unpack the value into
5613 * Gets the next item in the container and unpacks it into the variable
5614 * argument list according to @format_string, returning %TRUE.
5616 * If no more items remain then %FALSE is returned.
5618 * All of the pointers given on the variable arguments list of this
5619 * function are assumed to point at uninitialised memory. It is the
5620 * responsibility of the caller to free all of the values returned by
5621 * the unpacking process.
5623 * Here is an example for memory management with g_variant_iter_next():
5624 * |[<!-- language="C" -->
5625 * // Iterates a dictionary of type 'a{sv}'
5627 * iterate_dictionary (GVariant *dictionary)
5629 * GVariantIter iter;
5633 * g_variant_iter_init (&iter, dictionary);
5634 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5636 * g_print ("Item '%s' has type '%s'\n", key,
5637 * g_variant_get_type_string (value));
5639 * // must free data for ourselves
5640 * g_variant_unref (value);
5646 * For a solution that is likely to be more convenient to C programmers
5647 * when dealing with loops, see g_variant_iter_loop().
5649 * @format_string determines the C types that are used for unpacking
5650 * the values and also determines if the values are copied or borrowed.
5652 * See the section on
5653 * [GVariant format strings][gvariant-format-strings-pointers].
5655 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5660 g_variant_iter_next (GVariantIter *iter,
5661 const gchar *format_string,
5666 value = g_variant_iter_next_value (iter);
5668 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5675 va_start (ap, format_string);
5676 g_variant_valist_get (&format_string, value, FALSE, &ap);
5679 g_variant_unref (value);
5682 return value != NULL;
5686 * g_variant_iter_loop: (skip)
5687 * @iter: a #GVariantIter
5688 * @format_string: a GVariant format string
5689 * @...: the arguments to unpack the value into
5691 * Gets the next item in the container and unpacks it into the variable
5692 * argument list according to @format_string, returning %TRUE.
5694 * If no more items remain then %FALSE is returned.
5696 * On the first call to this function, the pointers appearing on the
5697 * variable argument list are assumed to point at uninitialised memory.
5698 * On the second and later calls, it is assumed that the same pointers
5699 * will be given and that they will point to the memory as set by the
5700 * previous call to this function. This allows the previous values to
5701 * be freed, as appropriate.
5703 * This function is intended to be used with a while loop as
5704 * demonstrated in the following example. This function can only be
5705 * used when iterating over an array. It is only valid to call this
5706 * function with a string constant for the format string and the same
5707 * string constant must be used each time. Mixing calls to this
5708 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5709 * the same iterator causes undefined behavior.
5711 * If you break out of a such a while loop using g_variant_iter_loop() then
5712 * you must free or unreference all the unpacked values as you would with
5713 * g_variant_get(). Failure to do so will cause a memory leak.
5715 * Here is an example for memory management with g_variant_iter_loop():
5716 * |[<!-- language="C" -->
5717 * // Iterates a dictionary of type 'a{sv}'
5719 * iterate_dictionary (GVariant *dictionary)
5721 * GVariantIter iter;
5725 * g_variant_iter_init (&iter, dictionary);
5726 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5728 * g_print ("Item '%s' has type '%s'\n", key,
5729 * g_variant_get_type_string (value));
5731 * // no need to free 'key' and 'value' here
5732 * // unless breaking out of this loop
5737 * For most cases you should use g_variant_iter_next().
5739 * This function is really only useful when unpacking into #GVariant or
5740 * #GVariantIter in order to allow you to skip the call to
5741 * g_variant_unref() or g_variant_iter_free().
5743 * For example, if you are only looping over simple integer and string
5744 * types, g_variant_iter_next() is definitely preferred. For string
5745 * types, use the '&' prefix to avoid allocating any memory at all (and
5746 * thereby avoiding the need to free anything as well).
5748 * @format_string determines the C types that are used for unpacking
5749 * the values and also determines if the values are copied or borrowed.
5751 * See the section on
5752 * [GVariant format strings][gvariant-format-strings-pointers].
5754 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5760 g_variant_iter_loop (GVariantIter *iter,
5761 const gchar *format_string,
5764 gboolean first_time = GVSI(iter)->loop_format == NULL;
5768 g_return_val_if_fail (first_time ||
5769 format_string == GVSI(iter)->loop_format,
5774 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5775 GVSI(iter)->loop_format = format_string;
5777 if (strchr (format_string, '&'))
5778 g_variant_get_data (GVSI(iter)->value);
5781 value = g_variant_iter_next_value (iter);
5783 g_return_val_if_fail (!first_time ||
5784 valid_format_string (format_string, TRUE, value),
5787 va_start (ap, format_string);
5788 g_variant_valist_get (&format_string, value, !first_time, &ap);
5792 g_variant_unref (value);
5794 return value != NULL;
5797 /* Serialised data {{{1 */
5799 g_variant_deep_copy (GVariant *value)
5801 switch (g_variant_classify (value))
5803 case G_VARIANT_CLASS_MAYBE:
5804 case G_VARIANT_CLASS_ARRAY:
5805 case G_VARIANT_CLASS_TUPLE:
5806 case G_VARIANT_CLASS_DICT_ENTRY:
5807 case G_VARIANT_CLASS_VARIANT:
5809 GVariantBuilder builder;
5813 g_variant_builder_init (&builder, g_variant_get_type (value));
5814 g_variant_iter_init (&iter, value);
5816 while ((child = g_variant_iter_next_value (&iter)))
5818 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5819 g_variant_unref (child);
5822 return g_variant_builder_end (&builder);
5825 case G_VARIANT_CLASS_BOOLEAN:
5826 return g_variant_new_boolean (g_variant_get_boolean (value));
5828 case G_VARIANT_CLASS_BYTE:
5829 return g_variant_new_byte (g_variant_get_byte (value));
5831 case G_VARIANT_CLASS_INT16:
5832 return g_variant_new_int16 (g_variant_get_int16 (value));
5834 case G_VARIANT_CLASS_UINT16:
5835 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5837 case G_VARIANT_CLASS_INT32:
5838 return g_variant_new_int32 (g_variant_get_int32 (value));
5840 case G_VARIANT_CLASS_UINT32:
5841 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5843 case G_VARIANT_CLASS_INT64:
5844 return g_variant_new_int64 (g_variant_get_int64 (value));
5846 case G_VARIANT_CLASS_UINT64:
5847 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5849 case G_VARIANT_CLASS_HANDLE:
5850 return g_variant_new_handle (g_variant_get_handle (value));
5852 case G_VARIANT_CLASS_DOUBLE:
5853 return g_variant_new_double (g_variant_get_double (value));
5855 case G_VARIANT_CLASS_STRING:
5856 return g_variant_new_string (g_variant_get_string (value, NULL));
5858 case G_VARIANT_CLASS_OBJECT_PATH:
5859 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5861 case G_VARIANT_CLASS_SIGNATURE:
5862 return g_variant_new_signature (g_variant_get_string (value, NULL));
5865 g_assert_not_reached ();
5869 * g_variant_get_normal_form:
5870 * @value: a #GVariant
5872 * Gets a #GVariant instance that has the same value as @value and is
5873 * trusted to be in normal form.
5875 * If @value is already trusted to be in normal form then a new
5876 * reference to @value is returned.
5878 * If @value is not already trusted, then it is scanned to check if it
5879 * is in normal form. If it is found to be in normal form then it is
5880 * marked as trusted and a new reference to it is returned.
5882 * If @value is found not to be in normal form then a new trusted
5883 * #GVariant is created with the same value as @value.
5885 * It makes sense to call this function if you've received #GVariant
5886 * data from untrusted sources and you want to ensure your serialised
5887 * output is definitely in normal form.
5889 * If @value is already in normal form, a new reference will be returned
5890 * (which will be floating if @value is floating). If it is not in normal form,
5891 * the newly created #GVariant will be returned with a single non-floating
5892 * reference. Typically, g_variant_take_ref() should be called on the return
5893 * value from this function to guarantee ownership of a single non-floating
5896 * Returns: (transfer full): a trusted #GVariant
5901 g_variant_get_normal_form (GVariant *value)
5905 if (g_variant_is_normal_form (value))
5906 return g_variant_ref (value);
5908 trusted = g_variant_deep_copy (value);
5909 g_assert (g_variant_is_trusted (trusted));
5911 return g_variant_ref_sink (trusted);
5915 * g_variant_byteswap:
5916 * @value: a #GVariant
5918 * Performs a byteswapping operation on the contents of @value. The
5919 * result is that all multi-byte numeric data contained in @value is
5920 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5921 * integers as well as file handles and double precision floating point
5924 * This function is an identity mapping on any value that does not
5925 * contain multi-byte numeric data. That include strings, booleans,
5926 * bytes and containers containing only these things (recursively).
5928 * The returned value is always in normal form and is marked as trusted.
5930 * Returns: (transfer full): the byteswapped form of @value
5935 g_variant_byteswap (GVariant *value)
5937 GVariantTypeInfo *type_info;
5941 type_info = g_variant_get_type_info (value);
5943 g_variant_type_info_query (type_info, &alignment, NULL);
5946 /* (potentially) contains multi-byte numeric data */
5948 GVariantSerialised serialised;
5952 trusted = g_variant_get_normal_form (value);
5953 serialised.type_info = g_variant_get_type_info (trusted);
5954 serialised.size = g_variant_get_size (trusted);
5955 serialised.data = g_malloc (serialised.size);
5956 serialised.depth = g_variant_get_depth (trusted);
5957 g_variant_store (trusted, serialised.data);
5958 g_variant_unref (trusted);
5960 g_variant_serialised_byteswap (serialised);
5962 bytes = g_bytes_new_take (serialised.data, serialised.size);
5963 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5964 g_bytes_unref (bytes);
5967 /* contains no multi-byte data */
5970 return g_variant_ref_sink (new);
5974 * g_variant_new_from_data:
5975 * @type: a definite #GVariantType
5976 * @data: (array length=size) (element-type guint8): the serialised data
5977 * @size: the size of @data
5978 * @trusted: %TRUE if @data is definitely in normal form
5979 * @notify: (scope async): function to call when @data is no longer needed
5980 * @user_data: data for @notify
5982 * Creates a new #GVariant instance from serialised data.
5984 * @type is the type of #GVariant instance that will be constructed.
5985 * The interpretation of @data depends on knowing the type.
5987 * @data is not modified by this function and must remain valid with an
5988 * unchanging value until such a time as @notify is called with
5989 * @user_data. If the contents of @data change before that time then
5990 * the result is undefined.
5992 * If @data is trusted to be serialised data in normal form then
5993 * @trusted should be %TRUE. This applies to serialised data created
5994 * within this process or read from a trusted location on the disk (such
5995 * as a file installed in /usr/lib alongside your application). You
5996 * should set trusted to %FALSE if @data is read from the network, a
5997 * file in the user's home directory, etc.
5999 * If @data was not stored in this machine's native endianness, any multi-byte
6000 * numeric values in the returned variant will also be in non-native
6001 * endianness. g_variant_byteswap() can be used to recover the original values.
6003 * @notify will be called with @user_data when @data is no longer
6004 * needed. The exact time of this call is unspecified and might even be
6005 * before this function returns.
6007 * Note: @data must be backed by memory that is aligned appropriately for the
6008 * @type being loaded. Otherwise this function will internally create a copy of
6009 * the memory (since GLib 2.60) or (in older versions) fail and exit the
6012 * Returns: (transfer none): a new floating #GVariant of type @type
6017 g_variant_new_from_data (const GVariantType *type,
6021 GDestroyNotify notify,
6027 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6028 g_return_val_if_fail (data != NULL || size == 0, NULL);
6031 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6033 bytes = g_bytes_new_static (data, size);
6035 value = g_variant_new_from_bytes (type, bytes, trusted);
6036 g_bytes_unref (bytes);
6042 /* vim:set foldmethod=marker: */