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 of the licence, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: Ryan Lortie <desrt@desrt.ca>
25 #include <glib/gvariant-serialiser.h>
26 #include "gvariant-internal.h"
27 #include <glib/gvariant-core.h>
28 #include <glib/gtestutils.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gslice.h>
31 #include <glib/ghash.h>
32 #include <glib/gmem.h>
40 * @short_description: strongly typed value datatype
41 * @see_also: GVariantType
43 * #GVariant is a variant datatype; it stores a value along with
44 * information about the type of that value. The range of possible
45 * values is determined by the type. The type system used by #GVariant
48 * #GVariant instances always have a type and a value (which are given
49 * at construction time). The type and value of a #GVariant instance
50 * can never change other than by the #GVariant itself being
51 * destroyed. A #GVariant cannot contain a pointer.
53 * #GVariant is reference counted using g_variant_ref() and
54 * g_variant_unref(). #GVariant also has floating reference counts --
55 * see g_variant_ref_sink().
57 * #GVariant is completely threadsafe. A #GVariant instance can be
58 * concurrently accessed in any way from any number of threads without
61 * #GVariant is heavily optimised for dealing with data in serialised
62 * form. It works particularly well with data located in memory-mapped
63 * files. It can perform nearly all deserialisation operations in a
64 * small constant time, usually touching only a single memory page.
65 * Serialised #GVariant data can also be sent over the network.
67 * #GVariant is largely compatible with D-Bus. Almost all types of
68 * #GVariant instances can be sent over D-Bus. See #GVariantType for
69 * exceptions. (However, #GVariant's serialisation format is not the same
70 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
71 * in the gio library, for those.)
73 * For space-efficiency, the #GVariant serialisation format does not
74 * automatically include the variant's type or endianness, which must
75 * either be implied from context (such as knowledge that a particular
76 * file format always contains a little-endian %G_VARIANT_TYPE_VARIANT)
77 * or supplied out-of-band (for instance, a type and/or endianness
78 * indicator could be placed at the beginning of a file, network message
81 * A #GVariant's size is limited mainly by any lower level operating
82 * system constraints, such as the number of bits in #gsize. For
83 * example, it is reasonable to have a 2GB file mapped into memory
84 * with #GMappedFile, and call g_variant_new_from_data() on it.
86 * For convenience to C programmers, #GVariant features powerful
87 * varargs-based value construction and destruction. This feature is
88 * designed to be embedded in other libraries.
90 * There is a Python-inspired text language for describing #GVariant
91 * values. #GVariant includes a printer for this language and a parser
92 * with type inferencing.
95 * <title>Memory Use</title>
97 * #GVariant tries to be quite efficient with respect to memory use.
98 * This section gives a rough idea of how much memory is used by the
99 * current implementation. The information here is subject to change
103 * The memory allocated by #GVariant can be grouped into 4 broad
104 * purposes: memory for serialised data, memory for the type
105 * information cache, buffer management memory and memory for the
106 * #GVariant structure itself.
108 * <refsect3 id="gvariant-serialised-data-memory">
109 * <title>Serialised Data Memory</title>
111 * This is the memory that is used for storing GVariant data in
112 * serialised form. This is what would be sent over the network or
113 * what would end up on disk.
116 * The amount of memory required to store a boolean is 1 byte. 16,
117 * 32 and 64 bit integers and double precision floating point numbers
118 * use their "natural" size. Strings (including object path and
119 * signature strings) are stored with a nul terminator, and as such
120 * use the length of the string plus 1 byte.
123 * Maybe types use no space at all to represent the null value and
124 * use the same amount of space (sometimes plus one byte) as the
125 * equivalent non-maybe-typed value to represent the non-null case.
128 * Arrays use the amount of space required to store each of their
129 * members, concatenated. Additionally, if the items stored in an
130 * array are not of a fixed-size (ie: strings, other arrays, etc)
131 * then an additional framing offset is stored for each item. The
132 * size of this offset is either 1, 2 or 4 bytes depending on the
133 * overall size of the container. Additionally, extra padding bytes
134 * are added as required for alignment of child values.
137 * Tuples (including dictionary entries) use the amount of space
138 * required to store each of their members, concatenated, plus one
139 * framing offset (as per arrays) for each non-fixed-sized item in
140 * the tuple, except for the last one. Additionally, extra padding
141 * bytes are added as required for alignment of child values.
144 * Variants use the same amount of space as the item inside of the
145 * variant, plus 1 byte, plus the length of the type string for the
146 * item inside the variant.
149 * As an example, consider a dictionary mapping strings to variants.
150 * In the case that the dictionary is empty, 0 bytes are required for
154 * If we add an item "width" that maps to the int32 value of 500 then
155 * we will use 4 byte to store the int32 (so 6 for the variant
156 * containing it) and 6 bytes for the string. The variant must be
157 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
158 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
159 * for the dictionary entry. An additional 1 byte is added to the
160 * array as a framing offset making a total of 15 bytes.
163 * If we add another entry, "title" that maps to a nullable string
164 * that happens to have a value of null, then we use 0 bytes for the
165 * null value (and 3 bytes for the variant to contain it along with
166 * its type string) plus 6 bytes for the string. Again, we need 2
167 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
170 * We now require extra padding between the two items in the array.
171 * After the 14 bytes of the first item, that's 2 bytes required. We
172 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
173 * + 2 = 29 bytes to encode the entire two-item dictionary.
177 * <title>Type Information Cache</title>
179 * For each GVariant type that currently exists in the program a type
180 * information structure is kept in the type information cache. The
181 * type information structure is required for rapid deserialisation.
184 * Continuing with the above example, if a #GVariant exists with the
185 * type "a{sv}" then a type information struct will exist for
186 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
187 * will share the same type information. Additionally, all
188 * single-digit types are stored in read-only static memory and do
189 * not contribute to the writable memory footprint of a program using
193 * Aside from the type information structures stored in read-only
194 * memory, there are two forms of type information. One is used for
195 * container types where there is a single element type: arrays and
196 * maybe types. The other is used for container types where there
197 * are multiple element types: tuples and dictionary entries.
200 * Array type info structures are 6 * sizeof (void *), plus the
201 * memory required to store the type string itself. This means that
202 * on 32-bit systems, the cache entry for "a{sv}" would require 30
203 * bytes of memory (plus malloc overhead).
206 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
207 * sizeof (void *) for each item in the tuple, plus the memory
208 * required to store the type string itself. A 2-item tuple, for
209 * example, would have a type information structure that consumed
210 * writable memory in the size of 14 * sizeof (void *) (plus type
211 * string) This means that on 32-bit systems, the cache entry for
212 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
215 * This means that in total, for our "a{sv}" example, 91 bytes of
216 * type information would be allocated.
219 * The type information cache, additionally, uses a #GHashTable to
220 * store and lookup the cached items and stores a pointer to this
221 * hash table in static storage. The hash table is freed when there
222 * are zero items in the type cache.
225 * Although these sizes may seem large it is important to remember
226 * that a program will probably only have a very small number of
227 * different types of values in it and that only one type information
228 * structure is required for many different values of the same type.
232 * <title>Buffer Management Memory</title>
234 * #GVariant uses an internal buffer management structure to deal
235 * with the various different possible sources of serialised data
236 * that it uses. The buffer is responsible for ensuring that the
237 * correct call is made when the data is no longer in use by
238 * #GVariant. This may involve a g_free() or a g_slice_free() or
239 * even g_mapped_file_unref().
242 * One buffer management structure is used for each chunk of
243 * serialised data. The size of the buffer management structure is 4
244 * * (void *). On 32bit systems, that's 16 bytes.
248 * <title>GVariant structure</title>
250 * The size of a #GVariant structure is 6 * (void *). On 32 bit
251 * systems, that's 24 bytes.
254 * #GVariant structures only exist if they are explicitly created
255 * with API calls. For example, if a #GVariant is constructed out of
256 * serialised data for the example given above (with the dictionary)
257 * then although there are 9 individual values that comprise the
258 * entire dictionary (two keys, two values, two variants containing
259 * the values, two dictionary entries, plus the dictionary itself),
260 * only 1 #GVariant instance exists -- the one referring to the
264 * If calls are made to start accessing the other values then
265 * #GVariant instances will exist for those values only for as long
266 * as they are in use (ie: until you call g_variant_unref()). The
267 * type information is shared. The serialised data and the buffer
268 * management structure for that serialised data is shared by the
273 * <title>Summary</title>
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 byes 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
291 /* definition of GVariant structure is in gvariant-core.c */
293 /* this is a g_return_val_if_fail() for making
294 * sure a (GVariant *) has the required type.
296 #define TYPE_CHECK(value, TYPE, val) \
297 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
298 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
299 "g_variant_is_of_type (" #value \
304 /* Numeric Type Constructor/Getters {{{1 */
306 * g_variant_new_from_trusted:
307 * @type: the #GVariantType
308 * @data: the data to use
309 * @size: the size of @data
311 * Constructs a new trusted #GVariant instance from the provided data.
312 * This is used to implement g_variant_new_* for all the basic types.
314 * Returns: a new floating #GVariant
317 g_variant_new_from_trusted (const GVariantType *type,
324 bytes = g_bytes_new (data, size);
325 value = g_variant_new_from_bytes (type, bytes, TRUE);
326 g_bytes_unref (bytes);
332 * g_variant_new_boolean:
333 * @value: a #gboolean value
335 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
337 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
342 g_variant_new_boolean (gboolean value)
346 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
350 * g_variant_get_boolean:
351 * @value: a boolean #GVariant instance
353 * Returns the boolean value of @value.
355 * It is an error to call this function with a @value of any type
356 * other than %G_VARIANT_TYPE_BOOLEAN.
358 * Returns: %TRUE or %FALSE
363 g_variant_get_boolean (GVariant *value)
367 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
369 data = g_variant_get_data (value);
371 return data != NULL ? *data != 0 : FALSE;
374 /* the constructors and accessors for byte, int{16,32,64}, handles and
375 * doubles all look pretty much exactly the same, so we reduce
378 #define NUMERIC_TYPE(TYPE, type, ctype) \
379 GVariant *g_variant_new_##type (ctype value) { \
380 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
381 &value, sizeof value); \
383 ctype g_variant_get_##type (GVariant *value) { \
385 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
386 data = g_variant_get_data (value); \
387 return data != NULL ? *data : 0; \
392 * g_variant_new_byte:
393 * @value: a #guint8 value
395 * Creates a new byte #GVariant instance.
397 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
402 * g_variant_get_byte:
403 * @value: a byte #GVariant instance
405 * Returns the byte value of @value.
407 * It is an error to call this function with a @value of any type
408 * other than %G_VARIANT_TYPE_BYTE.
414 NUMERIC_TYPE (BYTE, byte, guchar)
417 * g_variant_new_int16:
418 * @value: a #gint16 value
420 * Creates a new int16 #GVariant instance.
422 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
427 * g_variant_get_int16:
428 * @value: a int16 #GVariant instance
430 * Returns the 16-bit signed integer value of @value.
432 * It is an error to call this function with a @value of any type
433 * other than %G_VARIANT_TYPE_INT16.
439 NUMERIC_TYPE (INT16, int16, gint16)
442 * g_variant_new_uint16:
443 * @value: a #guint16 value
445 * Creates a new uint16 #GVariant instance.
447 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
452 * g_variant_get_uint16:
453 * @value: a uint16 #GVariant instance
455 * Returns the 16-bit unsigned integer value of @value.
457 * It is an error to call this function with a @value of any type
458 * other than %G_VARIANT_TYPE_UINT16.
460 * Returns: a #guint16
464 NUMERIC_TYPE (UINT16, uint16, guint16)
467 * g_variant_new_int32:
468 * @value: a #gint32 value
470 * Creates a new int32 #GVariant instance.
472 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
477 * g_variant_get_int32:
478 * @value: a int32 #GVariant instance
480 * Returns the 32-bit signed integer value of @value.
482 * It is an error to call this function with a @value of any type
483 * other than %G_VARIANT_TYPE_INT32.
489 NUMERIC_TYPE (INT32, int32, gint32)
492 * g_variant_new_uint32:
493 * @value: a #guint32 value
495 * Creates a new uint32 #GVariant instance.
497 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
502 * g_variant_get_uint32:
503 * @value: a uint32 #GVariant instance
505 * Returns the 32-bit unsigned integer value of @value.
507 * It is an error to call this function with a @value of any type
508 * other than %G_VARIANT_TYPE_UINT32.
510 * Returns: a #guint32
514 NUMERIC_TYPE (UINT32, uint32, guint32)
517 * g_variant_new_int64:
518 * @value: a #gint64 value
520 * Creates a new int64 #GVariant instance.
522 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
527 * g_variant_get_int64:
528 * @value: a int64 #GVariant instance
530 * Returns the 64-bit signed integer value of @value.
532 * It is an error to call this function with a @value of any type
533 * other than %G_VARIANT_TYPE_INT64.
539 NUMERIC_TYPE (INT64, int64, gint64)
542 * g_variant_new_uint64:
543 * @value: a #guint64 value
545 * Creates a new uint64 #GVariant instance.
547 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
552 * g_variant_get_uint64:
553 * @value: a uint64 #GVariant instance
555 * Returns the 64-bit unsigned integer value of @value.
557 * It is an error to call this function with a @value of any type
558 * other than %G_VARIANT_TYPE_UINT64.
560 * Returns: a #guint64
564 NUMERIC_TYPE (UINT64, uint64, guint64)
567 * g_variant_new_handle:
568 * @value: a #gint32 value
570 * Creates a new handle #GVariant instance.
572 * By convention, handles are indexes into an array of file descriptors
573 * that are sent alongside a D-Bus message. If you're not interacting
574 * with D-Bus, you probably don't need them.
576 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
581 * g_variant_get_handle:
582 * @value: a handle #GVariant instance
584 * Returns the 32-bit signed integer value of @value.
586 * It is an error to call this function with a @value of any type other
587 * than %G_VARIANT_TYPE_HANDLE.
589 * By convention, handles are indexes into an array of file descriptors
590 * that are sent alongside a D-Bus message. If you're not interacting
591 * with D-Bus, you probably don't need them.
597 NUMERIC_TYPE (HANDLE, handle, gint32)
600 * g_variant_new_double:
601 * @value: a #gdouble floating point value
603 * Creates a new double #GVariant instance.
605 * Returns: (transfer none): a floating reference to a new double #GVariant instance
610 * g_variant_get_double:
611 * @value: a double #GVariant instance
613 * Returns the double precision floating point value of @value.
615 * It is an error to call this function with a @value of any type
616 * other than %G_VARIANT_TYPE_DOUBLE.
618 * Returns: a #gdouble
622 NUMERIC_TYPE (DOUBLE, double, gdouble)
624 /* Container type Constructor / Deconstructors {{{1 */
626 * g_variant_new_maybe:
627 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
628 * @child: (allow-none): the child value, or %NULL
630 * Depending on if @child is %NULL, either wraps @child inside of a
631 * maybe container or creates a Nothing instance for the given @type.
633 * At least one of @child_type and @child must be non-%NULL.
634 * If @child_type is non-%NULL then it must be a definite type.
635 * If they are both non-%NULL then @child_type must be the type
638 * If @child is a floating reference (see g_variant_ref_sink()), the new
639 * instance takes ownership of @child.
641 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
646 g_variant_new_maybe (const GVariantType *child_type,
649 GVariantType *maybe_type;
652 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
654 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
655 g_return_val_if_fail (child_type == NULL || child == NULL ||
656 g_variant_is_of_type (child, child_type),
659 if (child_type == NULL)
660 child_type = g_variant_get_type (child);
662 maybe_type = g_variant_type_new_maybe (child_type);
669 children = g_new (GVariant *, 1);
670 children[0] = g_variant_ref_sink (child);
671 trusted = g_variant_is_trusted (children[0]);
673 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
676 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
678 g_variant_type_free (maybe_type);
684 * g_variant_get_maybe:
685 * @value: a maybe-typed value
687 * Given a maybe-typed #GVariant instance, extract its value. If the
688 * value is Nothing, then this function returns %NULL.
690 * Returns: (allow-none) (transfer full): the contents of @value, or %NULL
695 g_variant_get_maybe (GVariant *value)
697 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
699 if (g_variant_n_children (value))
700 return g_variant_get_child_value (value, 0);
706 * g_variant_new_variant: (constructor)
707 * @value: a #GVariant instance
709 * Boxes @value. The result is a #GVariant instance representing a
710 * variant containing the original value.
712 * If @child is a floating reference (see g_variant_ref_sink()), the new
713 * instance takes ownership of @child.
715 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
720 g_variant_new_variant (GVariant *value)
722 g_return_val_if_fail (value != NULL, NULL);
724 g_variant_ref_sink (value);
726 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
727 g_memdup (&value, sizeof value),
728 1, g_variant_is_trusted (value));
732 * g_variant_get_variant:
733 * @value: a variant #GVariant instance
735 * Unboxes @value. The result is the #GVariant instance that was
736 * contained in @value.
738 * Returns: (transfer full): the item contained in the variant
743 g_variant_get_variant (GVariant *value)
745 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
747 return g_variant_get_child_value (value, 0);
751 * g_variant_new_array:
752 * @child_type: (allow-none): the element type of the new array
753 * @children: (allow-none) (array length=n_children): an array of
754 * #GVariant pointers, the children
755 * @n_children: the length of @children
757 * Creates a new #GVariant array from @children.
759 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
760 * child type is determined by inspecting the first element of the
761 * @children array. If @child_type is non-%NULL then it must be a
764 * The items of the array are taken from the @children array. No entry
765 * in the @children array may be %NULL.
767 * All items in the array must have the same type, which must be the
768 * same as @child_type, if given.
770 * If the @children are floating references (see g_variant_ref_sink()), the
771 * new instance takes ownership of them as if via g_variant_ref_sink().
773 * Returns: (transfer none): a floating reference to a new #GVariant array
778 g_variant_new_array (const GVariantType *child_type,
779 GVariant * const *children,
782 GVariantType *array_type;
783 GVariant **my_children;
788 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
789 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
790 g_return_val_if_fail (child_type == NULL ||
791 g_variant_type_is_definite (child_type), NULL);
793 my_children = g_new (GVariant *, n_children);
796 if (child_type == NULL)
797 child_type = g_variant_get_type (children[0]);
798 array_type = g_variant_type_new_array (child_type);
800 for (i = 0; i < n_children; i++)
802 TYPE_CHECK (children[i], child_type, NULL);
803 my_children[i] = g_variant_ref_sink (children[i]);
804 trusted &= g_variant_is_trusted (children[i]);
807 value = g_variant_new_from_children (array_type, my_children,
808 n_children, trusted);
809 g_variant_type_free (array_type);
815 * g_variant_make_tuple_type:
816 * @children: (array length=n_children): an array of GVariant *
817 * @n_children: the length of @children
819 * Return the type of a tuple containing @children as its items.
821 static GVariantType *
822 g_variant_make_tuple_type (GVariant * const *children,
825 const GVariantType **types;
829 types = g_new (const GVariantType *, n_children);
831 for (i = 0; i < n_children; i++)
832 types[i] = g_variant_get_type (children[i]);
834 type = g_variant_type_new_tuple (types, n_children);
841 * g_variant_new_tuple:
842 * @children: (array length=n_children): the items to make the tuple out of
843 * @n_children: the length of @children
845 * Creates a new tuple #GVariant out of the items in @children. The
846 * type is determined from the types of @children. No entry in the
847 * @children array may be %NULL.
849 * If @n_children is 0 then the unit tuple is constructed.
851 * If the @children are floating references (see g_variant_ref_sink()), the
852 * new instance takes ownership of them as if via g_variant_ref_sink().
854 * Returns: (transfer none): a floating reference to a new #GVariant tuple
859 g_variant_new_tuple (GVariant * const *children,
862 GVariantType *tuple_type;
863 GVariant **my_children;
868 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
870 my_children = g_new (GVariant *, n_children);
873 for (i = 0; i < n_children; i++)
875 my_children[i] = g_variant_ref_sink (children[i]);
876 trusted &= g_variant_is_trusted (children[i]);
879 tuple_type = g_variant_make_tuple_type (children, n_children);
880 value = g_variant_new_from_children (tuple_type, my_children,
881 n_children, trusted);
882 g_variant_type_free (tuple_type);
888 * g_variant_make_dict_entry_type:
889 * @key: a #GVariant, the key
890 * @val: a #GVariant, the value
892 * Return the type of a dictionary entry containing @key and @val as its
895 static GVariantType *
896 g_variant_make_dict_entry_type (GVariant *key,
899 return g_variant_type_new_dict_entry (g_variant_get_type (key),
900 g_variant_get_type (val));
904 * g_variant_new_dict_entry: (constructor)
905 * @key: a basic #GVariant, the key
906 * @value: a #GVariant, the value
908 * Creates a new dictionary entry #GVariant. @key and @value must be
909 * non-%NULL. @key must be a value of a basic type (ie: not a container).
911 * If the @key or @value are floating references (see g_variant_ref_sink()),
912 * the new instance takes ownership of them as if via g_variant_ref_sink().
914 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
919 g_variant_new_dict_entry (GVariant *key,
922 GVariantType *dict_type;
926 g_return_val_if_fail (key != NULL && value != NULL, NULL);
927 g_return_val_if_fail (!g_variant_is_container (key), NULL);
929 children = g_new (GVariant *, 2);
930 children[0] = g_variant_ref_sink (key);
931 children[1] = g_variant_ref_sink (value);
932 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
934 dict_type = g_variant_make_dict_entry_type (key, value);
935 value = g_variant_new_from_children (dict_type, children, 2, trusted);
936 g_variant_type_free (dict_type);
942 * g_variant_lookup: (skip)
943 * @dictionary: a dictionary #GVariant
944 * @key: the key to lookup in the dictionary
945 * @format_string: a GVariant format string
946 * @...: the arguments to unpack the value into
948 * Looks up a value in a dictionary #GVariant.
950 * This function is a wrapper around g_variant_lookup_value() and
951 * g_variant_get(). In the case that %NULL would have been returned,
952 * this function returns %FALSE. Otherwise, it unpacks the returned
953 * value and returns %TRUE.
955 * @format_string determines the C types that are used for unpacking
956 * the values and also determines if the values are copied or borrowed,
958 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
960 * Returns: %TRUE if a value was unpacked
965 g_variant_lookup (GVariant *dictionary,
967 const gchar *format_string,
974 g_variant_get_data (dictionary);
976 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
977 value = g_variant_lookup_value (dictionary, key, type);
978 g_variant_type_free (type);
984 va_start (ap, format_string);
985 g_variant_get_va (value, format_string, NULL, &ap);
986 g_variant_unref (value);
997 * g_variant_lookup_value:
998 * @dictionary: a dictionary #GVariant
999 * @key: the key to lookup in the dictionary
1000 * @expected_type: (allow-none): a #GVariantType, or %NULL
1002 * Looks up a value in a dictionary #GVariant.
1004 * This function works with dictionaries of the type a{s*} (and equally
1005 * well with type a{o*}, but we only further discuss the string case
1006 * for sake of clarity).
1008 * In the event that @dictionary has the type a{sv}, the @expected_type
1009 * string specifies what type of value is expected to be inside of the
1010 * variant. If the value inside the variant has a different type then
1011 * %NULL is returned. In the event that @dictionary has a value type other
1012 * than v then @expected_type must directly match the key type and it is
1013 * used to unpack the value directly or an error occurs.
1015 * In either case, if @key is not found in @dictionary, %NULL is returned.
1017 * If the key is found and the value has the correct type, it is
1018 * returned. If @expected_type was specified then any non-%NULL return
1019 * value will have this type.
1021 * Returns: (transfer full): the value of the dictionary key, or %NULL
1026 g_variant_lookup_value (GVariant *dictionary,
1028 const GVariantType *expected_type)
1034 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1035 G_VARIANT_TYPE ("a{s*}")) ||
1036 g_variant_is_of_type (dictionary,
1037 G_VARIANT_TYPE ("a{o*}")),
1040 g_variant_iter_init (&iter, dictionary);
1042 while ((entry = g_variant_iter_next_value (&iter)))
1044 GVariant *entry_key;
1047 entry_key = g_variant_get_child_value (entry, 0);
1048 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1049 g_variant_unref (entry_key);
1054 g_variant_unref (entry);
1060 value = g_variant_get_child_value (entry, 1);
1061 g_variant_unref (entry);
1063 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1067 tmp = g_variant_get_variant (value);
1068 g_variant_unref (value);
1070 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1072 g_variant_unref (tmp);
1079 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1080 g_variant_is_of_type (value, expected_type), NULL);
1086 * g_variant_get_fixed_array:
1087 * @value: a #GVariant array with fixed-sized elements
1088 * @n_elements: (out): a pointer to the location to store the number of items
1089 * @element_size: the size of each element
1091 * Provides access to the serialised data for an array of fixed-sized
1094 * @value must be an array with fixed-sized elements. Numeric types are
1095 * fixed-size, as are tuples containing only other fixed-sized types.
1097 * @element_size must be the size of a single element in the array,
1098 * as given by the section on
1099 * <link linkend='gvariant-serialised-data-memory'>Serialised Data
1102 * In particular, arrays of these fixed-sized types can be interpreted
1103 * as an array of the given C type, with @element_size set to the size
1104 * the appropriate type:
1108 * <thead><row><entry>element type</entry> <entry>C type</entry></row></thead>
1110 * <row><entry>%G_VARIANT_TYPE_INT16 (etc.)</entry>
1111 * <entry>#gint16 (etc.)</entry></row>
1112 * <row><entry>%G_VARIANT_TYPE_BOOLEAN</entry>
1113 * <entry>#guchar (not #gboolean!)</entry></row>
1114 * <row><entry>%G_VARIANT_TYPE_BYTE</entry> <entry>#guchar</entry></row>
1115 * <row><entry>%G_VARIANT_TYPE_HANDLE</entry> <entry>#guint32</entry></row>
1116 * <row><entry>%G_VARIANT_TYPE_DOUBLE</entry> <entry>#gdouble</entry></row>
1121 * For example, if calling this function for an array of 32-bit integers,
1122 * you might say sizeof(gint32). This value isn't used except for the purpose
1123 * of a double-check that the form of the serialised data matches the caller's
1126 * @n_elements, which must be non-%NULL is set equal to the number of
1127 * items in the array.
1129 * Returns: (array length=n_elements) (transfer none): a pointer to
1135 g_variant_get_fixed_array (GVariant *value,
1139 GVariantTypeInfo *array_info;
1140 gsize array_element_size;
1144 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1146 g_return_val_if_fail (n_elements != NULL, NULL);
1147 g_return_val_if_fail (element_size > 0, NULL);
1149 array_info = g_variant_get_type_info (value);
1150 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1152 g_return_val_if_fail (array_element_size, NULL);
1154 if G_UNLIKELY (array_element_size != element_size)
1156 if (array_element_size)
1157 g_critical ("g_variant_get_fixed_array: assertion "
1158 "'g_variant_array_has_fixed_size (value, element_size)' "
1159 "failed: array size %"G_GSIZE_FORMAT" does not match "
1160 "given element_size %"G_GSIZE_FORMAT".",
1161 array_element_size, element_size);
1163 g_critical ("g_variant_get_fixed_array: assertion "
1164 "'g_variant_array_has_fixed_size (value, element_size)' "
1165 "failed: array does not have fixed size.");
1168 data = g_variant_get_data (value);
1169 size = g_variant_get_size (value);
1171 if (size % element_size)
1174 *n_elements = size / element_size;
1183 * g_variant_new_fixed_array:
1184 * @element_type: the #GVariantType of each element
1185 * @elements: a pointer to the fixed array of contiguous elements
1186 * @n_elements: the number of elements
1187 * @element_size: the size of each element
1189 * Provides access to the serialised data for an array of fixed-sized
1192 * @value must be an array with fixed-sized elements. Numeric types are
1193 * fixed-size as are tuples containing only other fixed-sized types.
1195 * @element_size must be the size of a single element in the array.
1196 * For example, if calling this function for an array of 32-bit integers,
1197 * you might say sizeof(gint32). This value isn't used except for the purpose
1198 * of a double-check that the form of the serialised data matches the caller's
1201 * @n_elements, which must be non-%NULL is set equal to the number of
1202 * items in the array.
1204 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1209 g_variant_new_fixed_array (const GVariantType *element_type,
1210 gconstpointer elements,
1214 GVariantType *array_type;
1215 gsize array_element_size;
1216 GVariantTypeInfo *array_info;
1220 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1221 g_return_val_if_fail (element_size > 0, NULL);
1223 array_type = g_variant_type_new_array (element_type);
1224 array_info = g_variant_type_info_get (array_type);
1225 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1226 if G_UNLIKELY (array_element_size != element_size)
1228 if (array_element_size)
1229 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1230 " does not match given element_size %" G_GSIZE_FORMAT ".",
1231 array_element_size, element_size);
1233 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1237 data = g_memdup (elements, n_elements * element_size);
1238 value = g_variant_new_from_data (array_type, data,
1239 n_elements * element_size,
1240 FALSE, g_free, data);
1242 g_variant_type_free (array_type);
1243 g_variant_type_info_unref (array_info);
1248 /* String type constructor/getters/validation {{{1 */
1250 * g_variant_new_string:
1251 * @string: a normal utf8 nul-terminated string
1253 * Creates a string #GVariant with the contents of @string.
1255 * @string must be valid utf8.
1257 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1262 g_variant_new_string (const gchar *string)
1264 g_return_val_if_fail (string != NULL, NULL);
1265 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1267 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1268 string, strlen (string) + 1);
1272 * g_variant_new_take_string: (skip)
1273 * @string: a normal utf8 nul-terminated string
1275 * Creates a string #GVariant with the contents of @string.
1277 * @string must be valid utf8.
1279 * This function consumes @string. g_free() will be called on @string
1280 * when it is no longer required.
1282 * You must not modify or access @string in any other way after passing
1283 * it to this function. It is even possible that @string is immediately
1286 * Returns: (transfer none): a floating reference to a new string
1287 * #GVariant instance
1292 g_variant_new_take_string (gchar *string)
1297 g_return_val_if_fail (string != NULL, NULL);
1298 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1300 bytes = g_bytes_new_take (string, strlen (string) + 1);
1301 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1302 g_bytes_unref (bytes);
1308 * g_variant_new_printf: (skip)
1309 * @format_string: a printf-style format string
1310 * @...: arguments for @format_string
1312 * Creates a string-type GVariant using printf formatting.
1314 * This is similar to calling g_strdup_printf() and then
1315 * g_variant_new_string() but it saves a temporary variable and an
1318 * Returns: (transfer none): a floating reference to a new string
1319 * #GVariant instance
1324 g_variant_new_printf (const gchar *format_string,
1332 g_return_val_if_fail (format_string != NULL, NULL);
1334 va_start (ap, format_string);
1335 string = g_strdup_vprintf (format_string, ap);
1338 bytes = g_bytes_new_take (string, strlen (string) + 1);
1339 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1340 g_bytes_unref (bytes);
1346 * g_variant_new_object_path:
1347 * @object_path: a normal C nul-terminated string
1349 * Creates a D-Bus object path #GVariant with the contents of @string.
1350 * @string must be a valid D-Bus object path. Use
1351 * g_variant_is_object_path() if you're not sure.
1353 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1358 g_variant_new_object_path (const gchar *object_path)
1360 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1362 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1363 object_path, strlen (object_path) + 1);
1367 * g_variant_is_object_path:
1368 * @string: a normal C nul-terminated string
1370 * Determines if a given string is a valid D-Bus object path. You
1371 * should ensure that a string is a valid D-Bus object path before
1372 * passing it to g_variant_new_object_path().
1374 * A valid object path starts with '/' followed by zero or more
1375 * sequences of characters separated by '/' characters. Each sequence
1376 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1377 * (including the one following the final '/' character) may be empty.
1379 * Returns: %TRUE if @string is a D-Bus object path
1384 g_variant_is_object_path (const gchar *string)
1386 g_return_val_if_fail (string != NULL, FALSE);
1388 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1392 * g_variant_new_signature:
1393 * @signature: a normal C nul-terminated string
1395 * Creates a D-Bus type signature #GVariant with the contents of
1396 * @string. @string must be a valid D-Bus type signature. Use
1397 * g_variant_is_signature() if you're not sure.
1399 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1404 g_variant_new_signature (const gchar *signature)
1406 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1408 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1409 signature, strlen (signature) + 1);
1413 * g_variant_is_signature:
1414 * @string: a normal C nul-terminated string
1416 * Determines if a given string is a valid D-Bus type signature. You
1417 * should ensure that a string is a valid D-Bus type signature before
1418 * passing it to g_variant_new_signature().
1420 * D-Bus type signatures consist of zero or more definite #GVariantType
1421 * strings in sequence.
1423 * Returns: %TRUE if @string is a D-Bus type signature
1428 g_variant_is_signature (const gchar *string)
1430 g_return_val_if_fail (string != NULL, FALSE);
1432 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1436 * g_variant_get_string:
1437 * @value: a string #GVariant instance
1438 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1439 * to store the length
1441 * Returns the string value of a #GVariant instance with a string
1442 * type. This includes the types %G_VARIANT_TYPE_STRING,
1443 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1445 * The string will always be utf8 encoded.
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. For untrusted values, a strlen() will be performed.
1451 * It is an error to call this function with a @value of any type
1452 * other than those three.
1454 * The return value remains valid as long as @value exists.
1456 * Returns: (transfer none): the constant string, utf8 encoded
1461 g_variant_get_string (GVariant *value,
1467 g_return_val_if_fail (value != NULL, NULL);
1468 g_return_val_if_fail (
1469 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1470 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1471 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1473 data = g_variant_get_data (value);
1474 size = g_variant_get_size (value);
1476 if (!g_variant_is_trusted (value))
1478 switch (g_variant_classify (value))
1480 case G_VARIANT_CLASS_STRING:
1481 if (g_variant_serialiser_is_string (data, size))
1488 case G_VARIANT_CLASS_OBJECT_PATH:
1489 if (g_variant_serialiser_is_object_path (data, size))
1496 case G_VARIANT_CLASS_SIGNATURE:
1497 if (g_variant_serialiser_is_signature (data, size))
1505 g_assert_not_reached ();
1516 * g_variant_dup_string:
1517 * @value: a string #GVariant instance
1518 * @length: (out): a pointer to a #gsize, to store the length
1520 * Similar to g_variant_get_string() except that instead of returning
1521 * a constant string, the string is duplicated.
1523 * The string will always be utf8 encoded.
1525 * The return value must be freed using g_free().
1527 * Returns: (transfer full): a newly allocated string, utf8 encoded
1532 g_variant_dup_string (GVariant *value,
1535 return g_strdup (g_variant_get_string (value, length));
1539 * g_variant_new_strv:
1540 * @strv: (array length=length) (element-type utf8): an array of strings
1541 * @length: the length of @strv, or -1
1543 * Constructs an array of strings #GVariant from the given array of
1546 * If @length is -1 then @strv is %NULL-terminated.
1548 * Returns: (transfer none): a new floating #GVariant instance
1553 g_variant_new_strv (const gchar * const *strv,
1559 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1562 length = g_strv_length ((gchar **) strv);
1564 strings = g_new (GVariant *, length);
1565 for (i = 0; i < length; i++)
1566 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1568 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1569 strings, length, TRUE);
1573 * g_variant_get_strv:
1574 * @value: an array of strings #GVariant
1575 * @length: (out) (allow-none): the length of the result, or %NULL
1577 * Gets the contents of an array of strings #GVariant. This call
1578 * makes a shallow copy; the return result should be released with
1579 * g_free(), but the individual strings must not be modified.
1581 * If @length is non-%NULL then the number of elements in the result
1582 * is stored there. In any case, the resulting array will be
1585 * For an empty array, @length will be set to 0 and a pointer to a
1586 * %NULL pointer will be returned.
1588 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1593 g_variant_get_strv (GVariant *value,
1600 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1602 g_variant_get_data (value);
1603 n = g_variant_n_children (value);
1604 strv = g_new (const gchar *, n + 1);
1606 for (i = 0; i < n; i++)
1610 string = g_variant_get_child_value (value, i);
1611 strv[i] = g_variant_get_string (string, NULL);
1612 g_variant_unref (string);
1623 * g_variant_dup_strv:
1624 * @value: an array of strings #GVariant
1625 * @length: (out) (allow-none): the length of the result, or %NULL
1627 * Gets the contents of an array of strings #GVariant. This call
1628 * makes a deep copy; the return result should be released with
1631 * If @length is non-%NULL then the number of elements in the result
1632 * is stored there. In any case, the resulting array will be
1635 * For an empty array, @length will be set to 0 and a pointer to a
1636 * %NULL pointer will be returned.
1638 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1643 g_variant_dup_strv (GVariant *value,
1650 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1652 n = g_variant_n_children (value);
1653 strv = g_new (gchar *, n + 1);
1655 for (i = 0; i < n; i++)
1659 string = g_variant_get_child_value (value, i);
1660 strv[i] = g_variant_dup_string (string, NULL);
1661 g_variant_unref (string);
1672 * g_variant_new_objv:
1673 * @strv: (array length=length) (element-type utf8): an array of strings
1674 * @length: the length of @strv, or -1
1676 * Constructs an array of object paths #GVariant from the given array of
1679 * Each string must be a valid #GVariant object path; see
1680 * g_variant_is_object_path().
1682 * If @length is -1 then @strv is %NULL-terminated.
1684 * Returns: (transfer none): a new floating #GVariant instance
1689 g_variant_new_objv (const gchar * const *strv,
1695 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1698 length = g_strv_length ((gchar **) strv);
1700 strings = g_new (GVariant *, length);
1701 for (i = 0; i < length; i++)
1702 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1704 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1705 strings, length, TRUE);
1709 * g_variant_get_objv:
1710 * @value: an array of object paths #GVariant
1711 * @length: (out) (allow-none): the length of the result, or %NULL
1713 * Gets the contents of an array of object paths #GVariant. This call
1714 * makes a shallow copy; the return result should be released with
1715 * g_free(), but the individual strings must not be modified.
1717 * If @length is non-%NULL then the number of elements in the result
1718 * is stored there. In any case, the resulting array will be
1721 * For an empty array, @length will be set to 0 and a pointer to a
1722 * %NULL pointer will be returned.
1724 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1729 g_variant_get_objv (GVariant *value,
1736 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1738 g_variant_get_data (value);
1739 n = g_variant_n_children (value);
1740 strv = g_new (const gchar *, n + 1);
1742 for (i = 0; i < n; i++)
1746 string = g_variant_get_child_value (value, i);
1747 strv[i] = g_variant_get_string (string, NULL);
1748 g_variant_unref (string);
1759 * g_variant_dup_objv:
1760 * @value: an array of object paths #GVariant
1761 * @length: (out) (allow-none): the length of the result, or %NULL
1763 * Gets the contents of an array of object paths #GVariant. This call
1764 * makes a deep copy; the return result should be released with
1767 * If @length is non-%NULL then the number of elements in the result
1768 * is stored there. In any case, the resulting array will be
1771 * For an empty array, @length will be set to 0 and a pointer to a
1772 * %NULL pointer will be returned.
1774 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1779 g_variant_dup_objv (GVariant *value,
1786 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1788 n = g_variant_n_children (value);
1789 strv = g_new (gchar *, n + 1);
1791 for (i = 0; i < n; i++)
1795 string = g_variant_get_child_value (value, i);
1796 strv[i] = g_variant_dup_string (string, NULL);
1797 g_variant_unref (string);
1809 * g_variant_new_bytestring:
1810 * @string: (array zero-terminated=1) (element-type guint8): a normal
1811 * nul-terminated string in no particular encoding
1813 * Creates an array-of-bytes #GVariant with the contents of @string.
1814 * This function is just like g_variant_new_string() except that the
1815 * string need not be valid utf8.
1817 * The nul terminator character at the end of the string is stored in
1820 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1825 g_variant_new_bytestring (const gchar *string)
1827 g_return_val_if_fail (string != NULL, NULL);
1829 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1830 string, strlen (string) + 1);
1834 * g_variant_get_bytestring:
1835 * @value: an array-of-bytes #GVariant instance
1837 * Returns the string value of a #GVariant instance with an
1838 * array-of-bytes type. The string has no particular encoding.
1840 * If the array does not end with a nul terminator character, the empty
1841 * string is returned. For this reason, you can always trust that a
1842 * non-%NULL nul-terminated string will be returned by this function.
1844 * If the array contains a nul terminator character somewhere other than
1845 * the last byte then the returned string is the string, up to the first
1846 * such nul character.
1848 * It is an error to call this function with a @value that is not an
1851 * The return value remains valid as long as @value exists.
1853 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1854 * the constant string
1859 g_variant_get_bytestring (GVariant *value)
1861 const gchar *string;
1864 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1866 /* Won't be NULL since this is an array type */
1867 string = g_variant_get_data (value);
1868 size = g_variant_get_size (value);
1870 if (size && string[size - 1] == '\0')
1877 * g_variant_dup_bytestring:
1878 * @value: an array-of-bytes #GVariant instance
1879 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1880 * the length (not including the nul terminator)
1882 * Similar to g_variant_get_bytestring() except that instead of
1883 * returning a constant string, the string is duplicated.
1885 * The return value must be freed using g_free().
1887 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1888 * a newly allocated string
1893 g_variant_dup_bytestring (GVariant *value,
1896 const gchar *original = g_variant_get_bytestring (value);
1899 /* don't crash in case get_bytestring() had an assert failure */
1900 if (original == NULL)
1903 size = strlen (original);
1908 return g_memdup (original, size + 1);
1912 * g_variant_new_bytestring_array:
1913 * @strv: (array length=length): an array of strings
1914 * @length: the length of @strv, or -1
1916 * Constructs an array of bytestring #GVariant from the given array of
1919 * If @length is -1 then @strv is %NULL-terminated.
1921 * Returns: (transfer none): a new floating #GVariant instance
1926 g_variant_new_bytestring_array (const gchar * const *strv,
1932 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1935 length = g_strv_length ((gchar **) strv);
1937 strings = g_new (GVariant *, length);
1938 for (i = 0; i < length; i++)
1939 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1941 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1942 strings, length, TRUE);
1946 * g_variant_get_bytestring_array:
1947 * @value: an array of array of bytes #GVariant ('aay')
1948 * @length: (out) (allow-none): the length of the result, or %NULL
1950 * Gets the contents of an array of array of bytes #GVariant. This call
1951 * makes a shallow copy; the return result should be released with
1952 * g_free(), but the individual strings must not be modified.
1954 * If @length is non-%NULL then the number of elements in the result is
1955 * stored there. In any case, the resulting array will be
1958 * For an empty array, @length will be set to 0 and a pointer to a
1959 * %NULL pointer will be returned.
1961 * Returns: (array length=length) (transfer container): an array of constant strings
1966 g_variant_get_bytestring_array (GVariant *value,
1973 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1975 g_variant_get_data (value);
1976 n = g_variant_n_children (value);
1977 strv = g_new (const gchar *, n + 1);
1979 for (i = 0; i < n; i++)
1983 string = g_variant_get_child_value (value, i);
1984 strv[i] = g_variant_get_bytestring (string);
1985 g_variant_unref (string);
1996 * g_variant_dup_bytestring_array:
1997 * @value: an array of array of bytes #GVariant ('aay')
1998 * @length: (out) (allow-none): the length of the result, or %NULL
2000 * Gets the contents of an array of array of bytes #GVariant. This call
2001 * makes a deep copy; the return result should be released with
2004 * If @length is non-%NULL then the number of elements in the result is
2005 * stored there. In any case, the resulting array will be
2008 * For an empty array, @length will be set to 0 and a pointer to a
2009 * %NULL pointer will be returned.
2011 * Returns: (array length=length) (transfer full): an array of strings
2016 g_variant_dup_bytestring_array (GVariant *value,
2023 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2025 g_variant_get_data (value);
2026 n = g_variant_n_children (value);
2027 strv = g_new (gchar *, n + 1);
2029 for (i = 0; i < n; i++)
2033 string = g_variant_get_child_value (value, i);
2034 strv[i] = g_variant_dup_bytestring (string, NULL);
2035 g_variant_unref (string);
2045 /* Type checking and querying {{{1 */
2047 * g_variant_get_type:
2048 * @value: a #GVariant
2050 * Determines the type of @value.
2052 * The return value is valid for the lifetime of @value and must not
2055 * Returns: a #GVariantType
2059 const GVariantType *
2060 g_variant_get_type (GVariant *value)
2062 GVariantTypeInfo *type_info;
2064 g_return_val_if_fail (value != NULL, NULL);
2066 type_info = g_variant_get_type_info (value);
2068 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2072 * g_variant_get_type_string:
2073 * @value: a #GVariant
2075 * Returns the type string of @value. Unlike the result of calling
2076 * g_variant_type_peek_string(), this string is nul-terminated. This
2077 * string belongs to #GVariant and must not be freed.
2079 * Returns: the type string for the type of @value
2084 g_variant_get_type_string (GVariant *value)
2086 GVariantTypeInfo *type_info;
2088 g_return_val_if_fail (value != NULL, NULL);
2090 type_info = g_variant_get_type_info (value);
2092 return g_variant_type_info_get_type_string (type_info);
2096 * g_variant_is_of_type:
2097 * @value: a #GVariant instance
2098 * @type: a #GVariantType
2100 * Checks if a value has a type matching the provided type.
2102 * Returns: %TRUE if the type of @value matches @type
2107 g_variant_is_of_type (GVariant *value,
2108 const GVariantType *type)
2110 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2114 * g_variant_is_container:
2115 * @value: a #GVariant instance
2117 * Checks if @value is a container.
2119 * Returns: %TRUE if @value is a container
2124 g_variant_is_container (GVariant *value)
2126 return g_variant_type_is_container (g_variant_get_type (value));
2131 * g_variant_classify:
2132 * @value: a #GVariant
2134 * Classifies @value according to its top-level type.
2136 * Returns: the #GVariantClass of @value
2142 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2143 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2144 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2145 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2146 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2147 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2148 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2149 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2150 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2151 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2153 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2154 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2156 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2157 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2158 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2159 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2160 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2161 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2163 * The range of possible top-level types of #GVariant instances.
2168 g_variant_classify (GVariant *value)
2170 g_return_val_if_fail (value != NULL, 0);
2172 return *g_variant_get_type_string (value);
2175 /* Pretty printer {{{1 */
2176 /* This function is not introspectable because if @string is NULL,
2177 @returns is (transfer full), otherwise it is (transfer none), which
2178 is not supported by GObjectIntrospection */
2180 * g_variant_print_string: (skip)
2181 * @value: a #GVariant
2182 * @string: (allow-none) (default NULL): a #GString, or %NULL
2183 * @type_annotate: %TRUE if type information should be included in
2186 * Behaves as g_variant_print(), but operates on a #GString.
2188 * If @string is non-%NULL then it is appended to and returned. Else,
2189 * a new empty #GString is allocated and it is returned.
2191 * Returns: a #GString containing the string
2196 g_variant_print_string (GVariant *value,
2198 gboolean type_annotate)
2200 if G_UNLIKELY (string == NULL)
2201 string = g_string_new (NULL);
2203 switch (g_variant_classify (value))
2205 case G_VARIANT_CLASS_MAYBE:
2207 g_string_append_printf (string, "@%s ",
2208 g_variant_get_type_string (value));
2210 if (g_variant_n_children (value))
2212 gchar *printed_child;
2217 * Consider the case of the type "mmi". In this case we could
2218 * write "just just 4", but "4" alone is totally unambiguous,
2219 * so we try to drop "just" where possible.
2221 * We have to be careful not to always drop "just", though,
2222 * since "nothing" needs to be distinguishable from "just
2223 * nothing". The case where we need to ensure we keep the
2224 * "just" is actually exactly the case where we have a nested
2227 * Instead of searching for that nested Nothing, we just print
2228 * the contained value into a separate string and see if we
2229 * end up with "nothing" at the end of it. If so, we need to
2230 * add "just" at our level.
2232 element = g_variant_get_child_value (value, 0);
2233 printed_child = g_variant_print (element, FALSE);
2234 g_variant_unref (element);
2236 if (g_str_has_suffix (printed_child, "nothing"))
2237 g_string_append (string, "just ");
2238 g_string_append (string, printed_child);
2239 g_free (printed_child);
2242 g_string_append (string, "nothing");
2246 case G_VARIANT_CLASS_ARRAY:
2247 /* it's an array so the first character of the type string is 'a'
2249 * if the first two characters are 'ay' then it's a bytestring.
2250 * under certain conditions we print those as strings.
2252 if (g_variant_get_type_string (value)[1] == 'y')
2258 /* first determine if it is a byte string.
2259 * that's when there's a single nul character: at the end.
2261 str = g_variant_get_data (value);
2262 size = g_variant_get_size (value);
2264 for (i = 0; i < size; i++)
2268 /* first nul byte is the last byte -> it's a byte string. */
2271 gchar *escaped = g_strescape (str, NULL);
2273 /* use double quotes only if a ' is in the string */
2274 if (strchr (str, '\''))
2275 g_string_append_printf (string, "b\"%s\"", escaped);
2277 g_string_append_printf (string, "b'%s'", escaped);
2284 /* fall through and handle normally... */;
2288 * if the first two characters are 'a{' then it's an array of
2289 * dictionary entries (ie: a dictionary) so we print that
2292 if (g_variant_get_type_string (value)[1] == '{')
2295 const gchar *comma = "";
2298 if ((n = g_variant_n_children (value)) == 0)
2301 g_string_append_printf (string, "@%s ",
2302 g_variant_get_type_string (value));
2303 g_string_append (string, "{}");
2307 g_string_append_c (string, '{');
2308 for (i = 0; i < n; i++)
2310 GVariant *entry, *key, *val;
2312 g_string_append (string, comma);
2315 entry = g_variant_get_child_value (value, i);
2316 key = g_variant_get_child_value (entry, 0);
2317 val = g_variant_get_child_value (entry, 1);
2318 g_variant_unref (entry);
2320 g_variant_print_string (key, string, type_annotate);
2321 g_variant_unref (key);
2322 g_string_append (string, ": ");
2323 g_variant_print_string (val, string, type_annotate);
2324 g_variant_unref (val);
2325 type_annotate = FALSE;
2327 g_string_append_c (string, '}');
2330 /* normal (non-dictionary) array */
2332 const gchar *comma = "";
2335 if ((n = g_variant_n_children (value)) == 0)
2338 g_string_append_printf (string, "@%s ",
2339 g_variant_get_type_string (value));
2340 g_string_append (string, "[]");
2344 g_string_append_c (string, '[');
2345 for (i = 0; i < n; i++)
2349 g_string_append (string, comma);
2352 element = g_variant_get_child_value (value, i);
2354 g_variant_print_string (element, string, type_annotate);
2355 g_variant_unref (element);
2356 type_annotate = FALSE;
2358 g_string_append_c (string, ']');
2363 case G_VARIANT_CLASS_TUPLE:
2367 n = g_variant_n_children (value);
2369 g_string_append_c (string, '(');
2370 for (i = 0; i < n; i++)
2374 element = g_variant_get_child_value (value, i);
2375 g_variant_print_string (element, string, type_annotate);
2376 g_string_append (string, ", ");
2377 g_variant_unref (element);
2380 /* for >1 item: remove final ", "
2381 * for 1 item: remove final " ", but leave the ","
2382 * for 0 items: there is only "(", so remove nothing
2384 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2385 g_string_append_c (string, ')');
2389 case G_VARIANT_CLASS_DICT_ENTRY:
2393 g_string_append_c (string, '{');
2395 element = g_variant_get_child_value (value, 0);
2396 g_variant_print_string (element, string, type_annotate);
2397 g_variant_unref (element);
2399 g_string_append (string, ", ");
2401 element = g_variant_get_child_value (value, 1);
2402 g_variant_print_string (element, string, type_annotate);
2403 g_variant_unref (element);
2405 g_string_append_c (string, '}');
2409 case G_VARIANT_CLASS_VARIANT:
2411 GVariant *child = g_variant_get_variant (value);
2413 /* Always annotate types in nested variants, because they are
2414 * (by nature) of variable type.
2416 g_string_append_c (string, '<');
2417 g_variant_print_string (child, string, TRUE);
2418 g_string_append_c (string, '>');
2420 g_variant_unref (child);
2424 case G_VARIANT_CLASS_BOOLEAN:
2425 if (g_variant_get_boolean (value))
2426 g_string_append (string, "true");
2428 g_string_append (string, "false");
2431 case G_VARIANT_CLASS_STRING:
2433 const gchar *str = g_variant_get_string (value, NULL);
2434 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2436 g_string_append_c (string, quote);
2440 gunichar c = g_utf8_get_char (str);
2442 if (c == quote || c == '\\')
2443 g_string_append_c (string, '\\');
2445 if (g_unichar_isprint (c))
2446 g_string_append_unichar (string, c);
2450 g_string_append_c (string, '\\');
2455 g_string_append_c (string, 'a');
2459 g_string_append_c (string, 'b');
2463 g_string_append_c (string, 'f');
2467 g_string_append_c (string, 'n');
2471 g_string_append_c (string, 'r');
2475 g_string_append_c (string, 't');
2479 g_string_append_c (string, 'v');
2483 g_string_append_printf (string, "u%04x", c);
2487 g_string_append_printf (string, "U%08x", c);
2490 str = g_utf8_next_char (str);
2493 g_string_append_c (string, quote);
2497 case G_VARIANT_CLASS_BYTE:
2499 g_string_append (string, "byte ");
2500 g_string_append_printf (string, "0x%02x",
2501 g_variant_get_byte (value));
2504 case G_VARIANT_CLASS_INT16:
2506 g_string_append (string, "int16 ");
2507 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2508 g_variant_get_int16 (value));
2511 case G_VARIANT_CLASS_UINT16:
2513 g_string_append (string, "uint16 ");
2514 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2515 g_variant_get_uint16 (value));
2518 case G_VARIANT_CLASS_INT32:
2519 /* Never annotate this type because it is the default for numbers
2520 * (and this is a *pretty* printer)
2522 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2523 g_variant_get_int32 (value));
2526 case G_VARIANT_CLASS_HANDLE:
2528 g_string_append (string, "handle ");
2529 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2530 g_variant_get_handle (value));
2533 case G_VARIANT_CLASS_UINT32:
2535 g_string_append (string, "uint32 ");
2536 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2537 g_variant_get_uint32 (value));
2540 case G_VARIANT_CLASS_INT64:
2542 g_string_append (string, "int64 ");
2543 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2544 g_variant_get_int64 (value));
2547 case G_VARIANT_CLASS_UINT64:
2549 g_string_append (string, "uint64 ");
2550 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2551 g_variant_get_uint64 (value));
2554 case G_VARIANT_CLASS_DOUBLE:
2559 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2561 for (i = 0; buffer[i]; i++)
2562 if (buffer[i] == '.' || buffer[i] == 'e' ||
2563 buffer[i] == 'n' || buffer[i] == 'N')
2566 /* if there is no '.' or 'e' in the float then add one */
2567 if (buffer[i] == '\0')
2574 g_string_append (string, buffer);
2578 case G_VARIANT_CLASS_OBJECT_PATH:
2580 g_string_append (string, "objectpath ");
2581 g_string_append_printf (string, "\'%s\'",
2582 g_variant_get_string (value, NULL));
2585 case G_VARIANT_CLASS_SIGNATURE:
2587 g_string_append (string, "signature ");
2588 g_string_append_printf (string, "\'%s\'",
2589 g_variant_get_string (value, NULL));
2593 g_assert_not_reached ();
2601 * @value: a #GVariant
2602 * @type_annotate: %TRUE if type information should be included in
2605 * Pretty-prints @value in the format understood by g_variant_parse().
2607 * The format is described <link linkend='gvariant-text'>here</link>.
2609 * If @type_annotate is %TRUE, then type information is included in
2612 * Returns: (transfer full): a newly-allocated string holding the result.
2617 g_variant_print (GVariant *value,
2618 gboolean type_annotate)
2620 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2624 /* Hash, Equal, Compare {{{1 */
2627 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2629 * Generates a hash value for a #GVariant instance.
2631 * The output of this function is guaranteed to be the same for a given
2632 * value only per-process. It may change between different processor
2633 * architectures or even different versions of GLib. Do not use this
2634 * function as a basis for building protocols or file formats.
2636 * The type of @value is #gconstpointer only to allow use of this
2637 * function with #GHashTable. @value must be a #GVariant.
2639 * Returns: a hash value corresponding to @value
2644 g_variant_hash (gconstpointer value_)
2646 GVariant *value = (GVariant *) value_;
2648 switch (g_variant_classify (value))
2650 case G_VARIANT_CLASS_STRING:
2651 case G_VARIANT_CLASS_OBJECT_PATH:
2652 case G_VARIANT_CLASS_SIGNATURE:
2653 return g_str_hash (g_variant_get_string (value, NULL));
2655 case G_VARIANT_CLASS_BOOLEAN:
2656 /* this is a very odd thing to hash... */
2657 return g_variant_get_boolean (value);
2659 case G_VARIANT_CLASS_BYTE:
2660 return g_variant_get_byte (value);
2662 case G_VARIANT_CLASS_INT16:
2663 case G_VARIANT_CLASS_UINT16:
2667 ptr = g_variant_get_data (value);
2675 case G_VARIANT_CLASS_INT32:
2676 case G_VARIANT_CLASS_UINT32:
2677 case G_VARIANT_CLASS_HANDLE:
2681 ptr = g_variant_get_data (value);
2689 case G_VARIANT_CLASS_INT64:
2690 case G_VARIANT_CLASS_UINT64:
2691 case G_VARIANT_CLASS_DOUBLE:
2692 /* need a separate case for these guys because otherwise
2693 * performance could be quite bad on big endian systems
2698 ptr = g_variant_get_data (value);
2701 return ptr[0] + ptr[1];
2707 g_return_val_if_fail (!g_variant_is_container (value), 0);
2708 g_assert_not_reached ();
2714 * @one: (type GVariant): a #GVariant instance
2715 * @two: (type GVariant): a #GVariant instance
2717 * Checks if @one and @two have the same type and value.
2719 * The types of @one and @two are #gconstpointer only to allow use of
2720 * this function with #GHashTable. They must each be a #GVariant.
2722 * Returns: %TRUE if @one and @two are equal
2727 g_variant_equal (gconstpointer one,
2732 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2734 if (g_variant_get_type_info ((GVariant *) one) !=
2735 g_variant_get_type_info ((GVariant *) two))
2738 /* if both values are trusted to be in their canonical serialised form
2739 * then a simple memcmp() of their serialised data will answer the
2742 * if not, then this might generate a false negative (since it is
2743 * possible for two different byte sequences to represent the same
2744 * value). for now we solve this by pretty-printing both values and
2745 * comparing the result.
2747 if (g_variant_is_trusted ((GVariant *) one) &&
2748 g_variant_is_trusted ((GVariant *) two))
2750 gconstpointer data_one, data_two;
2751 gsize size_one, size_two;
2753 size_one = g_variant_get_size ((GVariant *) one);
2754 size_two = g_variant_get_size ((GVariant *) two);
2756 if (size_one != size_two)
2759 data_one = g_variant_get_data ((GVariant *) one);
2760 data_two = g_variant_get_data ((GVariant *) two);
2762 equal = memcmp (data_one, data_two, size_one) == 0;
2766 gchar *strone, *strtwo;
2768 strone = g_variant_print ((GVariant *) one, FALSE);
2769 strtwo = g_variant_print ((GVariant *) two, FALSE);
2770 equal = strcmp (strone, strtwo) == 0;
2779 * g_variant_compare:
2780 * @one: (type GVariant): a basic-typed #GVariant instance
2781 * @two: (type GVariant): a #GVariant instance of the same type
2783 * Compares @one and @two.
2785 * The types of @one and @two are #gconstpointer only to allow use of
2786 * this function with #GTree, #GPtrArray, etc. They must each be a
2789 * Comparison is only defined for basic types (ie: booleans, numbers,
2790 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2791 * ordered in the usual way. Strings are in ASCII lexographical order.
2793 * It is a programmer error to attempt to compare container values or
2794 * two values that have types that are not exactly equal. For example,
2795 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2796 * integer. Also note that this function is not particularly
2797 * well-behaved when it comes to comparison of doubles; in particular,
2798 * the handling of incomparable values (ie: NaN) is undefined.
2800 * If you only require an equality comparison, g_variant_equal() is more
2803 * Returns: negative value if a < b;
2805 * positive value if a > b.
2810 g_variant_compare (gconstpointer one,
2813 GVariant *a = (GVariant *) one;
2814 GVariant *b = (GVariant *) two;
2816 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2818 switch (g_variant_classify (a))
2820 case G_VARIANT_CLASS_BOOLEAN:
2821 return g_variant_get_boolean (a) -
2822 g_variant_get_boolean (b);
2824 case G_VARIANT_CLASS_BYTE:
2825 return ((gint) g_variant_get_byte (a)) -
2826 ((gint) g_variant_get_byte (b));
2828 case G_VARIANT_CLASS_INT16:
2829 return ((gint) g_variant_get_int16 (a)) -
2830 ((gint) g_variant_get_int16 (b));
2832 case G_VARIANT_CLASS_UINT16:
2833 return ((gint) g_variant_get_uint16 (a)) -
2834 ((gint) g_variant_get_uint16 (b));
2836 case G_VARIANT_CLASS_INT32:
2838 gint32 a_val = g_variant_get_int32 (a);
2839 gint32 b_val = g_variant_get_int32 (b);
2841 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2844 case G_VARIANT_CLASS_UINT32:
2846 guint32 a_val = g_variant_get_uint32 (a);
2847 guint32 b_val = g_variant_get_uint32 (b);
2849 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2852 case G_VARIANT_CLASS_INT64:
2854 gint64 a_val = g_variant_get_int64 (a);
2855 gint64 b_val = g_variant_get_int64 (b);
2857 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2860 case G_VARIANT_CLASS_UINT64:
2862 guint64 a_val = g_variant_get_uint64 (a);
2863 guint64 b_val = g_variant_get_uint64 (b);
2865 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2868 case G_VARIANT_CLASS_DOUBLE:
2870 gdouble a_val = g_variant_get_double (a);
2871 gdouble b_val = g_variant_get_double (b);
2873 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2876 case G_VARIANT_CLASS_STRING:
2877 case G_VARIANT_CLASS_OBJECT_PATH:
2878 case G_VARIANT_CLASS_SIGNATURE:
2879 return strcmp (g_variant_get_string (a, NULL),
2880 g_variant_get_string (b, NULL));
2883 g_return_val_if_fail (!g_variant_is_container (a), 0);
2884 g_assert_not_reached ();
2888 /* GVariantIter {{{1 */
2890 * GVariantIter: (skip)
2892 * #GVariantIter is an opaque data structure and can only be accessed
2893 * using the following functions.
2900 const gchar *loop_format;
2906 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2910 struct stack_iter iter;
2912 GVariant *value_ref;
2916 #define GVSI(i) ((struct stack_iter *) (i))
2917 #define GVHI(i) ((struct heap_iter *) (i))
2918 #define GVSI_MAGIC ((gsize) 3579507750u)
2919 #define GVHI_MAGIC ((gsize) 1450270775u)
2920 #define is_valid_iter(i) (i != NULL && \
2921 GVSI(i)->magic == GVSI_MAGIC)
2922 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2926 * g_variant_iter_new:
2927 * @value: a container #GVariant
2929 * Creates a heap-allocated #GVariantIter for iterating over the items
2932 * Use g_variant_iter_free() to free the return value when you no longer
2935 * A reference is taken to @value and will be released only when
2936 * g_variant_iter_free() is called.
2938 * Returns: (transfer full): a new heap-allocated #GVariantIter
2943 g_variant_iter_new (GVariant *value)
2947 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2948 GVHI(iter)->value_ref = g_variant_ref (value);
2949 GVHI(iter)->magic = GVHI_MAGIC;
2951 g_variant_iter_init (iter, value);
2957 * g_variant_iter_init: (skip)
2958 * @iter: a pointer to a #GVariantIter
2959 * @value: a container #GVariant
2961 * Initialises (without allocating) a #GVariantIter. @iter may be
2962 * completely uninitialised prior to this call; its old value is
2965 * The iterator remains valid for as long as @value exists, and need not
2966 * be freed in any way.
2968 * Returns: the number of items in @value
2973 g_variant_iter_init (GVariantIter *iter,
2976 GVSI(iter)->magic = GVSI_MAGIC;
2977 GVSI(iter)->value = value;
2978 GVSI(iter)->n = g_variant_n_children (value);
2980 GVSI(iter)->loop_format = NULL;
2982 return GVSI(iter)->n;
2986 * g_variant_iter_copy:
2987 * @iter: a #GVariantIter
2989 * Creates a new heap-allocated #GVariantIter to iterate over the
2990 * container that was being iterated over by @iter. Iteration begins on
2991 * the new iterator from the current position of the old iterator but
2992 * the two copies are independent past that point.
2994 * Use g_variant_iter_free() to free the return value when you no longer
2997 * A reference is taken to the container that @iter is iterating over
2998 * and will be releated only when g_variant_iter_free() is called.
3000 * Returns: (transfer full): a new heap-allocated #GVariantIter
3005 g_variant_iter_copy (GVariantIter *iter)
3009 g_return_val_if_fail (is_valid_iter (iter), 0);
3011 copy = g_variant_iter_new (GVSI(iter)->value);
3012 GVSI(copy)->i = GVSI(iter)->i;
3018 * g_variant_iter_n_children:
3019 * @iter: a #GVariantIter
3021 * Queries the number of child items in the container that we are
3022 * iterating over. This is the total number of items -- not the number
3023 * of items remaining.
3025 * This function might be useful for preallocation of arrays.
3027 * Returns: the number of children in the container
3032 g_variant_iter_n_children (GVariantIter *iter)
3034 g_return_val_if_fail (is_valid_iter (iter), 0);
3036 return GVSI(iter)->n;
3040 * g_variant_iter_free:
3041 * @iter: (transfer full): a heap-allocated #GVariantIter
3043 * Frees a heap-allocated #GVariantIter. Only call this function on
3044 * iterators that were returned by g_variant_iter_new() or
3045 * g_variant_iter_copy().
3050 g_variant_iter_free (GVariantIter *iter)
3052 g_return_if_fail (is_valid_heap_iter (iter));
3054 g_variant_unref (GVHI(iter)->value_ref);
3055 GVHI(iter)->magic = 0;
3057 g_slice_free (struct heap_iter, GVHI(iter));
3061 * g_variant_iter_next_value:
3062 * @iter: a #GVariantIter
3064 * Gets the next item in the container. If no more items remain then
3065 * %NULL is returned.
3067 * Use g_variant_unref() to drop your reference on the return value when
3068 * you no longer need it.
3070 * Here is an example for iterating with g_variant_iter_next_value():
3071 * |[<!-- language="C" -->
3072 * /* recursively iterate a container */
3074 * iterate_container_recursive (GVariant *container)
3076 * GVariantIter iter;
3079 * g_variant_iter_init (&iter, container);
3080 * while ((child = g_variant_iter_next_value (&iter)))
3082 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3084 * if (g_variant_is_container (child))
3085 * iterate_container_recursive (child);
3087 * g_variant_unref (child);
3092 * Returns: (allow-none) (transfer full): a #GVariant, or %NULL
3097 g_variant_iter_next_value (GVariantIter *iter)
3099 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3101 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3103 g_critical ("g_variant_iter_next_value: must not be called again "
3104 "after NULL has already been returned.");
3110 if (GVSI(iter)->i < GVSI(iter)->n)
3111 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3116 /* GVariantBuilder {{{1 */
3120 * A utility type for constructing container-type #GVariant instances.
3122 * This is an opaque structure and may only be accessed using the
3123 * following functions.
3125 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3126 * access it from more than one thread.
3129 struct stack_builder
3131 GVariantBuilder *parent;
3134 /* type constraint explicitly specified by 'type'.
3135 * for tuple types, this moves along as we add more items.
3137 const GVariantType *expected_type;
3139 /* type constraint implied by previous array item.
3141 const GVariantType *prev_item_type;
3143 /* constraints on the number of children. max = -1 for unlimited. */
3147 /* dynamically-growing pointer array */
3148 GVariant **children;
3149 gsize allocated_children;
3152 /* set to '1' if all items in the container will have the same type
3153 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3155 guint uniform_item_types : 1;
3157 /* set to '1' initially and changed to '0' if an untrusted value is
3165 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3169 GVariantBuilder builder;
3175 #define GVSB(b) ((struct stack_builder *) (b))
3176 #define GVHB(b) ((struct heap_builder *) (b))
3177 #define GVSB_MAGIC ((gsize) 1033660112u)
3178 #define GVHB_MAGIC ((gsize) 3087242682u)
3179 #define is_valid_builder(b) (b != NULL && \
3180 GVSB(b)->magic == GVSB_MAGIC)
3181 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3184 * g_variant_builder_new:
3185 * @type: a container type
3187 * Allocates and initialises a new #GVariantBuilder.
3189 * You should call g_variant_builder_unref() on the return value when it
3190 * is no longer needed. The memory will not be automatically freed by
3193 * In most cases it is easier to place a #GVariantBuilder directly on
3194 * the stack of the calling function and initialise it with
3195 * g_variant_builder_init().
3197 * Returns: (transfer full): a #GVariantBuilder
3202 g_variant_builder_new (const GVariantType *type)
3204 GVariantBuilder *builder;
3206 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3207 g_variant_builder_init (builder, type);
3208 GVHB(builder)->magic = GVHB_MAGIC;
3209 GVHB(builder)->ref_count = 1;
3215 * g_variant_builder_unref:
3216 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3218 * Decreases the reference count on @builder.
3220 * In the event that there are no more references, releases all memory
3221 * associated with the #GVariantBuilder.
3223 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3224 * things will happen.
3229 g_variant_builder_unref (GVariantBuilder *builder)
3231 g_return_if_fail (is_valid_heap_builder (builder));
3233 if (--GVHB(builder)->ref_count)
3236 g_variant_builder_clear (builder);
3237 GVHB(builder)->magic = 0;
3239 g_slice_free (struct heap_builder, GVHB(builder));
3243 * g_variant_builder_ref:
3244 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3246 * Increases the reference count on @builder.
3248 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3249 * things will happen.
3251 * Returns: (transfer full): a new reference to @builder
3256 g_variant_builder_ref (GVariantBuilder *builder)
3258 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3260 GVHB(builder)->ref_count++;
3266 * g_variant_builder_clear: (skip)
3267 * @builder: a #GVariantBuilder
3269 * Releases all memory associated with a #GVariantBuilder without
3270 * freeing the #GVariantBuilder structure itself.
3272 * It typically only makes sense to do this on a stack-allocated
3273 * #GVariantBuilder if you want to abort building the value part-way
3274 * through. This function need not be called if you call
3275 * g_variant_builder_end() and it also doesn't need to be called on
3276 * builders allocated with g_variant_builder_new (see
3277 * g_variant_builder_unref() for that).
3279 * This function leaves the #GVariantBuilder structure set to all-zeros.
3280 * It is valid to call this function on either an initialised
3281 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3282 * to call this function on uninitialised memory.
3287 g_variant_builder_clear (GVariantBuilder *builder)
3291 if (GVSB(builder)->magic == 0)
3292 /* all-zeros case */
3295 g_return_if_fail (is_valid_builder (builder));
3297 g_variant_type_free (GVSB(builder)->type);
3299 for (i = 0; i < GVSB(builder)->offset; i++)
3300 g_variant_unref (GVSB(builder)->children[i]);
3302 g_free (GVSB(builder)->children);
3304 if (GVSB(builder)->parent)
3306 g_variant_builder_clear (GVSB(builder)->parent);
3307 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3310 memset (builder, 0, sizeof (GVariantBuilder));
3314 * g_variant_builder_init: (skip)
3315 * @builder: a #GVariantBuilder
3316 * @type: a container type
3318 * Initialises a #GVariantBuilder structure.
3320 * @type must be non-%NULL. It specifies the type of container to
3321 * construct. It can be an indefinite type such as
3322 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3323 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3326 * After the builder is initialised, values are added using
3327 * g_variant_builder_add_value() or g_variant_builder_add().
3329 * After all the child values are added, g_variant_builder_end() frees
3330 * the memory associated with the builder and returns the #GVariant that
3333 * This function completely ignores the previous contents of @builder.
3334 * On one hand this means that it is valid to pass in completely
3335 * uninitialised memory. On the other hand, this means that if you are
3336 * initialising over top of an existing #GVariantBuilder you need to
3337 * first call g_variant_builder_clear() in order to avoid leaking
3340 * You must not call g_variant_builder_ref() or
3341 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3342 * with this function. If you ever pass a reference to a
3343 * #GVariantBuilder outside of the control of your own code then you
3344 * should assume that the person receiving that reference may try to use
3345 * reference counting; you should use g_variant_builder_new() instead of
3351 g_variant_builder_init (GVariantBuilder *builder,
3352 const GVariantType *type)
3354 g_return_if_fail (type != NULL);
3355 g_return_if_fail (g_variant_type_is_container (type));
3357 memset (builder, 0, sizeof (GVariantBuilder));
3359 GVSB(builder)->type = g_variant_type_copy (type);
3360 GVSB(builder)->magic = GVSB_MAGIC;
3361 GVSB(builder)->trusted = TRUE;
3363 switch (*(const gchar *) type)
3365 case G_VARIANT_CLASS_VARIANT:
3366 GVSB(builder)->uniform_item_types = TRUE;
3367 GVSB(builder)->allocated_children = 1;
3368 GVSB(builder)->expected_type = NULL;
3369 GVSB(builder)->min_items = 1;
3370 GVSB(builder)->max_items = 1;
3373 case G_VARIANT_CLASS_ARRAY:
3374 GVSB(builder)->uniform_item_types = TRUE;
3375 GVSB(builder)->allocated_children = 8;
3376 GVSB(builder)->expected_type =
3377 g_variant_type_element (GVSB(builder)->type);
3378 GVSB(builder)->min_items = 0;
3379 GVSB(builder)->max_items = -1;
3382 case G_VARIANT_CLASS_MAYBE:
3383 GVSB(builder)->uniform_item_types = TRUE;
3384 GVSB(builder)->allocated_children = 1;
3385 GVSB(builder)->expected_type =
3386 g_variant_type_element (GVSB(builder)->type);
3387 GVSB(builder)->min_items = 0;
3388 GVSB(builder)->max_items = 1;
3391 case G_VARIANT_CLASS_DICT_ENTRY:
3392 GVSB(builder)->uniform_item_types = FALSE;
3393 GVSB(builder)->allocated_children = 2;
3394 GVSB(builder)->expected_type =
3395 g_variant_type_key (GVSB(builder)->type);
3396 GVSB(builder)->min_items = 2;
3397 GVSB(builder)->max_items = 2;
3400 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3401 GVSB(builder)->uniform_item_types = FALSE;
3402 GVSB(builder)->allocated_children = 8;
3403 GVSB(builder)->expected_type = NULL;
3404 GVSB(builder)->min_items = 0;
3405 GVSB(builder)->max_items = -1;
3408 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3409 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3410 GVSB(builder)->expected_type =
3411 g_variant_type_first (GVSB(builder)->type);
3412 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3413 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3414 GVSB(builder)->uniform_item_types = FALSE;
3418 g_assert_not_reached ();
3421 GVSB(builder)->children = g_new (GVariant *,
3422 GVSB(builder)->allocated_children);
3426 g_variant_builder_make_room (struct stack_builder *builder)
3428 if (builder->offset == builder->allocated_children)
3430 builder->allocated_children *= 2;
3431 builder->children = g_renew (GVariant *, builder->children,
3432 builder->allocated_children);
3437 * g_variant_builder_add_value:
3438 * @builder: a #GVariantBuilder
3439 * @value: a #GVariant
3441 * Adds @value to @builder.
3443 * It is an error to call this function in any way that would create an
3444 * inconsistent value to be constructed. Some examples of this are
3445 * putting different types of items into an array, putting the wrong
3446 * types or number of items in a tuple, putting more than one value into
3449 * If @value is a floating reference (see g_variant_ref_sink()),
3450 * the @builder instance takes ownership of @value.
3455 g_variant_builder_add_value (GVariantBuilder *builder,
3458 g_return_if_fail (is_valid_builder (builder));
3459 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3460 g_return_if_fail (!GVSB(builder)->expected_type ||
3461 g_variant_is_of_type (value,
3462 GVSB(builder)->expected_type));
3463 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3464 g_variant_is_of_type (value,
3465 GVSB(builder)->prev_item_type));
3467 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3469 if (!GVSB(builder)->uniform_item_types)
3471 /* advance our expected type pointers */
3472 if (GVSB(builder)->expected_type)
3473 GVSB(builder)->expected_type =
3474 g_variant_type_next (GVSB(builder)->expected_type);
3476 if (GVSB(builder)->prev_item_type)
3477 GVSB(builder)->prev_item_type =
3478 g_variant_type_next (GVSB(builder)->prev_item_type);
3481 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3483 g_variant_builder_make_room (GVSB(builder));
3485 GVSB(builder)->children[GVSB(builder)->offset++] =
3486 g_variant_ref_sink (value);
3490 * g_variant_builder_open:
3491 * @builder: a #GVariantBuilder
3492 * @type: a #GVariantType
3494 * Opens a subcontainer inside the given @builder. When done adding
3495 * items to the subcontainer, g_variant_builder_close() must be called.
3497 * It is an error to call this function in any way that would cause an
3498 * inconsistent value to be constructed (ie: adding too many values or
3499 * a value of an incorrect type).
3504 g_variant_builder_open (GVariantBuilder *builder,
3505 const GVariantType *type)
3507 GVariantBuilder *parent;
3509 g_return_if_fail (is_valid_builder (builder));
3510 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3511 g_return_if_fail (!GVSB(builder)->expected_type ||
3512 g_variant_type_is_subtype_of (type,
3513 GVSB(builder)->expected_type));
3514 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3515 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3518 parent = g_slice_dup (GVariantBuilder, builder);
3519 g_variant_builder_init (builder, type);
3520 GVSB(builder)->parent = parent;
3522 /* push the prev_item_type down into the subcontainer */
3523 if (GVSB(parent)->prev_item_type)
3525 if (!GVSB(builder)->uniform_item_types)
3526 /* tuples and dict entries */
3527 GVSB(builder)->prev_item_type =
3528 g_variant_type_first (GVSB(parent)->prev_item_type);
3530 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3531 /* maybes and arrays */
3532 GVSB(builder)->prev_item_type =
3533 g_variant_type_element (GVSB(parent)->prev_item_type);
3538 * g_variant_builder_close:
3539 * @builder: a #GVariantBuilder
3541 * Closes the subcontainer inside the given @builder that was opened by
3542 * the most recent call to g_variant_builder_open().
3544 * It is an error to call this function in any way that would create an
3545 * inconsistent value to be constructed (ie: too few values added to the
3551 g_variant_builder_close (GVariantBuilder *builder)
3553 GVariantBuilder *parent;
3555 g_return_if_fail (is_valid_builder (builder));
3556 g_return_if_fail (GVSB(builder)->parent != NULL);
3558 parent = GVSB(builder)->parent;
3559 GVSB(builder)->parent = NULL;
3561 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3564 g_slice_free (GVariantBuilder, parent);
3568 * g_variant_make_maybe_type:
3569 * @element: a #GVariant
3571 * Return the type of a maybe containing @element.
3573 static GVariantType *
3574 g_variant_make_maybe_type (GVariant *element)
3576 return g_variant_type_new_maybe (g_variant_get_type (element));
3580 * g_variant_make_array_type:
3581 * @element: a #GVariant
3583 * Return the type of an array containing @element.
3585 static GVariantType *
3586 g_variant_make_array_type (GVariant *element)
3588 return g_variant_type_new_array (g_variant_get_type (element));
3592 * g_variant_builder_end:
3593 * @builder: a #GVariantBuilder
3595 * Ends the builder process and returns the constructed value.
3597 * It is not permissible to use @builder in any way after this call
3598 * except for reference counting operations (in the case of a
3599 * heap-allocated #GVariantBuilder) or by reinitialising it with
3600 * g_variant_builder_init() (in the case of stack-allocated).
3602 * It is an error to call this function in any way that would create an
3603 * inconsistent value to be constructed (ie: insufficient number of
3604 * items added to a container with a specific number of children
3605 * required). It is also an error to call this function if the builder
3606 * was created with an indefinite array or maybe type and no children
3607 * have been added; in this case it is impossible to infer the type of
3610 * Returns: (transfer none): a new, floating, #GVariant
3615 g_variant_builder_end (GVariantBuilder *builder)
3617 GVariantType *my_type;
3620 g_return_val_if_fail (is_valid_builder (builder), NULL);
3621 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3623 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3624 GVSB(builder)->prev_item_type != NULL ||
3625 g_variant_type_is_definite (GVSB(builder)->type),
3628 if (g_variant_type_is_definite (GVSB(builder)->type))
3629 my_type = g_variant_type_copy (GVSB(builder)->type);
3631 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3632 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3634 else if (g_variant_type_is_array (GVSB(builder)->type))
3635 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3637 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3638 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3639 GVSB(builder)->offset);
3641 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3642 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3643 GVSB(builder)->children[1]);
3645 g_assert_not_reached ();
3647 value = g_variant_new_from_children (my_type,
3648 g_renew (GVariant *,
3649 GVSB(builder)->children,
3650 GVSB(builder)->offset),
3651 GVSB(builder)->offset,
3652 GVSB(builder)->trusted);
3653 GVSB(builder)->children = NULL;
3654 GVSB(builder)->offset = 0;
3656 g_variant_builder_clear (builder);
3657 g_variant_type_free (my_type);
3662 /* Format strings {{{1 */
3664 * g_variant_format_string_scan:
3665 * @string: a string that may be prefixed with a format string
3666 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3668 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3671 * Checks the string pointed to by @string for starting with a properly
3672 * formed #GVariant varargs format string. If no valid format string is
3673 * found then %FALSE is returned.
3675 * If @string does start with a valid format string then %TRUE is
3676 * returned. If @endptr is non-%NULL then it is updated to point to the
3677 * first character after the format string.
3679 * If @limit is non-%NULL then @limit (and any charater after it) will
3680 * not be accessed and the effect is otherwise equivalent to if the
3681 * character at @limit were nul.
3683 * See the section on <link linkend='gvariant-format-strings'>GVariant
3684 * Format Strings</link>.
3686 * Returns: %TRUE if there was a valid format string
3691 g_variant_format_string_scan (const gchar *string,
3693 const gchar **endptr)
3695 #define next_char() (string == limit ? '\0' : *string++)
3696 #define peek_char() (string == limit ? '\0' : *string)
3699 switch (next_char())
3701 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
3702 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
3703 case 'g': case 'v': case '*': case '?': case 'r':
3707 return g_variant_format_string_scan (string, limit, endptr);
3711 return g_variant_type_string_scan (string, limit, endptr);
3714 while (peek_char() != ')')
3715 if (!g_variant_format_string_scan (string, limit, &string))
3718 next_char(); /* consume ')' */
3728 if (c != 's' && c != 'o' && c != 'g')
3736 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3737 * The terminating null character is considered to be
3738 * part of the string.
3740 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3744 if (!g_variant_format_string_scan (string, limit, &string))
3747 if (next_char() != '}')
3753 if ((c = next_char()) == 'a')
3755 if ((c = next_char()) == '&')
3757 if ((c = next_char()) == 'a')
3759 if ((c = next_char()) == 'y')
3760 break; /* '^a&ay' */
3763 else if (c == 's' || c == 'o')
3764 break; /* '^a&s', '^a&o' */
3769 if ((c = next_char()) == 'y')
3773 else if (c == 's' || c == 'o')
3774 break; /* '^as', '^ao' */
3781 if ((c = next_char()) == 'a')
3783 if ((c = next_char()) == 'y')
3793 if (c != 's' && c != 'o' && c != 'g')
3812 * g_variant_check_format_string:
3813 * @value: a #GVariant
3814 * @format_string: a valid #GVariant format string
3815 * @copy_only: %TRUE to ensure the format string makes deep copies
3817 * Checks if calling g_variant_get() with @format_string on @value would
3818 * be valid from a type-compatibility standpoint. @format_string is
3819 * assumed to be a valid format string (from a syntactic standpoint).
3821 * If @copy_only is %TRUE then this function additionally checks that it
3822 * would be safe to call g_variant_unref() on @value immediately after
3823 * the call to g_variant_get() without invalidating the result. This is
3824 * only possible if deep copies are made (ie: there are no pointers to
3825 * the data inside of the soon-to-be-freed #GVariant instance). If this
3826 * check fails then a g_critical() is printed and %FALSE is returned.
3828 * This function is meant to be used by functions that wish to provide
3829 * varargs accessors to #GVariant values of uncertain values (eg:
3830 * g_variant_lookup() or g_menu_model_get_item_attribute()).
3832 * Returns: %TRUE if @format_string is safe to use
3837 g_variant_check_format_string (GVariant *value,
3838 const gchar *format_string,
3841 const gchar *original_format = format_string;
3842 const gchar *type_string;
3844 /* Interesting factoid: assuming a format string is valid, it can be
3845 * converted to a type string by removing all '@' '&' and '^'
3848 * Instead of doing that, we can just skip those characters when
3849 * comparing it to the type string of @value.
3851 * For the copy-only case we can just drop the '&' from the list of
3852 * characters to skip over. A '&' will never appear in a type string
3853 * so we know that it won't be possible to return %TRUE if it is in a
3856 type_string = g_variant_get_type_string (value);
3858 while (*type_string || *format_string)
3860 gchar format = *format_string++;
3865 if G_UNLIKELY (copy_only)
3867 /* for the love of all that is good, please don't mark this string for translation... */
3868 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
3869 "interface to validate the passed format string for type safety. The passed format "
3870 "(%s) contains a '&' character which would result in a pointer being returned to the "
3871 "data inside of a GVariant instance that may no longer exist by the time the function "
3872 "returns. Modify your code to use a format string without '&'.", original_format);
3879 /* ignore these 2 (or 3) */
3883 /* attempt to consume one of 'bynqiuxthdsog' */
3885 char s = *type_string++;
3887 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
3893 /* ensure it's a tuple */
3894 if (*type_string != '(')
3899 /* consume a full type string for the '*' or 'r' */
3900 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
3906 /* attempt to consume exactly one character equal to the format */
3907 if (format != *type_string++)
3916 * g_variant_format_string_scan_type:
3917 * @string: a string that may be prefixed with a format string
3918 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3920 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3923 * If @string starts with a valid format string then this function will
3924 * return the type that the format string corresponds to. Otherwise
3925 * this function returns %NULL.
3927 * Use g_variant_type_free() to free the return value when you no longer
3930 * This function is otherwise exactly like
3931 * g_variant_format_string_scan().
3933 * Returns: (allow-none): a #GVariantType if there was a valid format string
3938 g_variant_format_string_scan_type (const gchar *string,
3940 const gchar **endptr)
3942 const gchar *my_end;
3949 if (!g_variant_format_string_scan (string, limit, endptr))
3952 dest = new = g_malloc (*endptr - string + 1);
3953 while (string != *endptr)
3955 if (*string != '@' && *string != '&' && *string != '^')
3961 return (GVariantType *) G_VARIANT_TYPE (new);
3965 valid_format_string (const gchar *format_string,
3969 const gchar *endptr;
3972 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3974 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3977 g_critical ("'%s' is not a valid GVariant format string",
3980 g_critical ("'%s' does not have a valid GVariant format "
3981 "string as a prefix", format_string);
3984 g_variant_type_free (type);
3989 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3994 fragment = g_strndup (format_string, endptr - format_string);
3995 typestr = g_variant_type_dup_string (type);
3997 g_critical ("the GVariant format string '%s' has a type of "
3998 "'%s' but the given value has a type of '%s'",
3999 fragment, typestr, g_variant_get_type_string (value));
4001 g_variant_type_free (type);
4008 g_variant_type_free (type);
4013 /* Variable Arguments {{{1 */
4014 /* We consider 2 main classes of format strings:
4016 * - recursive format strings
4017 * these are ones that result in recursion and the collection of
4018 * possibly more than one argument. Maybe types, tuples,
4019 * dictionary entries.
4021 * - leaf format string
4022 * these result in the collection of a single argument.
4024 * Leaf format strings are further subdivided into two categories:
4026 * - single non-null pointer ("nnp")
4027 * these either collect or return a single non-null pointer.
4030 * these collect or return something else (bool, number, etc).
4032 * Based on the above, the varargs handling code is split into 4 main parts:
4034 * - nnp handling code
4035 * - leaf handling code (which may invoke nnp code)
4036 * - generic handling code (may be recursive, may invoke leaf code)
4037 * - user-facing API (which invokes the generic code)
4039 * Each section implements some of the following functions:
4042 * collect the arguments for the format string as if
4043 * g_variant_new() had been called, but do nothing with them. used
4044 * for skipping over arguments when constructing a Nothing maybe
4048 * create a GVariant *
4051 * unpack a GVariant *
4053 * - free (nnp only):
4054 * free a previously allocated item
4058 g_variant_format_string_is_leaf (const gchar *str)
4060 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4064 g_variant_format_string_is_nnp (const gchar *str)
4066 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4067 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4068 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4071 /* Single non-null pointer ("nnp") {{{2 */
4073 g_variant_valist_free_nnp (const gchar *str,
4079 g_variant_iter_free (ptr);
4083 if (str[2] != '&') /* '^as', '^ao' */
4085 else /* '^a&s', '^a&o' */
4099 g_variant_unref (ptr);
4106 g_assert_not_reached ();
4111 g_variant_scan_convenience (const gchar **str,
4134 g_variant_valist_new_nnp (const gchar **str,
4145 const GVariantType *type;
4148 value = g_variant_builder_end (ptr);
4149 type = g_variant_get_type (value);
4151 if G_UNLIKELY (!g_variant_type_is_array (type))
4152 g_error ("g_variant_new: expected array GVariantBuilder but "
4153 "the built value has type '%s'",
4154 g_variant_get_type_string (value));
4156 type = g_variant_type_element (type);
4158 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4159 g_error ("g_variant_new: expected GVariantBuilder array element "
4160 "type '%s' but the built value has element type '%s'",
4161 g_variant_type_dup_string ((GVariantType *) *str),
4162 g_variant_get_type_string (value) + 1);
4164 g_variant_type_string_scan (*str, NULL, str);
4170 /* special case: NULL pointer for empty array */
4172 const GVariantType *type = (GVariantType *) *str;
4174 g_variant_type_string_scan (*str, NULL, str);
4176 if G_UNLIKELY (!g_variant_type_is_definite (type))
4177 g_error ("g_variant_new: NULL pointer given with indefinite "
4178 "array type; unable to determine which type of empty "
4179 "array to construct.");
4181 return g_variant_new_array (type, NULL, 0);
4188 value = g_variant_new_string (ptr);
4191 value = g_variant_new_string ("[Invalid UTF-8]");
4197 return g_variant_new_object_path (ptr);
4200 return g_variant_new_signature (ptr);
4208 type = g_variant_scan_convenience (str, &constant, &arrays);
4211 return g_variant_new_strv (ptr, -1);
4214 return g_variant_new_objv (ptr, -1);
4217 return g_variant_new_bytestring_array (ptr, -1);
4219 return g_variant_new_bytestring (ptr);
4223 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4224 g_error ("g_variant_new: expected GVariant of type '%s' but "
4225 "received value has type '%s'",
4226 g_variant_type_dup_string ((GVariantType *) *str),
4227 g_variant_get_type_string (ptr));
4229 g_variant_type_string_scan (*str, NULL, str);
4237 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4238 g_error ("g_variant_new: format string '?' expects basic-typed "
4239 "GVariant, but received value has type '%s'",
4240 g_variant_get_type_string (ptr));
4245 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4246 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4247 "GVariant, but received value has type '%s'",
4248 g_variant_get_type_string (ptr));
4253 return g_variant_new_variant (ptr);
4256 g_assert_not_reached ();
4261 g_variant_valist_get_nnp (const gchar **str,
4267 g_variant_type_string_scan (*str, NULL, str);
4268 return g_variant_iter_new (value);
4272 return (gchar *) g_variant_get_string (value, NULL);
4277 return g_variant_dup_string (value, NULL);
4285 type = g_variant_scan_convenience (str, &constant, &arrays);
4290 return g_variant_get_strv (value, NULL);
4292 return g_variant_dup_strv (value, NULL);
4295 else if (type == 'o')
4298 return g_variant_get_objv (value, NULL);
4300 return g_variant_dup_objv (value, NULL);
4303 else if (arrays > 1)
4306 return g_variant_get_bytestring_array (value, NULL);
4308 return g_variant_dup_bytestring_array (value, NULL);
4314 return (gchar *) g_variant_get_bytestring (value);
4316 return g_variant_dup_bytestring (value, NULL);
4321 g_variant_type_string_scan (*str, NULL, str);
4327 return g_variant_ref (value);
4330 return g_variant_get_variant (value);
4333 g_assert_not_reached ();
4339 g_variant_valist_skip_leaf (const gchar **str,
4342 if (g_variant_format_string_is_nnp (*str))
4344 g_variant_format_string_scan (*str, NULL, str);
4345 va_arg (*app, gpointer);
4363 va_arg (*app, guint64);
4367 va_arg (*app, gdouble);
4371 g_assert_not_reached ();
4376 g_variant_valist_new_leaf (const gchar **str,
4379 if (g_variant_format_string_is_nnp (*str))
4380 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4385 return g_variant_new_boolean (va_arg (*app, gboolean));
4388 return g_variant_new_byte (va_arg (*app, guint));
4391 return g_variant_new_int16 (va_arg (*app, gint));
4394 return g_variant_new_uint16 (va_arg (*app, guint));
4397 return g_variant_new_int32 (va_arg (*app, gint));
4400 return g_variant_new_uint32 (va_arg (*app, guint));
4403 return g_variant_new_int64 (va_arg (*app, gint64));
4406 return g_variant_new_uint64 (va_arg (*app, guint64));
4409 return g_variant_new_handle (va_arg (*app, gint));
4412 return g_variant_new_double (va_arg (*app, gdouble));
4415 g_assert_not_reached ();
4419 /* The code below assumes this */
4420 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4421 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4424 g_variant_valist_get_leaf (const gchar **str,
4429 gpointer ptr = va_arg (*app, gpointer);
4433 g_variant_format_string_scan (*str, NULL, str);
4437 if (g_variant_format_string_is_nnp (*str))
4439 gpointer *nnp = (gpointer *) ptr;
4441 if (free && *nnp != NULL)
4442 g_variant_valist_free_nnp (*str, *nnp);
4447 *nnp = g_variant_valist_get_nnp (str, value);
4449 g_variant_format_string_scan (*str, NULL, str);
4459 *(gboolean *) ptr = g_variant_get_boolean (value);
4463 *(guchar *) ptr = g_variant_get_byte (value);
4467 *(gint16 *) ptr = g_variant_get_int16 (value);
4471 *(guint16 *) ptr = g_variant_get_uint16 (value);
4475 *(gint32 *) ptr = g_variant_get_int32 (value);
4479 *(guint32 *) ptr = g_variant_get_uint32 (value);
4483 *(gint64 *) ptr = g_variant_get_int64 (value);
4487 *(guint64 *) ptr = g_variant_get_uint64 (value);
4491 *(gint32 *) ptr = g_variant_get_handle (value);
4495 *(gdouble *) ptr = g_variant_get_double (value);
4504 *(guchar *) ptr = 0;
4509 *(guint16 *) ptr = 0;
4516 *(guint32 *) ptr = 0;
4522 *(guint64 *) ptr = 0;
4527 g_assert_not_reached ();
4530 /* Generic (recursive) {{{2 */
4532 g_variant_valist_skip (const gchar **str,
4535 if (g_variant_format_string_is_leaf (*str))
4536 g_variant_valist_skip_leaf (str, app);
4538 else if (**str == 'm') /* maybe */
4542 if (!g_variant_format_string_is_nnp (*str))
4543 va_arg (*app, gboolean);
4545 g_variant_valist_skip (str, app);
4547 else /* tuple, dictionary entry */
4549 g_assert (**str == '(' || **str == '{');
4551 while (**str != ')' && **str != '}')
4552 g_variant_valist_skip (str, app);
4558 g_variant_valist_new (const gchar **str,
4561 if (g_variant_format_string_is_leaf (*str))
4562 return g_variant_valist_new_leaf (str, app);
4564 if (**str == 'm') /* maybe */
4566 GVariantType *type = NULL;
4567 GVariant *value = NULL;
4571 if (g_variant_format_string_is_nnp (*str))
4573 gpointer nnp = va_arg (*app, gpointer);
4576 value = g_variant_valist_new_nnp (str, nnp);
4578 type = g_variant_format_string_scan_type (*str, NULL, str);
4582 gboolean just = va_arg (*app, gboolean);
4585 value = g_variant_valist_new (str, app);
4588 type = g_variant_format_string_scan_type (*str, NULL, NULL);
4589 g_variant_valist_skip (str, app);
4593 value = g_variant_new_maybe (type, value);
4596 g_variant_type_free (type);
4600 else /* tuple, dictionary entry */
4605 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
4608 g_assert (**str == '{');
4609 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
4613 while (**str != ')' && **str != '}')
4614 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
4617 return g_variant_builder_end (&b);
4622 g_variant_valist_get (const gchar **str,
4627 if (g_variant_format_string_is_leaf (*str))
4628 g_variant_valist_get_leaf (str, value, free, app);
4630 else if (**str == 'm')
4635 value = g_variant_get_maybe (value);
4637 if (!g_variant_format_string_is_nnp (*str))
4639 gboolean *ptr = va_arg (*app, gboolean *);
4642 *ptr = value != NULL;
4645 g_variant_valist_get (str, value, free, app);
4648 g_variant_unref (value);
4651 else /* tuple, dictionary entry */
4655 g_assert (**str == '(' || **str == '{');
4658 while (**str != ')' && **str != '}')
4662 GVariant *child = g_variant_get_child_value (value, index++);
4663 g_variant_valist_get (str, child, free, app);
4664 g_variant_unref (child);
4667 g_variant_valist_get (str, NULL, free, app);
4673 /* User-facing API {{{2 */
4675 * g_variant_new: (skip)
4676 * @format_string: a #GVariant format string
4677 * @...: arguments, as per @format_string
4679 * Creates a new #GVariant instance.
4681 * Think of this function as an analogue to g_strdup_printf().
4683 * The type of the created instance and the arguments that are
4684 * expected by this function are determined by @format_string. See the
4685 * section on <link linkend='gvariant-format-strings'>GVariant Format
4686 * Strings</link>. Please note that the syntax of the format string is
4687 * very likely to be extended in the future.
4689 * The first character of the format string must not be '*' '?' '@' or
4690 * 'r'; in essence, a new #GVariant must always be constructed by this
4691 * function (and not merely passed through it unmodified).
4693 * Returns: a new floating #GVariant instance
4698 g_variant_new (const gchar *format_string,
4704 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
4705 format_string[0] != '?' && format_string[0] != '@' &&
4706 format_string[0] != '*' && format_string[0] != 'r',
4709 va_start (ap, format_string);
4710 value = g_variant_new_va (format_string, NULL, &ap);
4717 * g_variant_new_va: (skip)
4718 * @format_string: a string that is prefixed with a format string
4719 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4721 * @app: a pointer to a #va_list
4723 * This function is intended to be used by libraries based on
4724 * #GVariant that want to provide g_variant_new()-like functionality
4727 * The API is more general than g_variant_new() to allow a wider range
4730 * @format_string must still point to a valid format string, but it only
4731 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
4732 * non-%NULL then it is updated to point to the first character past the
4733 * end of the format string.
4735 * @app is a pointer to a #va_list. The arguments, according to
4736 * @format_string, are collected from this #va_list and the list is left
4737 * pointing to the argument following the last.
4739 * These two generalisations allow mixing of multiple calls to
4740 * g_variant_new_va() and g_variant_get_va() within a single actual
4741 * varargs call by the user.
4743 * The return value will be floating if it was a newly created GVariant
4744 * instance (for example, if the format string was "(ii)"). In the case
4745 * that the format_string was '*', '?', 'r', or a format starting with
4746 * '@' then the collected #GVariant pointer will be returned unmodified,
4747 * without adding any additional references.
4749 * In order to behave correctly in all cases it is necessary for the
4750 * calling function to g_variant_ref_sink() the return result before
4751 * returning control to the user that originally provided the pointer.
4752 * At this point, the caller will have their own full reference to the
4753 * result. This can also be done by adding the result to a container,
4754 * or by passing it to another g_variant_new() call.
4756 * Returns: a new, usually floating, #GVariant
4761 g_variant_new_va (const gchar *format_string,
4762 const gchar **endptr,
4767 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
4769 g_return_val_if_fail (app != NULL, NULL);
4771 value = g_variant_valist_new (&format_string, app);
4774 *endptr = format_string;
4780 * g_variant_get: (skip)
4781 * @value: a #GVariant instance
4782 * @format_string: a #GVariant format string
4783 * @...: arguments, as per @format_string
4785 * Deconstructs a #GVariant instance.
4787 * Think of this function as an analogue to scanf().
4789 * The arguments that are expected by this function are entirely
4790 * determined by @format_string. @format_string also restricts the
4791 * permissible types of @value. It is an error to give a value with
4792 * an incompatible type. See the section on <link
4793 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
4794 * Please note that the syntax of the format string is very likely to be
4795 * extended in the future.
4797 * @format_string determines the C types that are used for unpacking
4798 * the values and also determines if the values are copied or borrowed,
4799 * see the section on
4800 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4805 g_variant_get (GVariant *value,
4806 const gchar *format_string,
4811 g_return_if_fail (valid_format_string (format_string, TRUE, value));
4813 /* if any direct-pointer-access formats are in use, flatten first */
4814 if (strchr (format_string, '&'))
4815 g_variant_get_data (value);
4817 va_start (ap, format_string);
4818 g_variant_get_va (value, format_string, NULL, &ap);
4823 * g_variant_get_va: (skip)
4824 * @value: a #GVariant
4825 * @format_string: a string that is prefixed with a format string
4826 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4828 * @app: a pointer to a #va_list
4830 * This function is intended to be used by libraries based on #GVariant
4831 * that want to provide g_variant_get()-like functionality to their
4834 * The API is more general than g_variant_get() to allow a wider range
4837 * @format_string must still point to a valid format string, but it only
4838 * need to be nul-terminated if @endptr is %NULL. If @endptr is
4839 * non-%NULL then it is updated to point to the first character past the
4840 * end of the format string.
4842 * @app is a pointer to a #va_list. The arguments, according to
4843 * @format_string, are collected from this #va_list and the list is left
4844 * pointing to the argument following the last.
4846 * These two generalisations allow mixing of multiple calls to
4847 * g_variant_new_va() and g_variant_get_va() within a single actual
4848 * varargs call by the user.
4850 * @format_string determines the C types that are used for unpacking
4851 * the values and also determines if the values are copied or borrowed,
4852 * see the section on
4853 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4858 g_variant_get_va (GVariant *value,
4859 const gchar *format_string,
4860 const gchar **endptr,
4863 g_return_if_fail (valid_format_string (format_string, !endptr, value));
4864 g_return_if_fail (value != NULL);
4865 g_return_if_fail (app != NULL);
4867 /* if any direct-pointer-access formats are in use, flatten first */
4868 if (strchr (format_string, '&'))
4869 g_variant_get_data (value);
4871 g_variant_valist_get (&format_string, value, FALSE, app);
4874 *endptr = format_string;
4877 /* Varargs-enabled Utility Functions {{{1 */
4880 * g_variant_builder_add: (skip)
4881 * @builder: a #GVariantBuilder
4882 * @format_string: a #GVariant varargs format string
4883 * @...: arguments, as per @format_string
4885 * Adds to a #GVariantBuilder.
4887 * This call is a convenience wrapper that is exactly equivalent to
4888 * calling g_variant_new() followed by g_variant_builder_add_value().
4890 * This function might be used as follows:
4892 * |[<!-- language="C" -->
4894 * make_pointless_dictionary (void)
4896 * GVariantBuilder builder;
4899 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
4900 * for (i = 0; i < 16; i++)
4904 * sprintf (buf, "%d", i);
4905 * g_variant_builder_add (&builder, "{is}", i, buf);
4908 * return g_variant_builder_end (&builder);
4915 g_variant_builder_add (GVariantBuilder *builder,
4916 const gchar *format_string,
4922 va_start (ap, format_string);
4923 variant = g_variant_new_va (format_string, NULL, &ap);
4926 g_variant_builder_add_value (builder, variant);
4930 * g_variant_get_child: (skip)
4931 * @value: a container #GVariant
4932 * @index_: the index of the child to deconstruct
4933 * @format_string: a #GVariant format string
4934 * @...: arguments, as per @format_string
4936 * Reads a child item out of a container #GVariant instance and
4937 * deconstructs it according to @format_string. This call is
4938 * essentially a combination of g_variant_get_child_value() and
4941 * @format_string determines the C types that are used for unpacking
4942 * the values and also determines if the values are copied or borrowed,
4943 * see the section on
4944 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4949 g_variant_get_child (GVariant *value,
4951 const gchar *format_string,
4957 child = g_variant_get_child_value (value, index_);
4958 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4960 va_start (ap, format_string);
4961 g_variant_get_va (child, format_string, NULL, &ap);
4964 g_variant_unref (child);
4968 * g_variant_iter_next: (skip)
4969 * @iter: a #GVariantIter
4970 * @format_string: a GVariant format string
4971 * @...: the arguments to unpack the value into
4973 * Gets the next item in the container and unpacks it into the variable
4974 * argument list according to @format_string, returning %TRUE.
4976 * If no more items remain then %FALSE is returned.
4978 * All of the pointers given on the variable arguments list of this
4979 * function are assumed to point at uninitialised memory. It is the
4980 * responsibility of the caller to free all of the values returned by
4981 * the unpacking process.
4983 * Here is an example for memory management with g_variant_iter_next():
4984 * |[<!-- language="C" -->
4985 * /* Iterates a dictionary of type 'a{sv}' */
4987 * iterate_dictionary (GVariant *dictionary)
4989 * GVariantIter iter;
4993 * g_variant_iter_init (&iter, dictionary);
4994 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4996 * g_print ("Item '%s' has type '%s'\n", key,
4997 * g_variant_get_type_string (value));
4999 * /* must free data for ourselves */
5000 * g_variant_unref (value);
5006 * For a solution that is likely to be more convenient to C programmers
5007 * when dealing with loops, see g_variant_iter_loop().
5009 * @format_string determines the C types that are used for unpacking
5010 * the values and also determines if the values are copied or borrowed.
5012 * See the section on
5013 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5015 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5020 g_variant_iter_next (GVariantIter *iter,
5021 const gchar *format_string,
5026 value = g_variant_iter_next_value (iter);
5028 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5035 va_start (ap, format_string);
5036 g_variant_valist_get (&format_string, value, FALSE, &ap);
5039 g_variant_unref (value);
5042 return value != NULL;
5046 * g_variant_iter_loop: (skip)
5047 * @iter: a #GVariantIter
5048 * @format_string: a GVariant format string
5049 * @...: the arguments to unpack the value into
5051 * Gets the next item in the container and unpacks it into the variable
5052 * argument list according to @format_string, returning %TRUE.
5054 * If no more items remain then %FALSE is returned.
5056 * On the first call to this function, the pointers appearing on the
5057 * variable argument list are assumed to point at uninitialised memory.
5058 * On the second and later calls, it is assumed that the same pointers
5059 * will be given and that they will point to the memory as set by the
5060 * previous call to this function. This allows the previous values to
5061 * be freed, as appropriate.
5063 * This function is intended to be used with a while loop as
5064 * demonstrated in the following example. This function can only be
5065 * used when iterating over an array. It is only valid to call this
5066 * function with a string constant for the format string and the same
5067 * string constant must be used each time. Mixing calls to this
5068 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5069 * the same iterator causes undefined behavior.
5071 * If you break out of a such a while loop using g_variant_iter_loop() then
5072 * you must free or unreference all the unpacked values as you would with
5073 * g_variant_get(). Failure to do so will cause a memory leak.
5075 * Here is an example for memory management with g_variant_iter_loop():
5076 * |[<!-- language="C" -->
5077 * /* Iterates a dictionary of type 'a{sv}' */
5079 * iterate_dictionary (GVariant *dictionary)
5081 * GVariantIter iter;
5085 * g_variant_iter_init (&iter, dictionary);
5086 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5088 * g_print ("Item '%s' has type '%s'\n", key,
5089 * g_variant_get_type_string (value));
5091 * /* no need to free 'key' and 'value' here
5092 * * unless breaking out of this loop
5098 * For most cases you should use g_variant_iter_next().
5100 * This function is really only useful when unpacking into #GVariant or
5101 * #GVariantIter in order to allow you to skip the call to
5102 * g_variant_unref() or g_variant_iter_free().
5104 * For example, if you are only looping over simple integer and string
5105 * types, g_variant_iter_next() is definitely preferred. For string
5106 * types, use the '&' prefix to avoid allocating any memory at all (and
5107 * thereby avoiding the need to free anything as well).
5109 * @format_string determines the C types that are used for unpacking
5110 * the values and also determines if the values are copied or borrowed.
5112 * See the section on
5113 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5115 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5121 g_variant_iter_loop (GVariantIter *iter,
5122 const gchar *format_string,
5125 gboolean first_time = GVSI(iter)->loop_format == NULL;
5129 g_return_val_if_fail (first_time ||
5130 format_string == GVSI(iter)->loop_format,
5135 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5136 GVSI(iter)->loop_format = format_string;
5138 if (strchr (format_string, '&'))
5139 g_variant_get_data (GVSI(iter)->value);
5142 value = g_variant_iter_next_value (iter);
5144 g_return_val_if_fail (!first_time ||
5145 valid_format_string (format_string, TRUE, value),
5148 va_start (ap, format_string);
5149 g_variant_valist_get (&format_string, value, !first_time, &ap);
5153 g_variant_unref (value);
5155 return value != NULL;
5158 /* Serialised data {{{1 */
5160 g_variant_deep_copy (GVariant *value)
5162 switch (g_variant_classify (value))
5164 case G_VARIANT_CLASS_MAYBE:
5165 case G_VARIANT_CLASS_ARRAY:
5166 case G_VARIANT_CLASS_TUPLE:
5167 case G_VARIANT_CLASS_DICT_ENTRY:
5168 case G_VARIANT_CLASS_VARIANT:
5170 GVariantBuilder builder;
5174 g_variant_builder_init (&builder, g_variant_get_type (value));
5175 g_variant_iter_init (&iter, value);
5177 while ((child = g_variant_iter_next_value (&iter)))
5179 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5180 g_variant_unref (child);
5183 return g_variant_builder_end (&builder);
5186 case G_VARIANT_CLASS_BOOLEAN:
5187 return g_variant_new_boolean (g_variant_get_boolean (value));
5189 case G_VARIANT_CLASS_BYTE:
5190 return g_variant_new_byte (g_variant_get_byte (value));
5192 case G_VARIANT_CLASS_INT16:
5193 return g_variant_new_int16 (g_variant_get_int16 (value));
5195 case G_VARIANT_CLASS_UINT16:
5196 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5198 case G_VARIANT_CLASS_INT32:
5199 return g_variant_new_int32 (g_variant_get_int32 (value));
5201 case G_VARIANT_CLASS_UINT32:
5202 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5204 case G_VARIANT_CLASS_INT64:
5205 return g_variant_new_int64 (g_variant_get_int64 (value));
5207 case G_VARIANT_CLASS_UINT64:
5208 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5210 case G_VARIANT_CLASS_HANDLE:
5211 return g_variant_new_handle (g_variant_get_handle (value));
5213 case G_VARIANT_CLASS_DOUBLE:
5214 return g_variant_new_double (g_variant_get_double (value));
5216 case G_VARIANT_CLASS_STRING:
5217 return g_variant_new_string (g_variant_get_string (value, NULL));
5219 case G_VARIANT_CLASS_OBJECT_PATH:
5220 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5222 case G_VARIANT_CLASS_SIGNATURE:
5223 return g_variant_new_signature (g_variant_get_string (value, NULL));
5226 g_assert_not_reached ();
5230 * g_variant_get_normal_form:
5231 * @value: a #GVariant
5233 * Gets a #GVariant instance that has the same value as @value and is
5234 * trusted to be in normal form.
5236 * If @value is already trusted to be in normal form then a new
5237 * reference to @value is returned.
5239 * If @value is not already trusted, then it is scanned to check if it
5240 * is in normal form. If it is found to be in normal form then it is
5241 * marked as trusted and a new reference to it is returned.
5243 * If @value is found not to be in normal form then a new trusted
5244 * #GVariant is created with the same value as @value.
5246 * It makes sense to call this function if you've received #GVariant
5247 * data from untrusted sources and you want to ensure your serialised
5248 * output is definitely in normal form.
5250 * Returns: (transfer full): a trusted #GVariant
5255 g_variant_get_normal_form (GVariant *value)
5259 if (g_variant_is_normal_form (value))
5260 return g_variant_ref (value);
5262 trusted = g_variant_deep_copy (value);
5263 g_assert (g_variant_is_trusted (trusted));
5265 return g_variant_ref_sink (trusted);
5269 * g_variant_byteswap:
5270 * @value: a #GVariant
5272 * Performs a byteswapping operation on the contents of @value. The
5273 * result is that all multi-byte numeric data contained in @value is
5274 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5275 * integers as well as file handles and double precision floating point
5278 * This function is an identity mapping on any value that does not
5279 * contain multi-byte numeric data. That include strings, booleans,
5280 * bytes and containers containing only these things (recursively).
5282 * The returned value is always in normal form and is marked as trusted.
5284 * Returns: (transfer full): the byteswapped form of @value
5289 g_variant_byteswap (GVariant *value)
5291 GVariantTypeInfo *type_info;
5295 type_info = g_variant_get_type_info (value);
5297 g_variant_type_info_query (type_info, &alignment, NULL);
5300 /* (potentially) contains multi-byte numeric data */
5302 GVariantSerialised serialised;
5306 trusted = g_variant_get_normal_form (value);
5307 serialised.type_info = g_variant_get_type_info (trusted);
5308 serialised.size = g_variant_get_size (trusted);
5309 serialised.data = g_malloc (serialised.size);
5310 g_variant_store (trusted, serialised.data);
5311 g_variant_unref (trusted);
5313 g_variant_serialised_byteswap (serialised);
5315 bytes = g_bytes_new_take (serialised.data, serialised.size);
5316 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5317 g_bytes_unref (bytes);
5320 /* contains no multi-byte data */
5323 return g_variant_ref_sink (new);
5327 * g_variant_new_from_data:
5328 * @type: a definite #GVariantType
5329 * @data: (array length=size) (element-type guint8): the serialised data
5330 * @size: the size of @data
5331 * @trusted: %TRUE if @data is definitely in normal form
5332 * @notify: (scope async): function to call when @data is no longer needed
5333 * @user_data: data for @notify
5335 * Creates a new #GVariant instance from serialised data.
5337 * @type is the type of #GVariant instance that will be constructed.
5338 * The interpretation of @data depends on knowing the type.
5340 * @data is not modified by this function and must remain valid with an
5341 * unchanging value until such a time as @notify is called with
5342 * @user_data. If the contents of @data change before that time then
5343 * the result is undefined.
5345 * If @data is trusted to be serialised data in normal form then
5346 * @trusted should be %TRUE. This applies to serialised data created
5347 * within this process or read from a trusted location on the disk (such
5348 * as a file installed in /usr/lib alongside your application). You
5349 * should set trusted to %FALSE if @data is read from the network, a
5350 * file in the user's home directory, etc.
5352 * If @data was not stored in this machine's native endianness, any multi-byte
5353 * numeric values in the returned variant will also be in non-native
5354 * endianness. g_variant_byteswap() can be used to recover the original values.
5356 * @notify will be called with @user_data when @data is no longer
5357 * needed. The exact time of this call is unspecified and might even be
5358 * before this function returns.
5360 * Returns: (transfer none): a new floating #GVariant of type @type
5365 g_variant_new_from_data (const GVariantType *type,
5369 GDestroyNotify notify,
5375 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5376 g_return_val_if_fail (data != NULL || size == 0, NULL);
5379 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5381 bytes = g_bytes_new_static (data, size);
5383 value = g_variant_new_from_bytes (type, bytes, trusted);
5384 g_bytes_unref (bytes);
5390 /* vim:set foldmethod=marker: */