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 32bit 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 32bit 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
1005 * <literal>a{s*}</literal> (and equally well with type
1006 * <literal>a{o*}</literal>, but we only further discuss the string case
1007 * for sake of clarity).
1009 * In the event that @dictionary has the type <literal>a{sv}</literal>,
1010 * the @expected_type string specifies what type of value is expected to
1011 * be inside of the variant. If the value inside the variant has a
1012 * different type then %NULL is returned. In the event that @dictionary
1013 * has a value type other than <literal>v</literal> then @expected_type
1014 * must directly match the key type and it is used to unpack the value
1015 * directly or an error occurs.
1017 * In either case, if @key is not found in @dictionary, %NULL is
1020 * If the key is found and the value has the correct type, it is
1021 * returned. If @expected_type was specified then any non-%NULL return
1022 * value will have this type.
1024 * Returns: (transfer full): the value of the dictionary key, or %NULL
1029 g_variant_lookup_value (GVariant *dictionary,
1031 const GVariantType *expected_type)
1037 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1038 G_VARIANT_TYPE ("a{s*}")) ||
1039 g_variant_is_of_type (dictionary,
1040 G_VARIANT_TYPE ("a{o*}")),
1043 g_variant_iter_init (&iter, dictionary);
1045 while ((entry = g_variant_iter_next_value (&iter)))
1047 GVariant *entry_key;
1050 entry_key = g_variant_get_child_value (entry, 0);
1051 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1052 g_variant_unref (entry_key);
1057 g_variant_unref (entry);
1063 value = g_variant_get_child_value (entry, 1);
1064 g_variant_unref (entry);
1066 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1070 tmp = g_variant_get_variant (value);
1071 g_variant_unref (value);
1073 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1075 g_variant_unref (tmp);
1082 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1083 g_variant_is_of_type (value, expected_type), NULL);
1089 * g_variant_get_fixed_array:
1090 * @value: a #GVariant array with fixed-sized elements
1091 * @n_elements: (out): a pointer to the location to store the number of items
1092 * @element_size: the size of each element
1094 * Provides access to the serialised data for an array of fixed-sized
1097 * @value must be an array with fixed-sized elements. Numeric types are
1098 * fixed-size, as are tuples containing only other fixed-sized types.
1100 * @element_size must be the size of a single element in the array,
1101 * as given by the section on
1102 * <link linkend='gvariant-serialised-data-memory'>Serialised Data
1105 * In particular, arrays of these fixed-sized types can be interpreted
1106 * as an array of the given C type, with @element_size set to
1107 * <code>sizeof</code> the appropriate type:
1111 * <thead><row><entry>element type</entry> <entry>C type</entry></row></thead>
1113 * <row><entry>%G_VARIANT_TYPE_INT16 (etc.)</entry>
1114 * <entry>#gint16 (etc.)</entry></row>
1115 * <row><entry>%G_VARIANT_TYPE_BOOLEAN</entry>
1116 * <entry>#guchar (not #gboolean!)</entry></row>
1117 * <row><entry>%G_VARIANT_TYPE_BYTE</entry> <entry>#guchar</entry></row>
1118 * <row><entry>%G_VARIANT_TYPE_HANDLE</entry> <entry>#guint32</entry></row>
1119 * <row><entry>%G_VARIANT_TYPE_DOUBLE</entry> <entry>#gdouble</entry></row>
1124 * For example, if calling this function for an array of 32 bit integers,
1125 * you might say <code>sizeof (gint32)</code>. This value isn't used
1126 * except for the purpose of a double-check that the form of the
1127 * serialised data matches the caller's expectation.
1129 * @n_elements, which must be non-%NULL is set equal to the number of
1130 * items in the array.
1132 * Returns: (array length=n_elements) (transfer none): a pointer to
1138 g_variant_get_fixed_array (GVariant *value,
1142 GVariantTypeInfo *array_info;
1143 gsize array_element_size;
1147 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1149 g_return_val_if_fail (n_elements != NULL, NULL);
1150 g_return_val_if_fail (element_size > 0, NULL);
1152 array_info = g_variant_get_type_info (value);
1153 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1155 g_return_val_if_fail (array_element_size, NULL);
1157 if G_UNLIKELY (array_element_size != element_size)
1159 if (array_element_size)
1160 g_critical ("g_variant_get_fixed_array: assertion "
1161 "'g_variant_array_has_fixed_size (value, element_size)' "
1162 "failed: array size %"G_GSIZE_FORMAT" does not match "
1163 "given element_size %"G_GSIZE_FORMAT".",
1164 array_element_size, element_size);
1166 g_critical ("g_variant_get_fixed_array: assertion "
1167 "'g_variant_array_has_fixed_size (value, element_size)' "
1168 "failed: array does not have fixed size.");
1171 data = g_variant_get_data (value);
1172 size = g_variant_get_size (value);
1174 if (size % element_size)
1177 *n_elements = size / element_size;
1186 * g_variant_new_fixed_array:
1187 * @element_type: the #GVariantType of each element
1188 * @elements: a pointer to the fixed array of contiguous elements
1189 * @n_elements: the number of elements
1190 * @element_size: the size of each element
1192 * Provides access to the serialised data for an array of fixed-sized
1195 * @value must be an array with fixed-sized elements. Numeric types are
1196 * fixed-size as are tuples containing only other fixed-sized types.
1198 * @element_size must be the size of a single element in the array. For
1199 * example, if calling this function for an array of 32 bit integers,
1200 * you might say <code>sizeof (gint32)</code>. This value isn't used
1201 * except for the purpose of a double-check that the form of the
1202 * serialised data matches the caller's expectation.
1204 * @n_elements, which must be non-%NULL is set equal to the number of
1205 * items in the array.
1207 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1212 g_variant_new_fixed_array (const GVariantType *element_type,
1213 gconstpointer elements,
1217 GVariantType *array_type;
1218 gsize array_element_size;
1219 GVariantTypeInfo *array_info;
1223 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1224 g_return_val_if_fail (element_size > 0, NULL);
1226 array_type = g_variant_type_new_array (element_type);
1227 array_info = g_variant_type_info_get (array_type);
1228 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1229 if G_UNLIKELY (array_element_size != element_size)
1231 if (array_element_size)
1232 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1233 " does not match given element_size %" G_GSIZE_FORMAT ".",
1234 array_element_size, element_size);
1236 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1240 data = g_memdup (elements, n_elements * element_size);
1241 value = g_variant_new_from_data (array_type, data,
1242 n_elements * element_size,
1243 FALSE, g_free, data);
1245 g_variant_type_free (array_type);
1246 g_variant_type_info_unref (array_info);
1251 /* String type constructor/getters/validation {{{1 */
1253 * g_variant_new_string:
1254 * @string: a normal utf8 nul-terminated string
1256 * Creates a string #GVariant with the contents of @string.
1258 * @string must be valid utf8.
1260 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1265 g_variant_new_string (const gchar *string)
1267 g_return_val_if_fail (string != NULL, NULL);
1268 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1270 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1271 string, strlen (string) + 1);
1275 * g_variant_new_take_string: (skip)
1276 * @string: a normal utf8 nul-terminated string
1278 * Creates a string #GVariant with the contents of @string.
1280 * @string must be valid utf8.
1282 * This function consumes @string. g_free() will be called on @string
1283 * when it is no longer required.
1285 * You must not modify or access @string in any other way after passing
1286 * it to this function. It is even possible that @string is immediately
1289 * Returns: (transfer none): a floating reference to a new string
1290 * #GVariant instance
1295 g_variant_new_take_string (gchar *string)
1300 g_return_val_if_fail (string != NULL, NULL);
1301 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1303 bytes = g_bytes_new_take (string, strlen (string) + 1);
1304 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1305 g_bytes_unref (bytes);
1311 * g_variant_new_printf: (skip)
1312 * @format_string: a printf-style format string
1313 * @...: arguments for @format_string
1315 * Creates a string-type GVariant using printf formatting.
1317 * This is similar to calling g_strdup_printf() and then
1318 * g_variant_new_string() but it saves a temporary variable and an
1321 * Returns: (transfer none): a floating reference to a new string
1322 * #GVariant instance
1327 g_variant_new_printf (const gchar *format_string,
1335 g_return_val_if_fail (format_string != NULL, NULL);
1337 va_start (ap, format_string);
1338 string = g_strdup_vprintf (format_string, ap);
1341 bytes = g_bytes_new_take (string, strlen (string) + 1);
1342 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1343 g_bytes_unref (bytes);
1349 * g_variant_new_object_path:
1350 * @object_path: a normal C nul-terminated string
1352 * Creates a D-Bus object path #GVariant with the contents of @string.
1353 * @string must be a valid D-Bus object path. Use
1354 * g_variant_is_object_path() if you're not sure.
1356 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1361 g_variant_new_object_path (const gchar *object_path)
1363 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1365 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1366 object_path, strlen (object_path) + 1);
1370 * g_variant_is_object_path:
1371 * @string: a normal C nul-terminated string
1373 * Determines if a given string is a valid D-Bus object path. You
1374 * should ensure that a string is a valid D-Bus object path before
1375 * passing it to g_variant_new_object_path().
1377 * A valid object path starts with '/' followed by zero or more
1378 * sequences of characters separated by '/' characters. Each sequence
1379 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1380 * (including the one following the final '/' character) may be empty.
1382 * Returns: %TRUE if @string is a D-Bus object path
1387 g_variant_is_object_path (const gchar *string)
1389 g_return_val_if_fail (string != NULL, FALSE);
1391 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1395 * g_variant_new_signature:
1396 * @signature: a normal C nul-terminated string
1398 * Creates a D-Bus type signature #GVariant with the contents of
1399 * @string. @string must be a valid D-Bus type signature. Use
1400 * g_variant_is_signature() if you're not sure.
1402 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1407 g_variant_new_signature (const gchar *signature)
1409 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1411 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1412 signature, strlen (signature) + 1);
1416 * g_variant_is_signature:
1417 * @string: a normal C nul-terminated string
1419 * Determines if a given string is a valid D-Bus type signature. You
1420 * should ensure that a string is a valid D-Bus type signature before
1421 * passing it to g_variant_new_signature().
1423 * D-Bus type signatures consist of zero or more definite #GVariantType
1424 * strings in sequence.
1426 * Returns: %TRUE if @string is a D-Bus type signature
1431 g_variant_is_signature (const gchar *string)
1433 g_return_val_if_fail (string != NULL, FALSE);
1435 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1439 * g_variant_get_string:
1440 * @value: a string #GVariant instance
1441 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1442 * to store the length
1444 * Returns the string value of a #GVariant instance with a string
1445 * type. This includes the types %G_VARIANT_TYPE_STRING,
1446 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1448 * The string will always be utf8 encoded.
1450 * If @length is non-%NULL then the length of the string (in bytes) is
1451 * returned there. For trusted values, this information is already
1452 * known. For untrusted values, a strlen() will be performed.
1454 * It is an error to call this function with a @value of any type
1455 * other than those three.
1457 * The return value remains valid as long as @value exists.
1459 * Returns: (transfer none): the constant string, utf8 encoded
1464 g_variant_get_string (GVariant *value,
1470 g_return_val_if_fail (value != NULL, NULL);
1471 g_return_val_if_fail (
1472 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1473 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1474 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1476 data = g_variant_get_data (value);
1477 size = g_variant_get_size (value);
1479 if (!g_variant_is_trusted (value))
1481 switch (g_variant_classify (value))
1483 case G_VARIANT_CLASS_STRING:
1484 if (g_variant_serialiser_is_string (data, size))
1491 case G_VARIANT_CLASS_OBJECT_PATH:
1492 if (g_variant_serialiser_is_object_path (data, size))
1499 case G_VARIANT_CLASS_SIGNATURE:
1500 if (g_variant_serialiser_is_signature (data, size))
1508 g_assert_not_reached ();
1519 * g_variant_dup_string:
1520 * @value: a string #GVariant instance
1521 * @length: (out): a pointer to a #gsize, to store the length
1523 * Similar to g_variant_get_string() except that instead of returning
1524 * a constant string, the string is duplicated.
1526 * The string will always be utf8 encoded.
1528 * The return value must be freed using g_free().
1530 * Returns: (transfer full): a newly allocated string, utf8 encoded
1535 g_variant_dup_string (GVariant *value,
1538 return g_strdup (g_variant_get_string (value, length));
1542 * g_variant_new_strv:
1543 * @strv: (array length=length) (element-type utf8): an array of strings
1544 * @length: the length of @strv, or -1
1546 * Constructs an array of strings #GVariant from the given array of
1549 * If @length is -1 then @strv is %NULL-terminated.
1551 * Returns: (transfer none): a new floating #GVariant instance
1556 g_variant_new_strv (const gchar * const *strv,
1562 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1565 length = g_strv_length ((gchar **) strv);
1567 strings = g_new (GVariant *, length);
1568 for (i = 0; i < length; i++)
1569 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1571 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1572 strings, length, TRUE);
1576 * g_variant_get_strv:
1577 * @value: an array of strings #GVariant
1578 * @length: (out) (allow-none): the length of the result, or %NULL
1580 * Gets the contents of an array of strings #GVariant. This call
1581 * makes a shallow copy; the return result should be released with
1582 * g_free(), but the individual strings must not be modified.
1584 * If @length is non-%NULL then the number of elements in the result
1585 * is stored there. In any case, the resulting array will be
1588 * For an empty array, @length will be set to 0 and a pointer to a
1589 * %NULL pointer will be returned.
1591 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1596 g_variant_get_strv (GVariant *value,
1603 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1605 g_variant_get_data (value);
1606 n = g_variant_n_children (value);
1607 strv = g_new (const gchar *, n + 1);
1609 for (i = 0; i < n; i++)
1613 string = g_variant_get_child_value (value, i);
1614 strv[i] = g_variant_get_string (string, NULL);
1615 g_variant_unref (string);
1626 * g_variant_dup_strv:
1627 * @value: an array of strings #GVariant
1628 * @length: (out) (allow-none): the length of the result, or %NULL
1630 * Gets the contents of an array of strings #GVariant. This call
1631 * makes a deep copy; the return result should be released with
1634 * If @length is non-%NULL then the number of elements in the result
1635 * is stored there. In any case, the resulting array will be
1638 * For an empty array, @length will be set to 0 and a pointer to a
1639 * %NULL pointer will be returned.
1641 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1646 g_variant_dup_strv (GVariant *value,
1653 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1655 n = g_variant_n_children (value);
1656 strv = g_new (gchar *, n + 1);
1658 for (i = 0; i < n; i++)
1662 string = g_variant_get_child_value (value, i);
1663 strv[i] = g_variant_dup_string (string, NULL);
1664 g_variant_unref (string);
1675 * g_variant_new_objv:
1676 * @strv: (array length=length) (element-type utf8): an array of strings
1677 * @length: the length of @strv, or -1
1679 * Constructs an array of object paths #GVariant from the given array of
1682 * Each string must be a valid #GVariant object path; see
1683 * g_variant_is_object_path().
1685 * If @length is -1 then @strv is %NULL-terminated.
1687 * Returns: (transfer none): a new floating #GVariant instance
1692 g_variant_new_objv (const gchar * const *strv,
1698 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1701 length = g_strv_length ((gchar **) strv);
1703 strings = g_new (GVariant *, length);
1704 for (i = 0; i < length; i++)
1705 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1707 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1708 strings, length, TRUE);
1712 * g_variant_get_objv:
1713 * @value: an array of object paths #GVariant
1714 * @length: (out) (allow-none): the length of the result, or %NULL
1716 * Gets the contents of an array of object paths #GVariant. This call
1717 * makes a shallow copy; the return result should be released with
1718 * g_free(), but the individual strings must not be modified.
1720 * If @length is non-%NULL then the number of elements in the result
1721 * is stored there. In any case, the resulting array will be
1724 * For an empty array, @length will be set to 0 and a pointer to a
1725 * %NULL pointer will be returned.
1727 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1732 g_variant_get_objv (GVariant *value,
1739 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1741 g_variant_get_data (value);
1742 n = g_variant_n_children (value);
1743 strv = g_new (const gchar *, n + 1);
1745 for (i = 0; i < n; i++)
1749 string = g_variant_get_child_value (value, i);
1750 strv[i] = g_variant_get_string (string, NULL);
1751 g_variant_unref (string);
1762 * g_variant_dup_objv:
1763 * @value: an array of object paths #GVariant
1764 * @length: (out) (allow-none): the length of the result, or %NULL
1766 * Gets the contents of an array of object paths #GVariant. This call
1767 * makes a deep copy; the return result should be released with
1770 * If @length is non-%NULL then the number of elements in the result
1771 * is stored there. In any case, the resulting array will be
1774 * For an empty array, @length will be set to 0 and a pointer to a
1775 * %NULL pointer will be returned.
1777 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1782 g_variant_dup_objv (GVariant *value,
1789 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1791 n = g_variant_n_children (value);
1792 strv = g_new (gchar *, n + 1);
1794 for (i = 0; i < n; i++)
1798 string = g_variant_get_child_value (value, i);
1799 strv[i] = g_variant_dup_string (string, NULL);
1800 g_variant_unref (string);
1812 * g_variant_new_bytestring:
1813 * @string: (array zero-terminated=1) (element-type guint8): a normal
1814 * nul-terminated string in no particular encoding
1816 * Creates an array-of-bytes #GVariant with the contents of @string.
1817 * This function is just like g_variant_new_string() except that the
1818 * string need not be valid utf8.
1820 * The nul terminator character at the end of the string is stored in
1823 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1828 g_variant_new_bytestring (const gchar *string)
1830 g_return_val_if_fail (string != NULL, NULL);
1832 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1833 string, strlen (string) + 1);
1837 * g_variant_get_bytestring:
1838 * @value: an array-of-bytes #GVariant instance
1840 * Returns the string value of a #GVariant instance with an
1841 * array-of-bytes type. The string has no particular encoding.
1843 * If the array does not end with a nul terminator character, the empty
1844 * string is returned. For this reason, you can always trust that a
1845 * non-%NULL nul-terminated string will be returned by this function.
1847 * If the array contains a nul terminator character somewhere other than
1848 * the last byte then the returned string is the string, up to the first
1849 * such nul character.
1851 * It is an error to call this function with a @value that is not an
1854 * The return value remains valid as long as @value exists.
1856 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1857 * the constant string
1862 g_variant_get_bytestring (GVariant *value)
1864 const gchar *string;
1867 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1869 /* Won't be NULL since this is an array type */
1870 string = g_variant_get_data (value);
1871 size = g_variant_get_size (value);
1873 if (size && string[size - 1] == '\0')
1880 * g_variant_dup_bytestring:
1881 * @value: an array-of-bytes #GVariant instance
1882 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1883 * the length (not including the nul terminator)
1885 * Similar to g_variant_get_bytestring() except that instead of
1886 * returning a constant string, the string is duplicated.
1888 * The return value must be freed using g_free().
1890 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1891 * a newly allocated string
1896 g_variant_dup_bytestring (GVariant *value,
1899 const gchar *original = g_variant_get_bytestring (value);
1902 /* don't crash in case get_bytestring() had an assert failure */
1903 if (original == NULL)
1906 size = strlen (original);
1911 return g_memdup (original, size + 1);
1915 * g_variant_new_bytestring_array:
1916 * @strv: (array length=length): an array of strings
1917 * @length: the length of @strv, or -1
1919 * Constructs an array of bytestring #GVariant from the given array of
1922 * If @length is -1 then @strv is %NULL-terminated.
1924 * Returns: (transfer none): a new floating #GVariant instance
1929 g_variant_new_bytestring_array (const gchar * const *strv,
1935 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1938 length = g_strv_length ((gchar **) strv);
1940 strings = g_new (GVariant *, length);
1941 for (i = 0; i < length; i++)
1942 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1944 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1945 strings, length, TRUE);
1949 * g_variant_get_bytestring_array:
1950 * @value: an array of array of bytes #GVariant ('aay')
1951 * @length: (out) (allow-none): the length of the result, or %NULL
1953 * Gets the contents of an array of array of bytes #GVariant. This call
1954 * makes a shallow copy; the return result should be released with
1955 * g_free(), but the individual strings must not be modified.
1957 * If @length is non-%NULL then the number of elements in the result is
1958 * stored there. In any case, the resulting array will be
1961 * For an empty array, @length will be set to 0 and a pointer to a
1962 * %NULL pointer will be returned.
1964 * Returns: (array length=length) (transfer container): an array of constant strings
1969 g_variant_get_bytestring_array (GVariant *value,
1976 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1978 g_variant_get_data (value);
1979 n = g_variant_n_children (value);
1980 strv = g_new (const gchar *, n + 1);
1982 for (i = 0; i < n; i++)
1986 string = g_variant_get_child_value (value, i);
1987 strv[i] = g_variant_get_bytestring (string);
1988 g_variant_unref (string);
1999 * g_variant_dup_bytestring_array:
2000 * @value: an array of array of bytes #GVariant ('aay')
2001 * @length: (out) (allow-none): the length of the result, or %NULL
2003 * Gets the contents of an array of array of bytes #GVariant. This call
2004 * makes a deep copy; the return result should be released with
2007 * If @length is non-%NULL then the number of elements in the result is
2008 * stored there. In any case, the resulting array will be
2011 * For an empty array, @length will be set to 0 and a pointer to a
2012 * %NULL pointer will be returned.
2014 * Returns: (array length=length) (transfer full): an array of strings
2019 g_variant_dup_bytestring_array (GVariant *value,
2026 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2028 g_variant_get_data (value);
2029 n = g_variant_n_children (value);
2030 strv = g_new (gchar *, n + 1);
2032 for (i = 0; i < n; i++)
2036 string = g_variant_get_child_value (value, i);
2037 strv[i] = g_variant_dup_bytestring (string, NULL);
2038 g_variant_unref (string);
2048 /* Type checking and querying {{{1 */
2050 * g_variant_get_type:
2051 * @value: a #GVariant
2053 * Determines the type of @value.
2055 * The return value is valid for the lifetime of @value and must not
2058 * Returns: a #GVariantType
2062 const GVariantType *
2063 g_variant_get_type (GVariant *value)
2065 GVariantTypeInfo *type_info;
2067 g_return_val_if_fail (value != NULL, NULL);
2069 type_info = g_variant_get_type_info (value);
2071 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2075 * g_variant_get_type_string:
2076 * @value: a #GVariant
2078 * Returns the type string of @value. Unlike the result of calling
2079 * g_variant_type_peek_string(), this string is nul-terminated. This
2080 * string belongs to #GVariant and must not be freed.
2082 * Returns: the type string for the type of @value
2087 g_variant_get_type_string (GVariant *value)
2089 GVariantTypeInfo *type_info;
2091 g_return_val_if_fail (value != NULL, NULL);
2093 type_info = g_variant_get_type_info (value);
2095 return g_variant_type_info_get_type_string (type_info);
2099 * g_variant_is_of_type:
2100 * @value: a #GVariant instance
2101 * @type: a #GVariantType
2103 * Checks if a value has a type matching the provided type.
2105 * Returns: %TRUE if the type of @value matches @type
2110 g_variant_is_of_type (GVariant *value,
2111 const GVariantType *type)
2113 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2117 * g_variant_is_container:
2118 * @value: a #GVariant instance
2120 * Checks if @value is a container.
2122 * Returns: %TRUE if @value is a container
2127 g_variant_is_container (GVariant *value)
2129 return g_variant_type_is_container (g_variant_get_type (value));
2134 * g_variant_classify:
2135 * @value: a #GVariant
2137 * Classifies @value according to its top-level type.
2139 * Returns: the #GVariantClass of @value
2145 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2146 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2147 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2148 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2149 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2150 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2151 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2152 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2153 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2154 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2156 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2157 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2159 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2160 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2161 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2162 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2163 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2164 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2166 * The range of possible top-level types of #GVariant instances.
2171 g_variant_classify (GVariant *value)
2173 g_return_val_if_fail (value != NULL, 0);
2175 return *g_variant_get_type_string (value);
2178 /* Pretty printer {{{1 */
2179 /* This function is not introspectable because if @string is NULL,
2180 @returns is (transfer full), otherwise it is (transfer none), which
2181 is not supported by GObjectIntrospection */
2183 * g_variant_print_string: (skip)
2184 * @value: a #GVariant
2185 * @string: (allow-none) (default NULL): a #GString, or %NULL
2186 * @type_annotate: %TRUE if type information should be included in
2189 * Behaves as g_variant_print(), but operates on a #GString.
2191 * If @string is non-%NULL then it is appended to and returned. Else,
2192 * a new empty #GString is allocated and it is returned.
2194 * Returns: a #GString containing the string
2199 g_variant_print_string (GVariant *value,
2201 gboolean type_annotate)
2203 if G_UNLIKELY (string == NULL)
2204 string = g_string_new (NULL);
2206 switch (g_variant_classify (value))
2208 case G_VARIANT_CLASS_MAYBE:
2210 g_string_append_printf (string, "@%s ",
2211 g_variant_get_type_string (value));
2213 if (g_variant_n_children (value))
2215 gchar *printed_child;
2220 * Consider the case of the type "mmi". In this case we could
2221 * write "just just 4", but "4" alone is totally unambiguous,
2222 * so we try to drop "just" where possible.
2224 * We have to be careful not to always drop "just", though,
2225 * since "nothing" needs to be distinguishable from "just
2226 * nothing". The case where we need to ensure we keep the
2227 * "just" is actually exactly the case where we have a nested
2230 * Instead of searching for that nested Nothing, we just print
2231 * the contained value into a separate string and see if we
2232 * end up with "nothing" at the end of it. If so, we need to
2233 * add "just" at our level.
2235 element = g_variant_get_child_value (value, 0);
2236 printed_child = g_variant_print (element, FALSE);
2237 g_variant_unref (element);
2239 if (g_str_has_suffix (printed_child, "nothing"))
2240 g_string_append (string, "just ");
2241 g_string_append (string, printed_child);
2242 g_free (printed_child);
2245 g_string_append (string, "nothing");
2249 case G_VARIANT_CLASS_ARRAY:
2250 /* it's an array so the first character of the type string is 'a'
2252 * if the first two characters are 'ay' then it's a bytestring.
2253 * under certain conditions we print those as strings.
2255 if (g_variant_get_type_string (value)[1] == 'y')
2261 /* first determine if it is a byte string.
2262 * that's when there's a single nul character: at the end.
2264 str = g_variant_get_data (value);
2265 size = g_variant_get_size (value);
2267 for (i = 0; i < size; i++)
2271 /* first nul byte is the last byte -> it's a byte string. */
2274 gchar *escaped = g_strescape (str, NULL);
2276 /* use double quotes only if a ' is in the string */
2277 if (strchr (str, '\''))
2278 g_string_append_printf (string, "b\"%s\"", escaped);
2280 g_string_append_printf (string, "b'%s'", escaped);
2287 /* fall through and handle normally... */;
2291 * if the first two characters are 'a{' then it's an array of
2292 * dictionary entries (ie: a dictionary) so we print that
2295 if (g_variant_get_type_string (value)[1] == '{')
2298 const gchar *comma = "";
2301 if ((n = g_variant_n_children (value)) == 0)
2304 g_string_append_printf (string, "@%s ",
2305 g_variant_get_type_string (value));
2306 g_string_append (string, "{}");
2310 g_string_append_c (string, '{');
2311 for (i = 0; i < n; i++)
2313 GVariant *entry, *key, *val;
2315 g_string_append (string, comma);
2318 entry = g_variant_get_child_value (value, i);
2319 key = g_variant_get_child_value (entry, 0);
2320 val = g_variant_get_child_value (entry, 1);
2321 g_variant_unref (entry);
2323 g_variant_print_string (key, string, type_annotate);
2324 g_variant_unref (key);
2325 g_string_append (string, ": ");
2326 g_variant_print_string (val, string, type_annotate);
2327 g_variant_unref (val);
2328 type_annotate = FALSE;
2330 g_string_append_c (string, '}');
2333 /* normal (non-dictionary) array */
2335 const gchar *comma = "";
2338 if ((n = g_variant_n_children (value)) == 0)
2341 g_string_append_printf (string, "@%s ",
2342 g_variant_get_type_string (value));
2343 g_string_append (string, "[]");
2347 g_string_append_c (string, '[');
2348 for (i = 0; i < n; i++)
2352 g_string_append (string, comma);
2355 element = g_variant_get_child_value (value, i);
2357 g_variant_print_string (element, string, type_annotate);
2358 g_variant_unref (element);
2359 type_annotate = FALSE;
2361 g_string_append_c (string, ']');
2366 case G_VARIANT_CLASS_TUPLE:
2370 n = g_variant_n_children (value);
2372 g_string_append_c (string, '(');
2373 for (i = 0; i < n; i++)
2377 element = g_variant_get_child_value (value, i);
2378 g_variant_print_string (element, string, type_annotate);
2379 g_string_append (string, ", ");
2380 g_variant_unref (element);
2383 /* for >1 item: remove final ", "
2384 * for 1 item: remove final " ", but leave the ","
2385 * for 0 items: there is only "(", so remove nothing
2387 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2388 g_string_append_c (string, ')');
2392 case G_VARIANT_CLASS_DICT_ENTRY:
2396 g_string_append_c (string, '{');
2398 element = g_variant_get_child_value (value, 0);
2399 g_variant_print_string (element, string, type_annotate);
2400 g_variant_unref (element);
2402 g_string_append (string, ", ");
2404 element = g_variant_get_child_value (value, 1);
2405 g_variant_print_string (element, string, type_annotate);
2406 g_variant_unref (element);
2408 g_string_append_c (string, '}');
2412 case G_VARIANT_CLASS_VARIANT:
2414 GVariant *child = g_variant_get_variant (value);
2416 /* Always annotate types in nested variants, because they are
2417 * (by nature) of variable type.
2419 g_string_append_c (string, '<');
2420 g_variant_print_string (child, string, TRUE);
2421 g_string_append_c (string, '>');
2423 g_variant_unref (child);
2427 case G_VARIANT_CLASS_BOOLEAN:
2428 if (g_variant_get_boolean (value))
2429 g_string_append (string, "true");
2431 g_string_append (string, "false");
2434 case G_VARIANT_CLASS_STRING:
2436 const gchar *str = g_variant_get_string (value, NULL);
2437 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2439 g_string_append_c (string, quote);
2443 gunichar c = g_utf8_get_char (str);
2445 if (c == quote || c == '\\')
2446 g_string_append_c (string, '\\');
2448 if (g_unichar_isprint (c))
2449 g_string_append_unichar (string, c);
2453 g_string_append_c (string, '\\');
2458 g_string_append_c (string, 'a');
2462 g_string_append_c (string, 'b');
2466 g_string_append_c (string, 'f');
2470 g_string_append_c (string, 'n');
2474 g_string_append_c (string, 'r');
2478 g_string_append_c (string, 't');
2482 g_string_append_c (string, 'v');
2486 g_string_append_printf (string, "u%04x", c);
2490 g_string_append_printf (string, "U%08x", c);
2493 str = g_utf8_next_char (str);
2496 g_string_append_c (string, quote);
2500 case G_VARIANT_CLASS_BYTE:
2502 g_string_append (string, "byte ");
2503 g_string_append_printf (string, "0x%02x",
2504 g_variant_get_byte (value));
2507 case G_VARIANT_CLASS_INT16:
2509 g_string_append (string, "int16 ");
2510 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2511 g_variant_get_int16 (value));
2514 case G_VARIANT_CLASS_UINT16:
2516 g_string_append (string, "uint16 ");
2517 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2518 g_variant_get_uint16 (value));
2521 case G_VARIANT_CLASS_INT32:
2522 /* Never annotate this type because it is the default for numbers
2523 * (and this is a *pretty* printer)
2525 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2526 g_variant_get_int32 (value));
2529 case G_VARIANT_CLASS_HANDLE:
2531 g_string_append (string, "handle ");
2532 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2533 g_variant_get_handle (value));
2536 case G_VARIANT_CLASS_UINT32:
2538 g_string_append (string, "uint32 ");
2539 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2540 g_variant_get_uint32 (value));
2543 case G_VARIANT_CLASS_INT64:
2545 g_string_append (string, "int64 ");
2546 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2547 g_variant_get_int64 (value));
2550 case G_VARIANT_CLASS_UINT64:
2552 g_string_append (string, "uint64 ");
2553 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2554 g_variant_get_uint64 (value));
2557 case G_VARIANT_CLASS_DOUBLE:
2562 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2564 for (i = 0; buffer[i]; i++)
2565 if (buffer[i] == '.' || buffer[i] == 'e' ||
2566 buffer[i] == 'n' || buffer[i] == 'N')
2569 /* if there is no '.' or 'e' in the float then add one */
2570 if (buffer[i] == '\0')
2577 g_string_append (string, buffer);
2581 case G_VARIANT_CLASS_OBJECT_PATH:
2583 g_string_append (string, "objectpath ");
2584 g_string_append_printf (string, "\'%s\'",
2585 g_variant_get_string (value, NULL));
2588 case G_VARIANT_CLASS_SIGNATURE:
2590 g_string_append (string, "signature ");
2591 g_string_append_printf (string, "\'%s\'",
2592 g_variant_get_string (value, NULL));
2596 g_assert_not_reached ();
2604 * @value: a #GVariant
2605 * @type_annotate: %TRUE if type information should be included in
2608 * Pretty-prints @value in the format understood by g_variant_parse().
2610 * The format is described <link linkend='gvariant-text'>here</link>.
2612 * If @type_annotate is %TRUE, then type information is included in
2615 * Returns: (transfer full): a newly-allocated string holding the result.
2620 g_variant_print (GVariant *value,
2621 gboolean type_annotate)
2623 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2627 /* Hash, Equal, Compare {{{1 */
2630 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2632 * Generates a hash value for a #GVariant instance.
2634 * The output of this function is guaranteed to be the same for a given
2635 * value only per-process. It may change between different processor
2636 * architectures or even different versions of GLib. Do not use this
2637 * function as a basis for building protocols or file formats.
2639 * The type of @value is #gconstpointer only to allow use of this
2640 * function with #GHashTable. @value must be a #GVariant.
2642 * Returns: a hash value corresponding to @value
2647 g_variant_hash (gconstpointer value_)
2649 GVariant *value = (GVariant *) value_;
2651 switch (g_variant_classify (value))
2653 case G_VARIANT_CLASS_STRING:
2654 case G_VARIANT_CLASS_OBJECT_PATH:
2655 case G_VARIANT_CLASS_SIGNATURE:
2656 return g_str_hash (g_variant_get_string (value, NULL));
2658 case G_VARIANT_CLASS_BOOLEAN:
2659 /* this is a very odd thing to hash... */
2660 return g_variant_get_boolean (value);
2662 case G_VARIANT_CLASS_BYTE:
2663 return g_variant_get_byte (value);
2665 case G_VARIANT_CLASS_INT16:
2666 case G_VARIANT_CLASS_UINT16:
2670 ptr = g_variant_get_data (value);
2678 case G_VARIANT_CLASS_INT32:
2679 case G_VARIANT_CLASS_UINT32:
2680 case G_VARIANT_CLASS_HANDLE:
2684 ptr = g_variant_get_data (value);
2692 case G_VARIANT_CLASS_INT64:
2693 case G_VARIANT_CLASS_UINT64:
2694 case G_VARIANT_CLASS_DOUBLE:
2695 /* need a separate case for these guys because otherwise
2696 * performance could be quite bad on big endian systems
2701 ptr = g_variant_get_data (value);
2704 return ptr[0] + ptr[1];
2710 g_return_val_if_fail (!g_variant_is_container (value), 0);
2711 g_assert_not_reached ();
2717 * @one: (type GVariant): a #GVariant instance
2718 * @two: (type GVariant): a #GVariant instance
2720 * Checks if @one and @two have the same type and value.
2722 * The types of @one and @two are #gconstpointer only to allow use of
2723 * this function with #GHashTable. They must each be a #GVariant.
2725 * Returns: %TRUE if @one and @two are equal
2730 g_variant_equal (gconstpointer one,
2735 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2737 if (g_variant_get_type_info ((GVariant *) one) !=
2738 g_variant_get_type_info ((GVariant *) two))
2741 /* if both values are trusted to be in their canonical serialised form
2742 * then a simple memcmp() of their serialised data will answer the
2745 * if not, then this might generate a false negative (since it is
2746 * possible for two different byte sequences to represent the same
2747 * value). for now we solve this by pretty-printing both values and
2748 * comparing the result.
2750 if (g_variant_is_trusted ((GVariant *) one) &&
2751 g_variant_is_trusted ((GVariant *) two))
2753 gconstpointer data_one, data_two;
2754 gsize size_one, size_two;
2756 size_one = g_variant_get_size ((GVariant *) one);
2757 size_two = g_variant_get_size ((GVariant *) two);
2759 if (size_one != size_two)
2762 data_one = g_variant_get_data ((GVariant *) one);
2763 data_two = g_variant_get_data ((GVariant *) two);
2765 equal = memcmp (data_one, data_two, size_one) == 0;
2769 gchar *strone, *strtwo;
2771 strone = g_variant_print ((GVariant *) one, FALSE);
2772 strtwo = g_variant_print ((GVariant *) two, FALSE);
2773 equal = strcmp (strone, strtwo) == 0;
2782 * g_variant_compare:
2783 * @one: (type GVariant): a basic-typed #GVariant instance
2784 * @two: (type GVariant): a #GVariant instance of the same type
2786 * Compares @one and @two.
2788 * The types of @one and @two are #gconstpointer only to allow use of
2789 * this function with #GTree, #GPtrArray, etc. They must each be a
2792 * Comparison is only defined for basic types (ie: booleans, numbers,
2793 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2794 * ordered in the usual way. Strings are in ASCII lexographical order.
2796 * It is a programmer error to attempt to compare container values or
2797 * two values that have types that are not exactly equal. For example,
2798 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2799 * integer. Also note that this function is not particularly
2800 * well-behaved when it comes to comparison of doubles; in particular,
2801 * the handling of incomparable values (ie: NaN) is undefined.
2803 * If you only require an equality comparison, g_variant_equal() is more
2806 * Returns: negative value if a < b;
2808 * positive value if a > b.
2813 g_variant_compare (gconstpointer one,
2816 GVariant *a = (GVariant *) one;
2817 GVariant *b = (GVariant *) two;
2819 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2821 switch (g_variant_classify (a))
2823 case G_VARIANT_CLASS_BOOLEAN:
2824 return g_variant_get_boolean (a) -
2825 g_variant_get_boolean (b);
2827 case G_VARIANT_CLASS_BYTE:
2828 return ((gint) g_variant_get_byte (a)) -
2829 ((gint) g_variant_get_byte (b));
2831 case G_VARIANT_CLASS_INT16:
2832 return ((gint) g_variant_get_int16 (a)) -
2833 ((gint) g_variant_get_int16 (b));
2835 case G_VARIANT_CLASS_UINT16:
2836 return ((gint) g_variant_get_uint16 (a)) -
2837 ((gint) g_variant_get_uint16 (b));
2839 case G_VARIANT_CLASS_INT32:
2841 gint32 a_val = g_variant_get_int32 (a);
2842 gint32 b_val = g_variant_get_int32 (b);
2844 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2847 case G_VARIANT_CLASS_UINT32:
2849 guint32 a_val = g_variant_get_uint32 (a);
2850 guint32 b_val = g_variant_get_uint32 (b);
2852 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2855 case G_VARIANT_CLASS_INT64:
2857 gint64 a_val = g_variant_get_int64 (a);
2858 gint64 b_val = g_variant_get_int64 (b);
2860 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2863 case G_VARIANT_CLASS_UINT64:
2865 guint64 a_val = g_variant_get_uint64 (a);
2866 guint64 b_val = g_variant_get_uint64 (b);
2868 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2871 case G_VARIANT_CLASS_DOUBLE:
2873 gdouble a_val = g_variant_get_double (a);
2874 gdouble b_val = g_variant_get_double (b);
2876 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2879 case G_VARIANT_CLASS_STRING:
2880 case G_VARIANT_CLASS_OBJECT_PATH:
2881 case G_VARIANT_CLASS_SIGNATURE:
2882 return strcmp (g_variant_get_string (a, NULL),
2883 g_variant_get_string (b, NULL));
2886 g_return_val_if_fail (!g_variant_is_container (a), 0);
2887 g_assert_not_reached ();
2891 /* GVariantIter {{{1 */
2893 * GVariantIter: (skip)
2895 * #GVariantIter is an opaque data structure and can only be accessed
2896 * using the following functions.
2903 const gchar *loop_format;
2909 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2913 struct stack_iter iter;
2915 GVariant *value_ref;
2919 #define GVSI(i) ((struct stack_iter *) (i))
2920 #define GVHI(i) ((struct heap_iter *) (i))
2921 #define GVSI_MAGIC ((gsize) 3579507750u)
2922 #define GVHI_MAGIC ((gsize) 1450270775u)
2923 #define is_valid_iter(i) (i != NULL && \
2924 GVSI(i)->magic == GVSI_MAGIC)
2925 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2929 * g_variant_iter_new:
2930 * @value: a container #GVariant
2932 * Creates a heap-allocated #GVariantIter for iterating over the items
2935 * Use g_variant_iter_free() to free the return value when you no longer
2938 * A reference is taken to @value and will be released only when
2939 * g_variant_iter_free() is called.
2941 * Returns: (transfer full): a new heap-allocated #GVariantIter
2946 g_variant_iter_new (GVariant *value)
2950 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2951 GVHI(iter)->value_ref = g_variant_ref (value);
2952 GVHI(iter)->magic = GVHI_MAGIC;
2954 g_variant_iter_init (iter, value);
2960 * g_variant_iter_init: (skip)
2961 * @iter: a pointer to a #GVariantIter
2962 * @value: a container #GVariant
2964 * Initialises (without allocating) a #GVariantIter. @iter may be
2965 * completely uninitialised prior to this call; its old value is
2968 * The iterator remains valid for as long as @value exists, and need not
2969 * be freed in any way.
2971 * Returns: the number of items in @value
2976 g_variant_iter_init (GVariantIter *iter,
2979 GVSI(iter)->magic = GVSI_MAGIC;
2980 GVSI(iter)->value = value;
2981 GVSI(iter)->n = g_variant_n_children (value);
2983 GVSI(iter)->loop_format = NULL;
2985 return GVSI(iter)->n;
2989 * g_variant_iter_copy:
2990 * @iter: a #GVariantIter
2992 * Creates a new heap-allocated #GVariantIter to iterate over the
2993 * container that was being iterated over by @iter. Iteration begins on
2994 * the new iterator from the current position of the old iterator but
2995 * the two copies are independent past that point.
2997 * Use g_variant_iter_free() to free the return value when you no longer
3000 * A reference is taken to the container that @iter is iterating over
3001 * and will be releated only when g_variant_iter_free() is called.
3003 * Returns: (transfer full): a new heap-allocated #GVariantIter
3008 g_variant_iter_copy (GVariantIter *iter)
3012 g_return_val_if_fail (is_valid_iter (iter), 0);
3014 copy = g_variant_iter_new (GVSI(iter)->value);
3015 GVSI(copy)->i = GVSI(iter)->i;
3021 * g_variant_iter_n_children:
3022 * @iter: a #GVariantIter
3024 * Queries the number of child items in the container that we are
3025 * iterating over. This is the total number of items -- not the number
3026 * of items remaining.
3028 * This function might be useful for preallocation of arrays.
3030 * Returns: the number of children in the container
3035 g_variant_iter_n_children (GVariantIter *iter)
3037 g_return_val_if_fail (is_valid_iter (iter), 0);
3039 return GVSI(iter)->n;
3043 * g_variant_iter_free:
3044 * @iter: (transfer full): a heap-allocated #GVariantIter
3046 * Frees a heap-allocated #GVariantIter. Only call this function on
3047 * iterators that were returned by g_variant_iter_new() or
3048 * g_variant_iter_copy().
3053 g_variant_iter_free (GVariantIter *iter)
3055 g_return_if_fail (is_valid_heap_iter (iter));
3057 g_variant_unref (GVHI(iter)->value_ref);
3058 GVHI(iter)->magic = 0;
3060 g_slice_free (struct heap_iter, GVHI(iter));
3064 * g_variant_iter_next_value:
3065 * @iter: a #GVariantIter
3067 * Gets the next item in the container. If no more items remain then
3068 * %NULL is returned.
3070 * Use g_variant_unref() to drop your reference on the return value when
3071 * you no longer need it.
3074 * <title>Iterating with g_variant_iter_next_value()</title>
3076 * /<!-- -->* recursively iterate a container *<!-- -->/
3078 * iterate_container_recursive (GVariant *container)
3080 * GVariantIter iter;
3083 * g_variant_iter_init (&iter, container);
3084 * while ((child = g_variant_iter_next_value (&iter)))
3086 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3088 * if (g_variant_is_container (child))
3089 * iterate_container_recursive (child);
3091 * g_variant_unref (child);
3097 * Returns: (allow-none) (transfer full): a #GVariant, or %NULL
3102 g_variant_iter_next_value (GVariantIter *iter)
3104 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3106 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3108 g_critical ("g_variant_iter_next_value: must not be called again "
3109 "after NULL has already been returned.");
3115 if (GVSI(iter)->i < GVSI(iter)->n)
3116 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3121 /* GVariantBuilder {{{1 */
3125 * A utility type for constructing container-type #GVariant instances.
3127 * This is an opaque structure and may only be accessed using the
3128 * following functions.
3130 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3131 * access it from more than one thread.
3134 struct stack_builder
3136 GVariantBuilder *parent;
3139 /* type constraint explicitly specified by 'type'.
3140 * for tuple types, this moves along as we add more items.
3142 const GVariantType *expected_type;
3144 /* type constraint implied by previous array item.
3146 const GVariantType *prev_item_type;
3148 /* constraints on the number of children. max = -1 for unlimited. */
3152 /* dynamically-growing pointer array */
3153 GVariant **children;
3154 gsize allocated_children;
3157 /* set to '1' if all items in the container will have the same type
3158 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3160 guint uniform_item_types : 1;
3162 /* set to '1' initially and changed to '0' if an untrusted value is
3170 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3174 GVariantBuilder builder;
3180 #define GVSB(b) ((struct stack_builder *) (b))
3181 #define GVHB(b) ((struct heap_builder *) (b))
3182 #define GVSB_MAGIC ((gsize) 1033660112u)
3183 #define GVHB_MAGIC ((gsize) 3087242682u)
3184 #define is_valid_builder(b) (b != NULL && \
3185 GVSB(b)->magic == GVSB_MAGIC)
3186 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3189 * g_variant_builder_new:
3190 * @type: a container type
3192 * Allocates and initialises a new #GVariantBuilder.
3194 * You should call g_variant_builder_unref() on the return value when it
3195 * is no longer needed. The memory will not be automatically freed by
3198 * In most cases it is easier to place a #GVariantBuilder directly on
3199 * the stack of the calling function and initialise it with
3200 * g_variant_builder_init().
3202 * Returns: (transfer full): a #GVariantBuilder
3207 g_variant_builder_new (const GVariantType *type)
3209 GVariantBuilder *builder;
3211 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3212 g_variant_builder_init (builder, type);
3213 GVHB(builder)->magic = GVHB_MAGIC;
3214 GVHB(builder)->ref_count = 1;
3220 * g_variant_builder_unref:
3221 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3223 * Decreases the reference count on @builder.
3225 * In the event that there are no more references, releases all memory
3226 * associated with the #GVariantBuilder.
3228 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3229 * things will happen.
3234 g_variant_builder_unref (GVariantBuilder *builder)
3236 g_return_if_fail (is_valid_heap_builder (builder));
3238 if (--GVHB(builder)->ref_count)
3241 g_variant_builder_clear (builder);
3242 GVHB(builder)->magic = 0;
3244 g_slice_free (struct heap_builder, GVHB(builder));
3248 * g_variant_builder_ref:
3249 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3251 * Increases the reference count on @builder.
3253 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3254 * things will happen.
3256 * Returns: (transfer full): a new reference to @builder
3261 g_variant_builder_ref (GVariantBuilder *builder)
3263 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3265 GVHB(builder)->ref_count++;
3271 * g_variant_builder_clear: (skip)
3272 * @builder: a #GVariantBuilder
3274 * Releases all memory associated with a #GVariantBuilder without
3275 * freeing the #GVariantBuilder structure itself.
3277 * It typically only makes sense to do this on a stack-allocated
3278 * #GVariantBuilder if you want to abort building the value part-way
3279 * through. This function need not be called if you call
3280 * g_variant_builder_end() and it also doesn't need to be called on
3281 * builders allocated with g_variant_builder_new (see
3282 * g_variant_builder_unref() for that).
3284 * This function leaves the #GVariantBuilder structure set to all-zeros.
3285 * It is valid to call this function on either an initialised
3286 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3287 * to call this function on uninitialised memory.
3292 g_variant_builder_clear (GVariantBuilder *builder)
3296 if (GVSB(builder)->magic == 0)
3297 /* all-zeros case */
3300 g_return_if_fail (is_valid_builder (builder));
3302 g_variant_type_free (GVSB(builder)->type);
3304 for (i = 0; i < GVSB(builder)->offset; i++)
3305 g_variant_unref (GVSB(builder)->children[i]);
3307 g_free (GVSB(builder)->children);
3309 if (GVSB(builder)->parent)
3311 g_variant_builder_clear (GVSB(builder)->parent);
3312 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3315 memset (builder, 0, sizeof (GVariantBuilder));
3319 * g_variant_builder_init: (skip)
3320 * @builder: a #GVariantBuilder
3321 * @type: a container type
3323 * Initialises a #GVariantBuilder structure.
3325 * @type must be non-%NULL. It specifies the type of container to
3326 * construct. It can be an indefinite type such as
3327 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3328 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3331 * After the builder is initialised, values are added using
3332 * g_variant_builder_add_value() or g_variant_builder_add().
3334 * After all the child values are added, g_variant_builder_end() frees
3335 * the memory associated with the builder and returns the #GVariant that
3338 * This function completely ignores the previous contents of @builder.
3339 * On one hand this means that it is valid to pass in completely
3340 * uninitialised memory. On the other hand, this means that if you are
3341 * initialising over top of an existing #GVariantBuilder you need to
3342 * first call g_variant_builder_clear() in order to avoid leaking
3345 * You must not call g_variant_builder_ref() or
3346 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3347 * with this function. If you ever pass a reference to a
3348 * #GVariantBuilder outside of the control of your own code then you
3349 * should assume that the person receiving that reference may try to use
3350 * reference counting; you should use g_variant_builder_new() instead of
3356 g_variant_builder_init (GVariantBuilder *builder,
3357 const GVariantType *type)
3359 g_return_if_fail (type != NULL);
3360 g_return_if_fail (g_variant_type_is_container (type));
3362 memset (builder, 0, sizeof (GVariantBuilder));
3364 GVSB(builder)->type = g_variant_type_copy (type);
3365 GVSB(builder)->magic = GVSB_MAGIC;
3366 GVSB(builder)->trusted = TRUE;
3368 switch (*(const gchar *) type)
3370 case G_VARIANT_CLASS_VARIANT:
3371 GVSB(builder)->uniform_item_types = TRUE;
3372 GVSB(builder)->allocated_children = 1;
3373 GVSB(builder)->expected_type = NULL;
3374 GVSB(builder)->min_items = 1;
3375 GVSB(builder)->max_items = 1;
3378 case G_VARIANT_CLASS_ARRAY:
3379 GVSB(builder)->uniform_item_types = TRUE;
3380 GVSB(builder)->allocated_children = 8;
3381 GVSB(builder)->expected_type =
3382 g_variant_type_element (GVSB(builder)->type);
3383 GVSB(builder)->min_items = 0;
3384 GVSB(builder)->max_items = -1;
3387 case G_VARIANT_CLASS_MAYBE:
3388 GVSB(builder)->uniform_item_types = TRUE;
3389 GVSB(builder)->allocated_children = 1;
3390 GVSB(builder)->expected_type =
3391 g_variant_type_element (GVSB(builder)->type);
3392 GVSB(builder)->min_items = 0;
3393 GVSB(builder)->max_items = 1;
3396 case G_VARIANT_CLASS_DICT_ENTRY:
3397 GVSB(builder)->uniform_item_types = FALSE;
3398 GVSB(builder)->allocated_children = 2;
3399 GVSB(builder)->expected_type =
3400 g_variant_type_key (GVSB(builder)->type);
3401 GVSB(builder)->min_items = 2;
3402 GVSB(builder)->max_items = 2;
3405 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3406 GVSB(builder)->uniform_item_types = FALSE;
3407 GVSB(builder)->allocated_children = 8;
3408 GVSB(builder)->expected_type = NULL;
3409 GVSB(builder)->min_items = 0;
3410 GVSB(builder)->max_items = -1;
3413 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3414 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3415 GVSB(builder)->expected_type =
3416 g_variant_type_first (GVSB(builder)->type);
3417 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3418 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3419 GVSB(builder)->uniform_item_types = FALSE;
3423 g_assert_not_reached ();
3426 GVSB(builder)->children = g_new (GVariant *,
3427 GVSB(builder)->allocated_children);
3431 g_variant_builder_make_room (struct stack_builder *builder)
3433 if (builder->offset == builder->allocated_children)
3435 builder->allocated_children *= 2;
3436 builder->children = g_renew (GVariant *, builder->children,
3437 builder->allocated_children);
3442 * g_variant_builder_add_value:
3443 * @builder: a #GVariantBuilder
3444 * @value: a #GVariant
3446 * Adds @value to @builder.
3448 * It is an error to call this function in any way that would create an
3449 * inconsistent value to be constructed. Some examples of this are
3450 * putting different types of items into an array, putting the wrong
3451 * types or number of items in a tuple, putting more than one value into
3454 * If @value is a floating reference (see g_variant_ref_sink()),
3455 * the @builder instance takes ownership of @value.
3460 g_variant_builder_add_value (GVariantBuilder *builder,
3463 g_return_if_fail (is_valid_builder (builder));
3464 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3465 g_return_if_fail (!GVSB(builder)->expected_type ||
3466 g_variant_is_of_type (value,
3467 GVSB(builder)->expected_type));
3468 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3469 g_variant_is_of_type (value,
3470 GVSB(builder)->prev_item_type));
3472 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3474 if (!GVSB(builder)->uniform_item_types)
3476 /* advance our expected type pointers */
3477 if (GVSB(builder)->expected_type)
3478 GVSB(builder)->expected_type =
3479 g_variant_type_next (GVSB(builder)->expected_type);
3481 if (GVSB(builder)->prev_item_type)
3482 GVSB(builder)->prev_item_type =
3483 g_variant_type_next (GVSB(builder)->prev_item_type);
3486 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3488 g_variant_builder_make_room (GVSB(builder));
3490 GVSB(builder)->children[GVSB(builder)->offset++] =
3491 g_variant_ref_sink (value);
3495 * g_variant_builder_open:
3496 * @builder: a #GVariantBuilder
3497 * @type: a #GVariantType
3499 * Opens a subcontainer inside the given @builder. When done adding
3500 * items to the subcontainer, g_variant_builder_close() must be called.
3502 * It is an error to call this function in any way that would cause an
3503 * inconsistent value to be constructed (ie: adding too many values or
3504 * a value of an incorrect type).
3509 g_variant_builder_open (GVariantBuilder *builder,
3510 const GVariantType *type)
3512 GVariantBuilder *parent;
3514 g_return_if_fail (is_valid_builder (builder));
3515 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3516 g_return_if_fail (!GVSB(builder)->expected_type ||
3517 g_variant_type_is_subtype_of (type,
3518 GVSB(builder)->expected_type));
3519 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3520 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3523 parent = g_slice_dup (GVariantBuilder, builder);
3524 g_variant_builder_init (builder, type);
3525 GVSB(builder)->parent = parent;
3527 /* push the prev_item_type down into the subcontainer */
3528 if (GVSB(parent)->prev_item_type)
3530 if (!GVSB(builder)->uniform_item_types)
3531 /* tuples and dict entries */
3532 GVSB(builder)->prev_item_type =
3533 g_variant_type_first (GVSB(parent)->prev_item_type);
3535 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3536 /* maybes and arrays */
3537 GVSB(builder)->prev_item_type =
3538 g_variant_type_element (GVSB(parent)->prev_item_type);
3543 * g_variant_builder_close:
3544 * @builder: a #GVariantBuilder
3546 * Closes the subcontainer inside the given @builder that was opened by
3547 * the most recent call to g_variant_builder_open().
3549 * It is an error to call this function in any way that would create an
3550 * inconsistent value to be constructed (ie: too few values added to the
3556 g_variant_builder_close (GVariantBuilder *builder)
3558 GVariantBuilder *parent;
3560 g_return_if_fail (is_valid_builder (builder));
3561 g_return_if_fail (GVSB(builder)->parent != NULL);
3563 parent = GVSB(builder)->parent;
3564 GVSB(builder)->parent = NULL;
3566 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3569 g_slice_free (GVariantBuilder, parent);
3573 * g_variant_make_maybe_type:
3574 * @element: a #GVariant
3576 * Return the type of a maybe containing @element.
3578 static GVariantType *
3579 g_variant_make_maybe_type (GVariant *element)
3581 return g_variant_type_new_maybe (g_variant_get_type (element));
3585 * g_variant_make_array_type:
3586 * @element: a #GVariant
3588 * Return the type of an array containing @element.
3590 static GVariantType *
3591 g_variant_make_array_type (GVariant *element)
3593 return g_variant_type_new_array (g_variant_get_type (element));
3597 * g_variant_builder_end:
3598 * @builder: a #GVariantBuilder
3600 * Ends the builder process and returns the constructed value.
3602 * It is not permissible to use @builder in any way after this call
3603 * except for reference counting operations (in the case of a
3604 * heap-allocated #GVariantBuilder) or by reinitialising it with
3605 * g_variant_builder_init() (in the case of stack-allocated).
3607 * It is an error to call this function in any way that would create an
3608 * inconsistent value to be constructed (ie: insufficient number of
3609 * items added to a container with a specific number of children
3610 * required). It is also an error to call this function if the builder
3611 * was created with an indefinite array or maybe type and no children
3612 * have been added; in this case it is impossible to infer the type of
3615 * Returns: (transfer none): a new, floating, #GVariant
3620 g_variant_builder_end (GVariantBuilder *builder)
3622 GVariantType *my_type;
3625 g_return_val_if_fail (is_valid_builder (builder), NULL);
3626 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3628 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3629 GVSB(builder)->prev_item_type != NULL ||
3630 g_variant_type_is_definite (GVSB(builder)->type),
3633 if (g_variant_type_is_definite (GVSB(builder)->type))
3634 my_type = g_variant_type_copy (GVSB(builder)->type);
3636 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3637 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3639 else if (g_variant_type_is_array (GVSB(builder)->type))
3640 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3642 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3643 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3644 GVSB(builder)->offset);
3646 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3647 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3648 GVSB(builder)->children[1]);
3650 g_assert_not_reached ();
3652 value = g_variant_new_from_children (my_type,
3653 g_renew (GVariant *,
3654 GVSB(builder)->children,
3655 GVSB(builder)->offset),
3656 GVSB(builder)->offset,
3657 GVSB(builder)->trusted);
3658 GVSB(builder)->children = NULL;
3659 GVSB(builder)->offset = 0;
3661 g_variant_builder_clear (builder);
3662 g_variant_type_free (my_type);
3667 /* Format strings {{{1 */
3669 * g_variant_format_string_scan:
3670 * @string: a string that may be prefixed with a format string
3671 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3673 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3676 * Checks the string pointed to by @string for starting with a properly
3677 * formed #GVariant varargs format string. If no valid format string is
3678 * found then %FALSE is returned.
3680 * If @string does start with a valid format string then %TRUE is
3681 * returned. If @endptr is non-%NULL then it is updated to point to the
3682 * first character after the format string.
3684 * If @limit is non-%NULL then @limit (and any charater after it) will
3685 * not be accessed and the effect is otherwise equivalent to if the
3686 * character at @limit were nul.
3688 * See the section on <link linkend='gvariant-format-strings'>GVariant
3689 * Format Strings</link>.
3691 * Returns: %TRUE if there was a valid format string
3696 g_variant_format_string_scan (const gchar *string,
3698 const gchar **endptr)
3700 #define next_char() (string == limit ? '\0' : *string++)
3701 #define peek_char() (string == limit ? '\0' : *string)
3704 switch (next_char())
3706 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
3707 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
3708 case 'g': case 'v': case '*': case '?': case 'r':
3712 return g_variant_format_string_scan (string, limit, endptr);
3716 return g_variant_type_string_scan (string, limit, endptr);
3719 while (peek_char() != ')')
3720 if (!g_variant_format_string_scan (string, limit, &string))
3723 next_char(); /* consume ')' */
3733 if (c != 's' && c != 'o' && c != 'g')
3741 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3742 * The terminating null character is considered to be
3743 * part of the string.
3745 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3749 if (!g_variant_format_string_scan (string, limit, &string))
3752 if (next_char() != '}')
3758 if ((c = next_char()) == 'a')
3760 if ((c = next_char()) == '&')
3762 if ((c = next_char()) == 'a')
3764 if ((c = next_char()) == 'y')
3765 break; /* '^a&ay' */
3768 else if (c == 's' || c == 'o')
3769 break; /* '^a&s', '^a&o' */
3774 if ((c = next_char()) == 'y')
3778 else if (c == 's' || c == 'o')
3779 break; /* '^as', '^ao' */
3786 if ((c = next_char()) == 'a')
3788 if ((c = next_char()) == 'y')
3798 if (c != 's' && c != 'o' && c != 'g')
3817 * g_variant_check_format_string:
3818 * @value: a #GVariant
3819 * @format_string: a valid #GVariant format string
3820 * @copy_only: %TRUE to ensure the format string makes deep copies
3822 * Checks if calling g_variant_get() with @format_string on @value would
3823 * be valid from a type-compatibility standpoint. @format_string is
3824 * assumed to be a valid format string (from a syntactic standpoint).
3826 * If @copy_only is %TRUE then this function additionally checks that it
3827 * would be safe to call g_variant_unref() on @value immediately after
3828 * the call to g_variant_get() without invalidating the result. This is
3829 * only possible if deep copies are made (ie: there are no pointers to
3830 * the data inside of the soon-to-be-freed #GVariant instance). If this
3831 * check fails then a g_critical() is printed and %FALSE is returned.
3833 * This function is meant to be used by functions that wish to provide
3834 * varargs accessors to #GVariant values of uncertain values (eg:
3835 * g_variant_lookup() or g_menu_model_get_item_attribute()).
3837 * Returns: %TRUE if @format_string is safe to use
3842 g_variant_check_format_string (GVariant *value,
3843 const gchar *format_string,
3846 const gchar *original_format = format_string;
3847 const gchar *type_string;
3849 /* Interesting factoid: assuming a format string is valid, it can be
3850 * converted to a type string by removing all '@' '&' and '^'
3853 * Instead of doing that, we can just skip those characters when
3854 * comparing it to the type string of @value.
3856 * For the copy-only case we can just drop the '&' from the list of
3857 * characters to skip over. A '&' will never appear in a type string
3858 * so we know that it won't be possible to return %TRUE if it is in a
3861 type_string = g_variant_get_type_string (value);
3863 while (*type_string || *format_string)
3865 gchar format = *format_string++;
3870 if G_UNLIKELY (copy_only)
3872 /* for the love of all that is good, please don't mark this string for translation... */
3873 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
3874 "interface to validate the passed format string for type safety. The passed format "
3875 "(%s) contains a '&' character which would result in a pointer being returned to the "
3876 "data inside of a GVariant instance that may no longer exist by the time the function "
3877 "returns. Modify your code to use a format string without '&'.", original_format);
3884 /* ignore these 2 (or 3) */
3888 /* attempt to consume one of 'bynqiuxthdsog' */
3890 char s = *type_string++;
3892 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
3898 /* ensure it's a tuple */
3899 if (*type_string != '(')
3904 /* consume a full type string for the '*' or 'r' */
3905 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
3911 /* attempt to consume exactly one character equal to the format */
3912 if (format != *type_string++)
3921 * g_variant_format_string_scan_type:
3922 * @string: a string that may be prefixed with a format string
3923 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3925 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3928 * If @string starts with a valid format string then this function will
3929 * return the type that the format string corresponds to. Otherwise
3930 * this function returns %NULL.
3932 * Use g_variant_type_free() to free the return value when you no longer
3935 * This function is otherwise exactly like
3936 * g_variant_format_string_scan().
3938 * Returns: (allow-none): a #GVariantType if there was a valid format string
3943 g_variant_format_string_scan_type (const gchar *string,
3945 const gchar **endptr)
3947 const gchar *my_end;
3954 if (!g_variant_format_string_scan (string, limit, endptr))
3957 dest = new = g_malloc (*endptr - string + 1);
3958 while (string != *endptr)
3960 if (*string != '@' && *string != '&' && *string != '^')
3966 return (GVariantType *) G_VARIANT_TYPE (new);
3970 valid_format_string (const gchar *format_string,
3974 const gchar *endptr;
3977 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3979 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3982 g_critical ("'%s' is not a valid GVariant format string",
3985 g_critical ("'%s' does not have a valid GVariant format "
3986 "string as a prefix", format_string);
3989 g_variant_type_free (type);
3994 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3999 fragment = g_strndup (format_string, endptr - format_string);
4000 typestr = g_variant_type_dup_string (type);
4002 g_critical ("the GVariant format string '%s' has a type of "
4003 "'%s' but the given value has a type of '%s'",
4004 fragment, typestr, g_variant_get_type_string (value));
4006 g_variant_type_free (type);
4013 g_variant_type_free (type);
4018 /* Variable Arguments {{{1 */
4019 /* We consider 2 main classes of format strings:
4021 * - recursive format strings
4022 * these are ones that result in recursion and the collection of
4023 * possibly more than one argument. Maybe types, tuples,
4024 * dictionary entries.
4026 * - leaf format string
4027 * these result in the collection of a single argument.
4029 * Leaf format strings are further subdivided into two categories:
4031 * - single non-null pointer ("nnp")
4032 * these either collect or return a single non-null pointer.
4035 * these collect or return something else (bool, number, etc).
4037 * Based on the above, the varargs handling code is split into 4 main parts:
4039 * - nnp handling code
4040 * - leaf handling code (which may invoke nnp code)
4041 * - generic handling code (may be recursive, may invoke leaf code)
4042 * - user-facing API (which invokes the generic code)
4044 * Each section implements some of the following functions:
4047 * collect the arguments for the format string as if
4048 * g_variant_new() had been called, but do nothing with them. used
4049 * for skipping over arguments when constructing a Nothing maybe
4053 * create a GVariant *
4056 * unpack a GVariant *
4058 * - free (nnp only):
4059 * free a previously allocated item
4063 g_variant_format_string_is_leaf (const gchar *str)
4065 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4069 g_variant_format_string_is_nnp (const gchar *str)
4071 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4072 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4073 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4076 /* Single non-null pointer ("nnp") {{{2 */
4078 g_variant_valist_free_nnp (const gchar *str,
4084 g_variant_iter_free (ptr);
4088 if (str[2] != '&') /* '^as', '^ao' */
4090 else /* '^a&s', '^a&o' */
4104 g_variant_unref (ptr);
4111 g_assert_not_reached ();
4116 g_variant_scan_convenience (const gchar **str,
4139 g_variant_valist_new_nnp (const gchar **str,
4150 const GVariantType *type;
4153 value = g_variant_builder_end (ptr);
4154 type = g_variant_get_type (value);
4156 if G_UNLIKELY (!g_variant_type_is_array (type))
4157 g_error ("g_variant_new: expected array GVariantBuilder but "
4158 "the built value has type '%s'",
4159 g_variant_get_type_string (value));
4161 type = g_variant_type_element (type);
4163 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4164 g_error ("g_variant_new: expected GVariantBuilder array element "
4165 "type '%s' but the built value has element type '%s'",
4166 g_variant_type_dup_string ((GVariantType *) *str),
4167 g_variant_get_type_string (value) + 1);
4169 g_variant_type_string_scan (*str, NULL, str);
4175 /* special case: NULL pointer for empty array */
4177 const GVariantType *type = (GVariantType *) *str;
4179 g_variant_type_string_scan (*str, NULL, str);
4181 if G_UNLIKELY (!g_variant_type_is_definite (type))
4182 g_error ("g_variant_new: NULL pointer given with indefinite "
4183 "array type; unable to determine which type of empty "
4184 "array to construct.");
4186 return g_variant_new_array (type, NULL, 0);
4193 value = g_variant_new_string (ptr);
4196 value = g_variant_new_string ("[Invalid UTF-8]");
4202 return g_variant_new_object_path (ptr);
4205 return g_variant_new_signature (ptr);
4213 type = g_variant_scan_convenience (str, &constant, &arrays);
4216 return g_variant_new_strv (ptr, -1);
4219 return g_variant_new_objv (ptr, -1);
4222 return g_variant_new_bytestring_array (ptr, -1);
4224 return g_variant_new_bytestring (ptr);
4228 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4229 g_error ("g_variant_new: expected GVariant of type '%s' but "
4230 "received value has type '%s'",
4231 g_variant_type_dup_string ((GVariantType *) *str),
4232 g_variant_get_type_string (ptr));
4234 g_variant_type_string_scan (*str, NULL, str);
4242 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4243 g_error ("g_variant_new: format string '?' expects basic-typed "
4244 "GVariant, but received value has type '%s'",
4245 g_variant_get_type_string (ptr));
4250 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4251 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4252 "GVariant, but received value has type '%s'",
4253 g_variant_get_type_string (ptr));
4258 return g_variant_new_variant (ptr);
4261 g_assert_not_reached ();
4266 g_variant_valist_get_nnp (const gchar **str,
4272 g_variant_type_string_scan (*str, NULL, str);
4273 return g_variant_iter_new (value);
4277 return (gchar *) g_variant_get_string (value, NULL);
4282 return g_variant_dup_string (value, NULL);
4290 type = g_variant_scan_convenience (str, &constant, &arrays);
4295 return g_variant_get_strv (value, NULL);
4297 return g_variant_dup_strv (value, NULL);
4300 else if (type == 'o')
4303 return g_variant_get_objv (value, NULL);
4305 return g_variant_dup_objv (value, NULL);
4308 else if (arrays > 1)
4311 return g_variant_get_bytestring_array (value, NULL);
4313 return g_variant_dup_bytestring_array (value, NULL);
4319 return (gchar *) g_variant_get_bytestring (value);
4321 return g_variant_dup_bytestring (value, NULL);
4326 g_variant_type_string_scan (*str, NULL, str);
4332 return g_variant_ref (value);
4335 return g_variant_get_variant (value);
4338 g_assert_not_reached ();
4344 g_variant_valist_skip_leaf (const gchar **str,
4347 if (g_variant_format_string_is_nnp (*str))
4349 g_variant_format_string_scan (*str, NULL, str);
4350 va_arg (*app, gpointer);
4368 va_arg (*app, guint64);
4372 va_arg (*app, gdouble);
4376 g_assert_not_reached ();
4381 g_variant_valist_new_leaf (const gchar **str,
4384 if (g_variant_format_string_is_nnp (*str))
4385 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4390 return g_variant_new_boolean (va_arg (*app, gboolean));
4393 return g_variant_new_byte (va_arg (*app, guint));
4396 return g_variant_new_int16 (va_arg (*app, gint));
4399 return g_variant_new_uint16 (va_arg (*app, guint));
4402 return g_variant_new_int32 (va_arg (*app, gint));
4405 return g_variant_new_uint32 (va_arg (*app, guint));
4408 return g_variant_new_int64 (va_arg (*app, gint64));
4411 return g_variant_new_uint64 (va_arg (*app, guint64));
4414 return g_variant_new_handle (va_arg (*app, gint));
4417 return g_variant_new_double (va_arg (*app, gdouble));
4420 g_assert_not_reached ();
4424 /* The code below assumes this */
4425 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4426 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4429 g_variant_valist_get_leaf (const gchar **str,
4434 gpointer ptr = va_arg (*app, gpointer);
4438 g_variant_format_string_scan (*str, NULL, str);
4442 if (g_variant_format_string_is_nnp (*str))
4444 gpointer *nnp = (gpointer *) ptr;
4446 if (free && *nnp != NULL)
4447 g_variant_valist_free_nnp (*str, *nnp);
4452 *nnp = g_variant_valist_get_nnp (str, value);
4454 g_variant_format_string_scan (*str, NULL, str);
4464 *(gboolean *) ptr = g_variant_get_boolean (value);
4468 *(guchar *) ptr = g_variant_get_byte (value);
4472 *(gint16 *) ptr = g_variant_get_int16 (value);
4476 *(guint16 *) ptr = g_variant_get_uint16 (value);
4480 *(gint32 *) ptr = g_variant_get_int32 (value);
4484 *(guint32 *) ptr = g_variant_get_uint32 (value);
4488 *(gint64 *) ptr = g_variant_get_int64 (value);
4492 *(guint64 *) ptr = g_variant_get_uint64 (value);
4496 *(gint32 *) ptr = g_variant_get_handle (value);
4500 *(gdouble *) ptr = g_variant_get_double (value);
4509 *(guchar *) ptr = 0;
4514 *(guint16 *) ptr = 0;
4521 *(guint32 *) ptr = 0;
4527 *(guint64 *) ptr = 0;
4532 g_assert_not_reached ();
4535 /* Generic (recursive) {{{2 */
4537 g_variant_valist_skip (const gchar **str,
4540 if (g_variant_format_string_is_leaf (*str))
4541 g_variant_valist_skip_leaf (str, app);
4543 else if (**str == 'm') /* maybe */
4547 if (!g_variant_format_string_is_nnp (*str))
4548 va_arg (*app, gboolean);
4550 g_variant_valist_skip (str, app);
4552 else /* tuple, dictionary entry */
4554 g_assert (**str == '(' || **str == '{');
4556 while (**str != ')' && **str != '}')
4557 g_variant_valist_skip (str, app);
4563 g_variant_valist_new (const gchar **str,
4566 if (g_variant_format_string_is_leaf (*str))
4567 return g_variant_valist_new_leaf (str, app);
4569 if (**str == 'm') /* maybe */
4571 GVariantType *type = NULL;
4572 GVariant *value = NULL;
4576 if (g_variant_format_string_is_nnp (*str))
4578 gpointer nnp = va_arg (*app, gpointer);
4581 value = g_variant_valist_new_nnp (str, nnp);
4583 type = g_variant_format_string_scan_type (*str, NULL, str);
4587 gboolean just = va_arg (*app, gboolean);
4590 value = g_variant_valist_new (str, app);
4593 type = g_variant_format_string_scan_type (*str, NULL, NULL);
4594 g_variant_valist_skip (str, app);
4598 value = g_variant_new_maybe (type, value);
4601 g_variant_type_free (type);
4605 else /* tuple, dictionary entry */
4610 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
4613 g_assert (**str == '{');
4614 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
4618 while (**str != ')' && **str != '}')
4619 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
4622 return g_variant_builder_end (&b);
4627 g_variant_valist_get (const gchar **str,
4632 if (g_variant_format_string_is_leaf (*str))
4633 g_variant_valist_get_leaf (str, value, free, app);
4635 else if (**str == 'm')
4640 value = g_variant_get_maybe (value);
4642 if (!g_variant_format_string_is_nnp (*str))
4644 gboolean *ptr = va_arg (*app, gboolean *);
4647 *ptr = value != NULL;
4650 g_variant_valist_get (str, value, free, app);
4653 g_variant_unref (value);
4656 else /* tuple, dictionary entry */
4660 g_assert (**str == '(' || **str == '{');
4663 while (**str != ')' && **str != '}')
4667 GVariant *child = g_variant_get_child_value (value, index++);
4668 g_variant_valist_get (str, child, free, app);
4669 g_variant_unref (child);
4672 g_variant_valist_get (str, NULL, free, app);
4678 /* User-facing API {{{2 */
4680 * g_variant_new: (skip)
4681 * @format_string: a #GVariant format string
4682 * @...: arguments, as per @format_string
4684 * Creates a new #GVariant instance.
4686 * Think of this function as an analogue to g_strdup_printf().
4688 * The type of the created instance and the arguments that are
4689 * expected by this function are determined by @format_string. See the
4690 * section on <link linkend='gvariant-format-strings'>GVariant Format
4691 * Strings</link>. Please note that the syntax of the format string is
4692 * very likely to be extended in the future.
4694 * The first character of the format string must not be '*' '?' '@' or
4695 * 'r'; in essence, a new #GVariant must always be constructed by this
4696 * function (and not merely passed through it unmodified).
4698 * Returns: a new floating #GVariant instance
4703 g_variant_new (const gchar *format_string,
4709 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
4710 format_string[0] != '?' && format_string[0] != '@' &&
4711 format_string[0] != '*' && format_string[0] != 'r',
4714 va_start (ap, format_string);
4715 value = g_variant_new_va (format_string, NULL, &ap);
4722 * g_variant_new_va: (skip)
4723 * @format_string: a string that is prefixed with a format string
4724 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4726 * @app: a pointer to a #va_list
4728 * This function is intended to be used by libraries based on
4729 * #GVariant that want to provide g_variant_new()-like functionality
4732 * The API is more general than g_variant_new() to allow a wider range
4735 * @format_string must still point to a valid format string, but it only
4736 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
4737 * non-%NULL then it is updated to point to the first character past the
4738 * end of the format string.
4740 * @app is a pointer to a #va_list. The arguments, according to
4741 * @format_string, are collected from this #va_list and the list is left
4742 * pointing to the argument following the last.
4744 * These two generalisations allow mixing of multiple calls to
4745 * g_variant_new_va() and g_variant_get_va() within a single actual
4746 * varargs call by the user.
4748 * The return value will be floating if it was a newly created GVariant
4749 * instance (for example, if the format string was "(ii)"). In the case
4750 * that the format_string was '*', '?', 'r', or a format starting with
4751 * '@' then the collected #GVariant pointer will be returned unmodified,
4752 * without adding any additional references.
4754 * In order to behave correctly in all cases it is necessary for the
4755 * calling function to g_variant_ref_sink() the return result before
4756 * returning control to the user that originally provided the pointer.
4757 * At this point, the caller will have their own full reference to the
4758 * result. This can also be done by adding the result to a container,
4759 * or by passing it to another g_variant_new() call.
4761 * Returns: a new, usually floating, #GVariant
4766 g_variant_new_va (const gchar *format_string,
4767 const gchar **endptr,
4772 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
4774 g_return_val_if_fail (app != NULL, NULL);
4776 value = g_variant_valist_new (&format_string, app);
4779 *endptr = format_string;
4785 * g_variant_get: (skip)
4786 * @value: a #GVariant instance
4787 * @format_string: a #GVariant format string
4788 * @...: arguments, as per @format_string
4790 * Deconstructs a #GVariant instance.
4792 * Think of this function as an analogue to scanf().
4794 * The arguments that are expected by this function are entirely
4795 * determined by @format_string. @format_string also restricts the
4796 * permissible types of @value. It is an error to give a value with
4797 * an incompatible type. See the section on <link
4798 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
4799 * Please note that the syntax of the format string is very likely to be
4800 * extended in the future.
4802 * @format_string determines the C types that are used for unpacking
4803 * the values and also determines if the values are copied or borrowed,
4804 * see the section on
4805 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4810 g_variant_get (GVariant *value,
4811 const gchar *format_string,
4816 g_return_if_fail (valid_format_string (format_string, TRUE, value));
4818 /* if any direct-pointer-access formats are in use, flatten first */
4819 if (strchr (format_string, '&'))
4820 g_variant_get_data (value);
4822 va_start (ap, format_string);
4823 g_variant_get_va (value, format_string, NULL, &ap);
4828 * g_variant_get_va: (skip)
4829 * @value: a #GVariant
4830 * @format_string: a string that is prefixed with a format string
4831 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4833 * @app: a pointer to a #va_list
4835 * This function is intended to be used by libraries based on #GVariant
4836 * that want to provide g_variant_get()-like functionality to their
4839 * The API is more general than g_variant_get() to allow a wider range
4842 * @format_string must still point to a valid format string, but it only
4843 * need to be nul-terminated if @endptr is %NULL. If @endptr is
4844 * non-%NULL then it is updated to point to the first character past the
4845 * end of the format string.
4847 * @app is a pointer to a #va_list. The arguments, according to
4848 * @format_string, are collected from this #va_list and the list is left
4849 * pointing to the argument following the last.
4851 * These two generalisations allow mixing of multiple calls to
4852 * g_variant_new_va() and g_variant_get_va() within a single actual
4853 * varargs call by the user.
4855 * @format_string determines the C types that are used for unpacking
4856 * the values and also determines if the values are copied or borrowed,
4857 * see the section on
4858 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4863 g_variant_get_va (GVariant *value,
4864 const gchar *format_string,
4865 const gchar **endptr,
4868 g_return_if_fail (valid_format_string (format_string, !endptr, value));
4869 g_return_if_fail (value != NULL);
4870 g_return_if_fail (app != NULL);
4872 /* if any direct-pointer-access formats are in use, flatten first */
4873 if (strchr (format_string, '&'))
4874 g_variant_get_data (value);
4876 g_variant_valist_get (&format_string, value, FALSE, app);
4879 *endptr = format_string;
4882 /* Varargs-enabled Utility Functions {{{1 */
4885 * g_variant_builder_add: (skip)
4886 * @builder: a #GVariantBuilder
4887 * @format_string: a #GVariant varargs format string
4888 * @...: arguments, as per @format_string
4890 * Adds to a #GVariantBuilder.
4892 * This call is a convenience wrapper that is exactly equivalent to
4893 * calling g_variant_new() followed by g_variant_builder_add_value().
4895 * This function might be used as follows:
4899 * make_pointless_dictionary (void)
4901 * GVariantBuilder builder;
4904 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
4905 * for (i = 0; i < 16; i++)
4909 * sprintf (buf, "%d", i);
4910 * g_variant_builder_add (&builder, "{is}", i, buf);
4913 * return g_variant_builder_end (&builder);
4920 g_variant_builder_add (GVariantBuilder *builder,
4921 const gchar *format_string,
4927 va_start (ap, format_string);
4928 variant = g_variant_new_va (format_string, NULL, &ap);
4931 g_variant_builder_add_value (builder, variant);
4935 * g_variant_get_child: (skip)
4936 * @value: a container #GVariant
4937 * @index_: the index of the child to deconstruct
4938 * @format_string: a #GVariant format string
4939 * @...: arguments, as per @format_string
4941 * Reads a child item out of a container #GVariant instance and
4942 * deconstructs it according to @format_string. This call is
4943 * essentially a combination of g_variant_get_child_value() and
4946 * @format_string determines the C types that are used for unpacking
4947 * the values and also determines if the values are copied or borrowed,
4948 * see the section on
4949 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4954 g_variant_get_child (GVariant *value,
4956 const gchar *format_string,
4962 child = g_variant_get_child_value (value, index_);
4963 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4965 va_start (ap, format_string);
4966 g_variant_get_va (child, format_string, NULL, &ap);
4969 g_variant_unref (child);
4973 * g_variant_iter_next: (skip)
4974 * @iter: a #GVariantIter
4975 * @format_string: a GVariant format string
4976 * @...: the arguments to unpack the value into
4978 * Gets the next item in the container and unpacks it into the variable
4979 * argument list according to @format_string, returning %TRUE.
4981 * If no more items remain then %FALSE is returned.
4983 * All of the pointers given on the variable arguments list of this
4984 * function are assumed to point at uninitialised memory. It is the
4985 * responsibility of the caller to free all of the values returned by
4986 * the unpacking process.
4988 * See the section on <link linkend='gvariant-format-strings'>GVariant
4989 * Format Strings</link>.
4992 * <title>Memory management with g_variant_iter_next()</title>
4994 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4996 * iterate_dictionary (GVariant *dictionary)
4998 * GVariantIter iter;
5002 * g_variant_iter_init (&iter, dictionary);
5003 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5005 * g_print ("Item '%s' has type '%s'\n", key,
5006 * g_variant_get_type_string (value));
5008 * /<!-- -->* must free data for ourselves *<!-- -->/
5009 * g_variant_unref (value);
5016 * For a solution that is likely to be more convenient to C programmers
5017 * when dealing with loops, see g_variant_iter_loop().
5019 * @format_string determines the C types that are used for unpacking
5020 * the values and also determines if the values are copied or borrowed,
5021 * see the section on
5022 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5024 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5029 g_variant_iter_next (GVariantIter *iter,
5030 const gchar *format_string,
5035 value = g_variant_iter_next_value (iter);
5037 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5044 va_start (ap, format_string);
5045 g_variant_valist_get (&format_string, value, FALSE, &ap);
5048 g_variant_unref (value);
5051 return value != NULL;
5055 * g_variant_iter_loop: (skip)
5056 * @iter: a #GVariantIter
5057 * @format_string: a GVariant format string
5058 * @...: the arguments to unpack the value into
5060 * Gets the next item in the container and unpacks it into the variable
5061 * argument list according to @format_string, returning %TRUE.
5063 * If no more items remain then %FALSE is returned.
5065 * On the first call to this function, the pointers appearing on the
5066 * variable argument list are assumed to point at uninitialised memory.
5067 * On the second and later calls, it is assumed that the same pointers
5068 * will be given and that they will point to the memory as set by the
5069 * previous call to this function. This allows the previous values to
5070 * be freed, as appropriate.
5072 * This function is intended to be used with a while loop as
5073 * demonstrated in the following example. This function can only be
5074 * used when iterating over an array. It is only valid to call this
5075 * function with a string constant for the format string and the same
5076 * string constant must be used each time. Mixing calls to this
5077 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5078 * the same iterator causes undefined behavior.
5080 * If you break out of a such a while loop using g_variant_iter_loop() then
5081 * you must free or unreference all the unpacked values as you would with
5082 * g_variant_get(). Failure to do so will cause a memory leak.
5084 * See the section on <link linkend='gvariant-format-strings'>GVariant
5085 * Format Strings</link>.
5088 * <title>Memory management with g_variant_iter_loop()</title>
5090 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
5092 * iterate_dictionary (GVariant *dictionary)
5094 * GVariantIter iter;
5098 * g_variant_iter_init (&iter, dictionary);
5099 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5101 * g_print ("Item '%s' has type '%s'\n", key,
5102 * g_variant_get_type_string (value));
5104 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
5105 * /<!-- -->* unless breaking out of this loop *<!-- -->/
5111 * For most cases you should use g_variant_iter_next().
5113 * This function is really only useful when unpacking into #GVariant or
5114 * #GVariantIter in order to allow you to skip the call to
5115 * g_variant_unref() or g_variant_iter_free().
5117 * For example, if you are only looping over simple integer and string
5118 * types, g_variant_iter_next() is definitely preferred. For string
5119 * types, use the '&' prefix to avoid allocating any memory at all (and
5120 * thereby avoiding the need to free anything as well).
5122 * @format_string determines the C types that are used for unpacking
5123 * the values and also determines if the values are copied or borrowed,
5124 * see the section on
5125 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5127 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5133 g_variant_iter_loop (GVariantIter *iter,
5134 const gchar *format_string,
5137 gboolean first_time = GVSI(iter)->loop_format == NULL;
5141 g_return_val_if_fail (first_time ||
5142 format_string == GVSI(iter)->loop_format,
5147 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5148 GVSI(iter)->loop_format = format_string;
5150 if (strchr (format_string, '&'))
5151 g_variant_get_data (GVSI(iter)->value);
5154 value = g_variant_iter_next_value (iter);
5156 g_return_val_if_fail (!first_time ||
5157 valid_format_string (format_string, TRUE, value),
5160 va_start (ap, format_string);
5161 g_variant_valist_get (&format_string, value, !first_time, &ap);
5165 g_variant_unref (value);
5167 return value != NULL;
5170 /* Serialised data {{{1 */
5172 g_variant_deep_copy (GVariant *value)
5174 switch (g_variant_classify (value))
5176 case G_VARIANT_CLASS_MAYBE:
5177 case G_VARIANT_CLASS_ARRAY:
5178 case G_VARIANT_CLASS_TUPLE:
5179 case G_VARIANT_CLASS_DICT_ENTRY:
5180 case G_VARIANT_CLASS_VARIANT:
5182 GVariantBuilder builder;
5186 g_variant_builder_init (&builder, g_variant_get_type (value));
5187 g_variant_iter_init (&iter, value);
5189 while ((child = g_variant_iter_next_value (&iter)))
5191 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5192 g_variant_unref (child);
5195 return g_variant_builder_end (&builder);
5198 case G_VARIANT_CLASS_BOOLEAN:
5199 return g_variant_new_boolean (g_variant_get_boolean (value));
5201 case G_VARIANT_CLASS_BYTE:
5202 return g_variant_new_byte (g_variant_get_byte (value));
5204 case G_VARIANT_CLASS_INT16:
5205 return g_variant_new_int16 (g_variant_get_int16 (value));
5207 case G_VARIANT_CLASS_UINT16:
5208 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5210 case G_VARIANT_CLASS_INT32:
5211 return g_variant_new_int32 (g_variant_get_int32 (value));
5213 case G_VARIANT_CLASS_UINT32:
5214 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5216 case G_VARIANT_CLASS_INT64:
5217 return g_variant_new_int64 (g_variant_get_int64 (value));
5219 case G_VARIANT_CLASS_UINT64:
5220 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5222 case G_VARIANT_CLASS_HANDLE:
5223 return g_variant_new_handle (g_variant_get_handle (value));
5225 case G_VARIANT_CLASS_DOUBLE:
5226 return g_variant_new_double (g_variant_get_double (value));
5228 case G_VARIANT_CLASS_STRING:
5229 return g_variant_new_string (g_variant_get_string (value, NULL));
5231 case G_VARIANT_CLASS_OBJECT_PATH:
5232 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5234 case G_VARIANT_CLASS_SIGNATURE:
5235 return g_variant_new_signature (g_variant_get_string (value, NULL));
5238 g_assert_not_reached ();
5242 * g_variant_get_normal_form:
5243 * @value: a #GVariant
5245 * Gets a #GVariant instance that has the same value as @value and is
5246 * trusted to be in normal form.
5248 * If @value is already trusted to be in normal form then a new
5249 * reference to @value is returned.
5251 * If @value is not already trusted, then it is scanned to check if it
5252 * is in normal form. If it is found to be in normal form then it is
5253 * marked as trusted and a new reference to it is returned.
5255 * If @value is found not to be in normal form then a new trusted
5256 * #GVariant is created with the same value as @value.
5258 * It makes sense to call this function if you've received #GVariant
5259 * data from untrusted sources and you want to ensure your serialised
5260 * output is definitely in normal form.
5262 * Returns: (transfer full): a trusted #GVariant
5267 g_variant_get_normal_form (GVariant *value)
5271 if (g_variant_is_normal_form (value))
5272 return g_variant_ref (value);
5274 trusted = g_variant_deep_copy (value);
5275 g_assert (g_variant_is_trusted (trusted));
5277 return g_variant_ref_sink (trusted);
5281 * g_variant_byteswap:
5282 * @value: a #GVariant
5284 * Performs a byteswapping operation on the contents of @value. The
5285 * result is that all multi-byte numeric data contained in @value is
5286 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5287 * integers as well as file handles and double precision floating point
5290 * This function is an identity mapping on any value that does not
5291 * contain multi-byte numeric data. That include strings, booleans,
5292 * bytes and containers containing only these things (recursively).
5294 * The returned value is always in normal form and is marked as trusted.
5296 * Returns: (transfer full): the byteswapped form of @value
5301 g_variant_byteswap (GVariant *value)
5303 GVariantTypeInfo *type_info;
5307 type_info = g_variant_get_type_info (value);
5309 g_variant_type_info_query (type_info, &alignment, NULL);
5312 /* (potentially) contains multi-byte numeric data */
5314 GVariantSerialised serialised;
5318 trusted = g_variant_get_normal_form (value);
5319 serialised.type_info = g_variant_get_type_info (trusted);
5320 serialised.size = g_variant_get_size (trusted);
5321 serialised.data = g_malloc (serialised.size);
5322 g_variant_store (trusted, serialised.data);
5323 g_variant_unref (trusted);
5325 g_variant_serialised_byteswap (serialised);
5327 bytes = g_bytes_new_take (serialised.data, serialised.size);
5328 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5329 g_bytes_unref (bytes);
5332 /* contains no multi-byte data */
5335 return g_variant_ref_sink (new);
5339 * g_variant_new_from_data:
5340 * @type: a definite #GVariantType
5341 * @data: (array length=size) (element-type guint8): the serialised data
5342 * @size: the size of @data
5343 * @trusted: %TRUE if @data is definitely in normal form
5344 * @notify: (scope async): function to call when @data is no longer needed
5345 * @user_data: data for @notify
5347 * Creates a new #GVariant instance from serialised data.
5349 * @type is the type of #GVariant instance that will be constructed.
5350 * The interpretation of @data depends on knowing the type.
5352 * @data is not modified by this function and must remain valid with an
5353 * unchanging value until such a time as @notify is called with
5354 * @user_data. If the contents of @data change before that time then
5355 * the result is undefined.
5357 * If @data is trusted to be serialised data in normal form then
5358 * @trusted should be %TRUE. This applies to serialised data created
5359 * within this process or read from a trusted location on the disk (such
5360 * as a file installed in /usr/lib alongside your application). You
5361 * should set trusted to %FALSE if @data is read from the network, a
5362 * file in the user's home directory, etc.
5364 * If @data was not stored in this machine's native endianness, any multi-byte
5365 * numeric values in the returned variant will also be in non-native
5366 * endianness. g_variant_byteswap() can be used to recover the original values.
5368 * @notify will be called with @user_data when @data is no longer
5369 * needed. The exact time of this call is unspecified and might even be
5370 * before this function returns.
5372 * Returns: (transfer none): a new floating #GVariant of type @type
5377 g_variant_new_from_data (const GVariantType *type,
5381 GDestroyNotify notify,
5387 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5388 g_return_val_if_fail (data != NULL || size == 0, NULL);
5391 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5393 bytes = g_bytes_new_static (data, size);
5395 value = g_variant_new_from_bytes (type, bytes, trusted);
5396 g_bytes_unref (bytes);
5402 /* vim:set foldmethod=marker: */