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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: Ryan Lortie <desrt@desrt.ca>
27 #include <glib/gvariant-serialiser.h>
28 #include "gvariant-internal.h"
29 #include <glib/gvariant-core.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gstrfuncs.h>
32 #include <glib/gslice.h>
33 #include <glib/ghash.h>
34 #include <glib/gmem.h>
42 * @short_description: strongly typed value datatype
43 * @see_also: GVariantType
45 * #GVariant is a variant datatype; it stores a value along with
46 * information about the type of that value. The range of possible
47 * values is determined by the type. The type system used by #GVariant
50 * #GVariant instances always have a type and a value (which are given
51 * at construction time). The type and value of a #GVariant instance
52 * can never change other than by the #GVariant itself being
53 * destroyed. A #GVariant cannot contain a pointer.
55 * #GVariant is reference counted using g_variant_ref() and
56 * g_variant_unref(). #GVariant also has floating reference counts --
57 * see g_variant_ref_sink().
59 * #GVariant is completely threadsafe. A #GVariant instance can be
60 * concurrently accessed in any way from any number of threads without
63 * #GVariant is heavily optimised for dealing with data in serialised
64 * form. It works particularly well with data located in memory-mapped
65 * files. It can perform nearly all deserialisation operations in a
66 * small constant time, usually touching only a single memory page.
67 * Serialised #GVariant data can also be sent over the network.
69 * #GVariant is largely compatible with D-Bus. Almost all types of
70 * #GVariant instances can be sent over D-Bus. See #GVariantType for
71 * exceptions. (However, #GVariant's serialisation format is not the same
72 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
73 * in the gio library, for those.)
75 * For space-efficiency, the #GVariant serialisation format does not
76 * automatically include the variant's type or endianness, which must
77 * either be implied from context (such as knowledge that a particular
78 * file format always contains a little-endian %G_VARIANT_TYPE_VARIANT)
79 * or supplied out-of-band (for instance, a type and/or endianness
80 * indicator could be placed at the beginning of a file, network message
83 * A #GVariant's size is limited mainly by any lower level operating
84 * system constraints, such as the number of bits in #gsize. For
85 * example, it is reasonable to have a 2GB file mapped into memory
86 * with #GMappedFile, and call g_variant_new_from_data() on it.
88 * For convenience to C programmers, #GVariant features powerful
89 * varargs-based value construction and destruction. This feature is
90 * designed to be embedded in other libraries.
92 * There is a Python-inspired text language for describing #GVariant
93 * values. #GVariant includes a printer for this language and a parser
94 * with type inferencing.
97 * <title>Memory Use</title>
99 * #GVariant tries to be quite efficient with respect to memory use.
100 * This section gives a rough idea of how much memory is used by the
101 * current implementation. The information here is subject to change
105 * The memory allocated by #GVariant can be grouped into 4 broad
106 * purposes: memory for serialised data, memory for the type
107 * information cache, buffer management memory and memory for the
108 * #GVariant structure itself.
110 * <refsect3 id="gvariant-serialised-data-memory">
111 * <title>Serialised Data Memory</title>
113 * This is the memory that is used for storing GVariant data in
114 * serialised form. This is what would be sent over the network or
115 * what would end up on disk.
118 * The amount of memory required to store a boolean is 1 byte. 16,
119 * 32 and 64 bit integers and double precision floating point numbers
120 * use their "natural" size. Strings (including object path and
121 * signature strings) are stored with a nul terminator, and as such
122 * use the length of the string plus 1 byte.
125 * Maybe types use no space at all to represent the null value and
126 * use the same amount of space (sometimes plus one byte) as the
127 * equivalent non-maybe-typed value to represent the non-null case.
130 * Arrays use the amount of space required to store each of their
131 * members, concatenated. Additionally, if the items stored in an
132 * array are not of a fixed-size (ie: strings, other arrays, etc)
133 * then an additional framing offset is stored for each item. The
134 * size of this offset is either 1, 2 or 4 bytes depending on the
135 * overall size of the container. Additionally, extra padding bytes
136 * are added as required for alignment of child values.
139 * Tuples (including dictionary entries) use the amount of space
140 * required to store each of their members, concatenated, plus one
141 * framing offset (as per arrays) for each non-fixed-sized item in
142 * the tuple, except for the last one. Additionally, extra padding
143 * bytes are added as required for alignment of child values.
146 * Variants use the same amount of space as the item inside of the
147 * variant, plus 1 byte, plus the length of the type string for the
148 * item inside the variant.
151 * As an example, consider a dictionary mapping strings to variants.
152 * In the case that the dictionary is empty, 0 bytes are required for
156 * If we add an item "width" that maps to the int32 value of 500 then
157 * we will use 4 byte to store the int32 (so 6 for the variant
158 * containing it) and 6 bytes for the string. The variant must be
159 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
160 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
161 * for the dictionary entry. An additional 1 byte is added to the
162 * array as a framing offset making a total of 15 bytes.
165 * If we add another entry, "title" that maps to a nullable string
166 * that happens to have a value of null, then we use 0 bytes for the
167 * null value (and 3 bytes for the variant to contain it along with
168 * its type string) plus 6 bytes for the string. Again, we need 2
169 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
172 * We now require extra padding between the two items in the array.
173 * After the 14 bytes of the first item, that's 2 bytes required. We
174 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
175 * + 2 = 29 bytes to encode the entire two-item dictionary.
179 * <title>Type Information Cache</title>
181 * For each GVariant type that currently exists in the program a type
182 * information structure is kept in the type information cache. The
183 * type information structure is required for rapid deserialisation.
186 * Continuing with the above example, if a #GVariant exists with the
187 * type "a{sv}" then a type information struct will exist for
188 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
189 * will share the same type information. Additionally, all
190 * single-digit types are stored in read-only static memory and do
191 * not contribute to the writable memory footprint of a program using
195 * Aside from the type information structures stored in read-only
196 * memory, there are two forms of type information. One is used for
197 * container types where there is a single element type: arrays and
198 * maybe types. The other is used for container types where there
199 * are multiple element types: tuples and dictionary entries.
202 * Array type info structures are 6 * sizeof (void *), plus the
203 * memory required to store the type string itself. This means that
204 * on 32bit systems, the cache entry for "a{sv}" would require 30
205 * bytes of memory (plus malloc overhead).
208 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
209 * sizeof (void *) for each item in the tuple, plus the memory
210 * required to store the type string itself. A 2-item tuple, for
211 * example, would have a type information structure that consumed
212 * writable memory in the size of 14 * sizeof (void *) (plus type
213 * string) This means that on 32bit systems, the cache entry for
214 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
217 * This means that in total, for our "a{sv}" example, 91 bytes of
218 * type information would be allocated.
221 * The type information cache, additionally, uses a #GHashTable to
222 * store and lookup the cached items and stores a pointer to this
223 * hash table in static storage. The hash table is freed when there
224 * are zero items in the type cache.
227 * Although these sizes may seem large it is important to remember
228 * that a program will probably only have a very small number of
229 * different types of values in it and that only one type information
230 * structure is required for many different values of the same type.
234 * <title>Buffer Management Memory</title>
236 * #GVariant uses an internal buffer management structure to deal
237 * with the various different possible sources of serialised data
238 * that it uses. The buffer is responsible for ensuring that the
239 * correct call is made when the data is no longer in use by
240 * #GVariant. This may involve a g_free() or a g_slice_free() or
241 * even g_mapped_file_unref().
244 * One buffer management structure is used for each chunk of
245 * serialised data. The size of the buffer management structure is 4
246 * * (void *). On 32bit systems, that's 16 bytes.
250 * <title>GVariant structure</title>
252 * The size of a #GVariant structure is 6 * (void *). On 32 bit
253 * systems, that's 24 bytes.
256 * #GVariant structures only exist if they are explicitly created
257 * with API calls. For example, if a #GVariant is constructed out of
258 * serialised data for the example given above (with the dictionary)
259 * then although there are 9 individual values that comprise the
260 * entire dictionary (two keys, two values, two variants containing
261 * the values, two dictionary entries, plus the dictionary itself),
262 * only 1 #GVariant instance exists -- the one referring to the
266 * If calls are made to start accessing the other values then
267 * #GVariant instances will exist for those values only for as long
268 * as they are in use (ie: until you call g_variant_unref()). The
269 * type information is shared. The serialised data and the buffer
270 * management structure for that serialised data is shared by the
275 * <title>Summary</title>
277 * To put the entire example together, for our dictionary mapping
278 * strings to variants (with two entries, as given above), we are
279 * using 91 bytes of memory for type information, 29 byes of memory
280 * for the serialised data, 16 bytes for buffer management and 24
281 * bytes for the #GVariant instance, or a total of 160 bytes, plus
282 * malloc overhead. If we were to use g_variant_get_child_value() to
283 * access the two dictionary entries, we would use an additional 48
284 * bytes. If we were to have other dictionaries of the same type, we
285 * would use more memory for the serialised data and buffer
286 * management for those dictionaries, but the type information would
293 /* definition of GVariant structure is in gvariant-core.c */
295 /* this is a g_return_val_if_fail() for making
296 * sure a (GVariant *) has the required type.
298 #define TYPE_CHECK(value, TYPE, val) \
299 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
300 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
301 "g_variant_is_of_type (" #value \
306 /* Numeric Type Constructor/Getters {{{1 */
308 * g_variant_new_from_trusted:
309 * @type: the #GVariantType
310 * @data: the data to use
311 * @size: the size of @data
313 * Constructs a new trusted #GVariant instance from the provided data.
314 * This is used to implement g_variant_new_* for all the basic types.
316 * Returns: a new floating #GVariant
319 g_variant_new_from_trusted (const GVariantType *type,
326 bytes = g_bytes_new (data, size);
327 value = g_variant_new_from_bytes (type, bytes, TRUE);
328 g_bytes_unref (bytes);
334 * g_variant_new_boolean:
335 * @value: a #gboolean value
337 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
339 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
344 g_variant_new_boolean (gboolean value)
348 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
352 * g_variant_get_boolean:
353 * @value: a boolean #GVariant instance
355 * Returns the boolean value of @value.
357 * It is an error to call this function with a @value of any type
358 * other than %G_VARIANT_TYPE_BOOLEAN.
360 * Returns: %TRUE or %FALSE
365 g_variant_get_boolean (GVariant *value)
369 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
371 data = g_variant_get_data (value);
373 return data != NULL ? *data != 0 : FALSE;
376 /* the constructors and accessors for byte, int{16,32,64}, handles and
377 * doubles all look pretty much exactly the same, so we reduce
380 #define NUMERIC_TYPE(TYPE, type, ctype) \
381 GVariant *g_variant_new_##type (ctype value) { \
382 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
383 &value, sizeof value); \
385 ctype g_variant_get_##type (GVariant *value) { \
387 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
388 data = g_variant_get_data (value); \
389 return data != NULL ? *data : 0; \
394 * g_variant_new_byte:
395 * @value: a #guint8 value
397 * Creates a new byte #GVariant instance.
399 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
404 * g_variant_get_byte:
405 * @value: a byte #GVariant instance
407 * Returns the byte value of @value.
409 * It is an error to call this function with a @value of any type
410 * other than %G_VARIANT_TYPE_BYTE.
416 NUMERIC_TYPE (BYTE, byte, guchar)
419 * g_variant_new_int16:
420 * @value: a #gint16 value
422 * Creates a new int16 #GVariant instance.
424 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
429 * g_variant_get_int16:
430 * @value: a int16 #GVariant instance
432 * Returns the 16-bit signed integer value of @value.
434 * It is an error to call this function with a @value of any type
435 * other than %G_VARIANT_TYPE_INT16.
441 NUMERIC_TYPE (INT16, int16, gint16)
444 * g_variant_new_uint16:
445 * @value: a #guint16 value
447 * Creates a new uint16 #GVariant instance.
449 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
454 * g_variant_get_uint16:
455 * @value: a uint16 #GVariant instance
457 * Returns the 16-bit unsigned integer value of @value.
459 * It is an error to call this function with a @value of any type
460 * other than %G_VARIANT_TYPE_UINT16.
462 * Returns: a #guint16
466 NUMERIC_TYPE (UINT16, uint16, guint16)
469 * g_variant_new_int32:
470 * @value: a #gint32 value
472 * Creates a new int32 #GVariant instance.
474 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
479 * g_variant_get_int32:
480 * @value: a int32 #GVariant instance
482 * Returns the 32-bit signed integer value of @value.
484 * It is an error to call this function with a @value of any type
485 * other than %G_VARIANT_TYPE_INT32.
491 NUMERIC_TYPE (INT32, int32, gint32)
494 * g_variant_new_uint32:
495 * @value: a #guint32 value
497 * Creates a new uint32 #GVariant instance.
499 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
504 * g_variant_get_uint32:
505 * @value: a uint32 #GVariant instance
507 * Returns the 32-bit unsigned integer value of @value.
509 * It is an error to call this function with a @value of any type
510 * other than %G_VARIANT_TYPE_UINT32.
512 * Returns: a #guint32
516 NUMERIC_TYPE (UINT32, uint32, guint32)
519 * g_variant_new_int64:
520 * @value: a #gint64 value
522 * Creates a new int64 #GVariant instance.
524 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
529 * g_variant_get_int64:
530 * @value: a int64 #GVariant instance
532 * Returns the 64-bit signed integer value of @value.
534 * It is an error to call this function with a @value of any type
535 * other than %G_VARIANT_TYPE_INT64.
541 NUMERIC_TYPE (INT64, int64, gint64)
544 * g_variant_new_uint64:
545 * @value: a #guint64 value
547 * Creates a new uint64 #GVariant instance.
549 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
554 * g_variant_get_uint64:
555 * @value: a uint64 #GVariant instance
557 * Returns the 64-bit unsigned integer value of @value.
559 * It is an error to call this function with a @value of any type
560 * other than %G_VARIANT_TYPE_UINT64.
562 * Returns: a #guint64
566 NUMERIC_TYPE (UINT64, uint64, guint64)
569 * g_variant_new_handle:
570 * @value: a #gint32 value
572 * Creates a new handle #GVariant instance.
574 * By convention, handles are indexes into an array of file descriptors
575 * that are sent alongside a D-Bus message. If you're not interacting
576 * with D-Bus, you probably don't need them.
578 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
583 * g_variant_get_handle:
584 * @value: a handle #GVariant instance
586 * Returns the 32-bit signed integer value of @value.
588 * It is an error to call this function with a @value of any type other
589 * than %G_VARIANT_TYPE_HANDLE.
591 * By convention, handles are indexes into an array of file descriptors
592 * that are sent alongside a D-Bus message. If you're not interacting
593 * with D-Bus, you probably don't need them.
599 NUMERIC_TYPE (HANDLE, handle, gint32)
602 * g_variant_new_double:
603 * @value: a #gdouble floating point value
605 * Creates a new double #GVariant instance.
607 * Returns: (transfer none): a floating reference to a new double #GVariant instance
612 * g_variant_get_double:
613 * @value: a double #GVariant instance
615 * Returns the double precision floating point value of @value.
617 * It is an error to call this function with a @value of any type
618 * other than %G_VARIANT_TYPE_DOUBLE.
620 * Returns: a #gdouble
624 NUMERIC_TYPE (DOUBLE, double, gdouble)
626 /* Container type Constructor / Deconstructors {{{1 */
628 * g_variant_new_maybe:
629 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
630 * @child: (allow-none): the child value, or %NULL
632 * Depending on if @child is %NULL, either wraps @child inside of a
633 * maybe container or creates a Nothing instance for the given @type.
635 * At least one of @child_type and @child must be non-%NULL.
636 * If @child_type is non-%NULL then it must be a definite type.
637 * If they are both non-%NULL then @child_type must be the type
640 * If @child is a floating reference (see g_variant_ref_sink()), the new
641 * instance takes ownership of @child.
643 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
648 g_variant_new_maybe (const GVariantType *child_type,
651 GVariantType *maybe_type;
654 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
656 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
657 g_return_val_if_fail (child_type == NULL || child == NULL ||
658 g_variant_is_of_type (child, child_type),
661 if (child_type == NULL)
662 child_type = g_variant_get_type (child);
664 maybe_type = g_variant_type_new_maybe (child_type);
671 children = g_new (GVariant *, 1);
672 children[0] = g_variant_ref_sink (child);
673 trusted = g_variant_is_trusted (children[0]);
675 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
678 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
680 g_variant_type_free (maybe_type);
686 * g_variant_get_maybe:
687 * @value: a maybe-typed value
689 * Given a maybe-typed #GVariant instance, extract its value. If the
690 * value is Nothing, then this function returns %NULL.
692 * Returns: (allow-none) (transfer full): the contents of @value, or %NULL
697 g_variant_get_maybe (GVariant *value)
699 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
701 if (g_variant_n_children (value))
702 return g_variant_get_child_value (value, 0);
708 * g_variant_new_variant: (constructor)
709 * @value: a #GVariant instance
711 * Boxes @value. The result is a #GVariant instance representing a
712 * variant containing the original value.
714 * If @child is a floating reference (see g_variant_ref_sink()), the new
715 * instance takes ownership of @child.
717 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
722 g_variant_new_variant (GVariant *value)
724 g_return_val_if_fail (value != NULL, NULL);
726 g_variant_ref_sink (value);
728 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
729 g_memdup (&value, sizeof value),
730 1, g_variant_is_trusted (value));
734 * g_variant_get_variant:
735 * @value: a variant #GVariant instance
737 * Unboxes @value. The result is the #GVariant instance that was
738 * contained in @value.
740 * Returns: (transfer full): the item contained in the variant
745 g_variant_get_variant (GVariant *value)
747 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
749 return g_variant_get_child_value (value, 0);
753 * g_variant_new_array:
754 * @child_type: (allow-none): the element type of the new array
755 * @children: (allow-none) (array length=n_children): an array of
756 * #GVariant pointers, the children
757 * @n_children: the length of @children
759 * Creates a new #GVariant array from @children.
761 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
762 * child type is determined by inspecting the first element of the
763 * @children array. If @child_type is non-%NULL then it must be a
766 * The items of the array are taken from the @children array. No entry
767 * in the @children array may be %NULL.
769 * All items in the array must have the same type, which must be the
770 * same as @child_type, if given.
772 * If the @children are floating references (see g_variant_ref_sink()), the
773 * new instance takes ownership of them as if via g_variant_ref_sink().
775 * Returns: (transfer none): a floating reference to a new #GVariant array
780 g_variant_new_array (const GVariantType *child_type,
781 GVariant * const *children,
784 GVariantType *array_type;
785 GVariant **my_children;
790 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
791 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
792 g_return_val_if_fail (child_type == NULL ||
793 g_variant_type_is_definite (child_type), NULL);
795 my_children = g_new (GVariant *, n_children);
798 if (child_type == NULL)
799 child_type = g_variant_get_type (children[0]);
800 array_type = g_variant_type_new_array (child_type);
802 for (i = 0; i < n_children; i++)
804 TYPE_CHECK (children[i], child_type, NULL);
805 my_children[i] = g_variant_ref_sink (children[i]);
806 trusted &= g_variant_is_trusted (children[i]);
809 value = g_variant_new_from_children (array_type, my_children,
810 n_children, trusted);
811 g_variant_type_free (array_type);
817 * g_variant_make_tuple_type:
818 * @children: (array length=n_children): an array of GVariant *
819 * @n_children: the length of @children
821 * Return the type of a tuple containing @children as its items.
823 static GVariantType *
824 g_variant_make_tuple_type (GVariant * const *children,
827 const GVariantType **types;
831 types = g_new (const GVariantType *, n_children);
833 for (i = 0; i < n_children; i++)
834 types[i] = g_variant_get_type (children[i]);
836 type = g_variant_type_new_tuple (types, n_children);
843 * g_variant_new_tuple:
844 * @children: (array length=n_children): the items to make the tuple out of
845 * @n_children: the length of @children
847 * Creates a new tuple #GVariant out of the items in @children. The
848 * type is determined from the types of @children. No entry in the
849 * @children array may be %NULL.
851 * If @n_children is 0 then the unit tuple is constructed.
853 * If the @children are floating references (see g_variant_ref_sink()), the
854 * new instance takes ownership of them as if via g_variant_ref_sink().
856 * Returns: (transfer none): a floating reference to a new #GVariant tuple
861 g_variant_new_tuple (GVariant * const *children,
864 GVariantType *tuple_type;
865 GVariant **my_children;
870 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
872 my_children = g_new (GVariant *, n_children);
875 for (i = 0; i < n_children; i++)
877 my_children[i] = g_variant_ref_sink (children[i]);
878 trusted &= g_variant_is_trusted (children[i]);
881 tuple_type = g_variant_make_tuple_type (children, n_children);
882 value = g_variant_new_from_children (tuple_type, my_children,
883 n_children, trusted);
884 g_variant_type_free (tuple_type);
890 * g_variant_make_dict_entry_type:
891 * @key: a #GVariant, the key
892 * @val: a #GVariant, the value
894 * Return the type of a dictionary entry containing @key and @val as its
897 static GVariantType *
898 g_variant_make_dict_entry_type (GVariant *key,
901 return g_variant_type_new_dict_entry (g_variant_get_type (key),
902 g_variant_get_type (val));
906 * g_variant_new_dict_entry: (constructor)
907 * @key: a basic #GVariant, the key
908 * @value: a #GVariant, the value
910 * Creates a new dictionary entry #GVariant. @key and @value must be
911 * non-%NULL. @key must be a value of a basic type (ie: not a container).
913 * If the @key or @value are floating references (see g_variant_ref_sink()),
914 * the new instance takes ownership of them as if via g_variant_ref_sink().
916 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
921 g_variant_new_dict_entry (GVariant *key,
924 GVariantType *dict_type;
928 g_return_val_if_fail (key != NULL && value != NULL, NULL);
929 g_return_val_if_fail (!g_variant_is_container (key), NULL);
931 children = g_new (GVariant *, 2);
932 children[0] = g_variant_ref_sink (key);
933 children[1] = g_variant_ref_sink (value);
934 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
936 dict_type = g_variant_make_dict_entry_type (key, value);
937 value = g_variant_new_from_children (dict_type, children, 2, trusted);
938 g_variant_type_free (dict_type);
944 * g_variant_lookup: (skip)
945 * @dictionary: a dictionary #GVariant
946 * @key: the key to lookup in the dictionary
947 * @format_string: a GVariant format string
948 * @...: the arguments to unpack the value into
950 * Looks up a value in a dictionary #GVariant.
952 * This function is a wrapper around g_variant_lookup_value() and
953 * g_variant_get(). In the case that %NULL would have been returned,
954 * this function returns %FALSE. Otherwise, it unpacks the returned
955 * value and returns %TRUE.
957 * @format_string determines the C types that are used for unpacking
958 * the values and also determines if the values are copied or borrowed,
960 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
962 * Returns: %TRUE if a value was unpacked
967 g_variant_lookup (GVariant *dictionary,
969 const gchar *format_string,
976 g_variant_get_data (dictionary);
978 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
979 value = g_variant_lookup_value (dictionary, key, type);
980 g_variant_type_free (type);
986 va_start (ap, format_string);
987 g_variant_get_va (value, format_string, NULL, &ap);
988 g_variant_unref (value);
999 * g_variant_lookup_value:
1000 * @dictionary: a dictionary #GVariant
1001 * @key: the key to lookup in the dictionary
1002 * @expected_type: (allow-none): a #GVariantType, or %NULL
1004 * Looks up a value in a dictionary #GVariant.
1006 * This function works with dictionaries of the type
1007 * <literal>a{s*}</literal> (and equally well with type
1008 * <literal>a{o*}</literal>, but we only further discuss the string case
1009 * for sake of clarity).
1011 * In the event that @dictionary has the type <literal>a{sv}</literal>,
1012 * the @expected_type string specifies what type of value is expected to
1013 * be inside of the variant. If the value inside the variant has a
1014 * different type then %NULL is returned. In the event that @dictionary
1015 * has a value type other than <literal>v</literal> then @expected_type
1016 * must directly match the key type and it is used to unpack the value
1017 * directly or an error occurs.
1019 * In either case, if @key is not found in @dictionary, %NULL is
1022 * If the key is found and the value has the correct type, it is
1023 * returned. If @expected_type was specified then any non-%NULL return
1024 * value will have this type.
1026 * Returns: (transfer full): the value of the dictionary key, or %NULL
1031 g_variant_lookup_value (GVariant *dictionary,
1033 const GVariantType *expected_type)
1039 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1040 G_VARIANT_TYPE ("a{s*}")) ||
1041 g_variant_is_of_type (dictionary,
1042 G_VARIANT_TYPE ("a{o*}")),
1045 g_variant_iter_init (&iter, dictionary);
1047 while ((entry = g_variant_iter_next_value (&iter)))
1049 GVariant *entry_key;
1052 entry_key = g_variant_get_child_value (entry, 0);
1053 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1054 g_variant_unref (entry_key);
1059 g_variant_unref (entry);
1065 value = g_variant_get_child_value (entry, 1);
1066 g_variant_unref (entry);
1068 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1072 tmp = g_variant_get_variant (value);
1073 g_variant_unref (value);
1075 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1077 g_variant_unref (tmp);
1084 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1085 g_variant_is_of_type (value, expected_type), NULL);
1091 * g_variant_get_fixed_array:
1092 * @value: a #GVariant array with fixed-sized elements
1093 * @n_elements: (out): a pointer to the location to store the number of items
1094 * @element_size: the size of each element
1096 * Provides access to the serialised data for an array of fixed-sized
1099 * @value must be an array with fixed-sized elements. Numeric types are
1100 * fixed-size, as are tuples containing only other fixed-sized types.
1102 * @element_size must be the size of a single element in the array,
1103 * as given by the section on
1104 * <link linkend='gvariant-serialised-data-memory'>Serialised Data
1107 * In particular, arrays of these fixed-sized types can be interpreted
1108 * as an array of the given C type, with @element_size set to
1109 * <code>sizeof</code> the appropriate type:
1113 * <thead><row><entry>element type</entry> <entry>C type</entry></row></thead>
1115 * <row><entry>%G_VARIANT_TYPE_INT16 (etc.)</entry>
1116 * <entry>#gint16 (etc.)</entry></row>
1117 * <row><entry>%G_VARIANT_TYPE_BOOLEAN</entry>
1118 * <entry>#guchar (not #gboolean!)</entry></row>
1119 * <row><entry>%G_VARIANT_TYPE_BYTE</entry> <entry>#guchar</entry></row>
1120 * <row><entry>%G_VARIANT_TYPE_HANDLE</entry> <entry>#guint32</entry></row>
1121 * <row><entry>%G_VARIANT_TYPE_DOUBLE</entry> <entry>#gdouble</entry></row>
1126 * For example, if calling this function for an array of 32 bit integers,
1127 * you might say <code>sizeof (gint32)</code>. This value isn't used
1128 * except for the purpose of a double-check that the form of the
1129 * serialised data matches the caller's expectation.
1131 * @n_elements, which must be non-%NULL is set equal to the number of
1132 * items in the array.
1134 * Returns: (array length=n_elements) (transfer none): a pointer to
1140 g_variant_get_fixed_array (GVariant *value,
1144 GVariantTypeInfo *array_info;
1145 gsize array_element_size;
1149 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1151 g_return_val_if_fail (n_elements != NULL, NULL);
1152 g_return_val_if_fail (element_size > 0, NULL);
1154 array_info = g_variant_get_type_info (value);
1155 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1157 g_return_val_if_fail (array_element_size, NULL);
1159 if G_UNLIKELY (array_element_size != element_size)
1161 if (array_element_size)
1162 g_critical ("g_variant_get_fixed_array: assertion "
1163 "'g_variant_array_has_fixed_size (value, element_size)' "
1164 "failed: array size %"G_GSIZE_FORMAT" does not match "
1165 "given element_size %"G_GSIZE_FORMAT".",
1166 array_element_size, element_size);
1168 g_critical ("g_variant_get_fixed_array: assertion "
1169 "'g_variant_array_has_fixed_size (value, element_size)' "
1170 "failed: array does not have fixed size.");
1173 data = g_variant_get_data (value);
1174 size = g_variant_get_size (value);
1176 if (size % element_size)
1179 *n_elements = size / element_size;
1188 * g_variant_new_fixed_array:
1189 * @element_type: the #GVariantType of each element
1190 * @elements: a pointer to the fixed array of contiguous elements
1191 * @n_elements: the number of elements
1192 * @element_size: the size of each element
1194 * Provides access to the serialised data for an array of fixed-sized
1197 * @value must be an array with fixed-sized elements. Numeric types are
1198 * fixed-size as are tuples containing only other fixed-sized types.
1200 * @element_size must be the size of a single element in the array. For
1201 * example, if calling this function for an array of 32 bit integers,
1202 * you might say <code>sizeof (gint32)</code>. This value isn't used
1203 * except for the purpose of a double-check that the form of the
1204 * serialised data matches the caller's expectation.
1206 * @n_elements, which must be non-%NULL is set equal to the number of
1207 * items in the array.
1209 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1214 g_variant_new_fixed_array (const GVariantType *element_type,
1215 gconstpointer elements,
1219 GVariantType *array_type;
1220 gsize array_element_size;
1221 GVariantTypeInfo *array_info;
1225 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1226 g_return_val_if_fail (element_size > 0, NULL);
1228 array_type = g_variant_type_new_array (element_type);
1229 array_info = g_variant_type_info_get (array_type);
1230 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1231 if G_UNLIKELY (array_element_size != element_size)
1233 if (array_element_size)
1234 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1235 " does not match given element_size %" G_GSIZE_FORMAT ".",
1236 array_element_size, element_size);
1238 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1242 data = g_memdup (elements, n_elements * element_size);
1243 value = g_variant_new_from_data (array_type, data,
1244 n_elements * element_size,
1245 FALSE, g_free, data);
1247 g_variant_type_free (array_type);
1248 g_variant_type_info_unref (array_info);
1253 /* String type constructor/getters/validation {{{1 */
1255 * g_variant_new_string:
1256 * @string: a normal utf8 nul-terminated string
1258 * Creates a string #GVariant with the contents of @string.
1260 * @string must be valid utf8.
1262 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1267 g_variant_new_string (const gchar *string)
1269 g_return_val_if_fail (string != NULL, NULL);
1270 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1272 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1273 string, strlen (string) + 1);
1277 * g_variant_new_take_string: (skip)
1278 * @string: a normal utf8 nul-terminated string
1280 * Creates a string #GVariant with the contents of @string.
1282 * @string must be valid utf8.
1284 * This function consumes @string. g_free() will be called on @string
1285 * when it is no longer required.
1287 * You must not modify or access @string in any other way after passing
1288 * it to this function. It is even possible that @string is immediately
1291 * Returns: (transfer none): a floating reference to a new string
1292 * #GVariant instance
1297 g_variant_new_take_string (gchar *string)
1302 g_return_val_if_fail (string != NULL, NULL);
1303 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1305 bytes = g_bytes_new_take (string, strlen (string) + 1);
1306 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1307 g_bytes_unref (bytes);
1313 * g_variant_new_printf: (skip)
1314 * @format_string: a printf-style format string
1315 * @...: arguments for @format_string
1317 * Creates a string-type GVariant using printf formatting.
1319 * This is similar to calling g_strdup_printf() and then
1320 * g_variant_new_string() but it saves a temporary variable and an
1323 * Returns: (transfer none): a floating reference to a new string
1324 * #GVariant instance
1329 g_variant_new_printf (const gchar *format_string,
1337 g_return_val_if_fail (format_string != NULL, NULL);
1339 va_start (ap, format_string);
1340 string = g_strdup_vprintf (format_string, ap);
1343 bytes = g_bytes_new_take (string, strlen (string) + 1);
1344 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1345 g_bytes_unref (bytes);
1351 * g_variant_new_object_path:
1352 * @object_path: a normal C nul-terminated string
1354 * Creates a D-Bus object path #GVariant with the contents of @string.
1355 * @string must be a valid D-Bus object path. Use
1356 * g_variant_is_object_path() if you're not sure.
1358 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1363 g_variant_new_object_path (const gchar *object_path)
1365 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1367 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1368 object_path, strlen (object_path) + 1);
1372 * g_variant_is_object_path:
1373 * @string: a normal C nul-terminated string
1375 * Determines if a given string is a valid D-Bus object path. You
1376 * should ensure that a string is a valid D-Bus object path before
1377 * passing it to g_variant_new_object_path().
1379 * A valid object path starts with '/' followed by zero or more
1380 * sequences of characters separated by '/' characters. Each sequence
1381 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1382 * (including the one following the final '/' character) may be empty.
1384 * Returns: %TRUE if @string is a D-Bus object path
1389 g_variant_is_object_path (const gchar *string)
1391 g_return_val_if_fail (string != NULL, FALSE);
1393 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1397 * g_variant_new_signature:
1398 * @signature: a normal C nul-terminated string
1400 * Creates a D-Bus type signature #GVariant with the contents of
1401 * @string. @string must be a valid D-Bus type signature. Use
1402 * g_variant_is_signature() if you're not sure.
1404 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1409 g_variant_new_signature (const gchar *signature)
1411 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1413 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1414 signature, strlen (signature) + 1);
1418 * g_variant_is_signature:
1419 * @string: a normal C nul-terminated string
1421 * Determines if a given string is a valid D-Bus type signature. You
1422 * should ensure that a string is a valid D-Bus type signature before
1423 * passing it to g_variant_new_signature().
1425 * D-Bus type signatures consist of zero or more definite #GVariantType
1426 * strings in sequence.
1428 * Returns: %TRUE if @string is a D-Bus type signature
1433 g_variant_is_signature (const gchar *string)
1435 g_return_val_if_fail (string != NULL, FALSE);
1437 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1441 * g_variant_get_string:
1442 * @value: a string #GVariant instance
1443 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1444 * to store the length
1446 * Returns the string value of a #GVariant instance with a string
1447 * type. This includes the types %G_VARIANT_TYPE_STRING,
1448 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1450 * The string will always be utf8 encoded.
1452 * If @length is non-%NULL then the length of the string (in bytes) is
1453 * returned there. For trusted values, this information is already
1454 * known. For untrusted values, a strlen() will be performed.
1456 * It is an error to call this function with a @value of any type
1457 * other than those three.
1459 * The return value remains valid as long as @value exists.
1461 * Returns: (transfer none): the constant string, utf8 encoded
1466 g_variant_get_string (GVariant *value,
1472 g_return_val_if_fail (value != NULL, NULL);
1473 g_return_val_if_fail (
1474 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1475 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1476 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1478 data = g_variant_get_data (value);
1479 size = g_variant_get_size (value);
1481 if (!g_variant_is_trusted (value))
1483 switch (g_variant_classify (value))
1485 case G_VARIANT_CLASS_STRING:
1486 if (g_variant_serialiser_is_string (data, size))
1493 case G_VARIANT_CLASS_OBJECT_PATH:
1494 if (g_variant_serialiser_is_object_path (data, size))
1501 case G_VARIANT_CLASS_SIGNATURE:
1502 if (g_variant_serialiser_is_signature (data, size))
1510 g_assert_not_reached ();
1521 * g_variant_dup_string:
1522 * @value: a string #GVariant instance
1523 * @length: (out): a pointer to a #gsize, to store the length
1525 * Similar to g_variant_get_string() except that instead of returning
1526 * a constant string, the string is duplicated.
1528 * The string will always be utf8 encoded.
1530 * The return value must be freed using g_free().
1532 * Returns: (transfer full): a newly allocated string, utf8 encoded
1537 g_variant_dup_string (GVariant *value,
1540 return g_strdup (g_variant_get_string (value, length));
1544 * g_variant_new_strv:
1545 * @strv: (array length=length) (element-type utf8): an array of strings
1546 * @length: the length of @strv, or -1
1548 * Constructs an array of strings #GVariant from the given array of
1551 * If @length is -1 then @strv is %NULL-terminated.
1553 * Returns: (transfer none): a new floating #GVariant instance
1558 g_variant_new_strv (const gchar * const *strv,
1564 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1567 length = g_strv_length ((gchar **) strv);
1569 strings = g_new (GVariant *, length);
1570 for (i = 0; i < length; i++)
1571 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1573 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1574 strings, length, TRUE);
1578 * g_variant_get_strv:
1579 * @value: an array of strings #GVariant
1580 * @length: (out) (allow-none): the length of the result, or %NULL
1582 * Gets the contents of an array of strings #GVariant. This call
1583 * makes a shallow copy; the return result should be released with
1584 * g_free(), but the individual strings must not be modified.
1586 * If @length is non-%NULL then the number of elements in the result
1587 * is stored there. In any case, the resulting array will be
1590 * For an empty array, @length will be set to 0 and a pointer to a
1591 * %NULL pointer will be returned.
1593 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1598 g_variant_get_strv (GVariant *value,
1605 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1607 g_variant_get_data (value);
1608 n = g_variant_n_children (value);
1609 strv = g_new (const gchar *, n + 1);
1611 for (i = 0; i < n; i++)
1615 string = g_variant_get_child_value (value, i);
1616 strv[i] = g_variant_get_string (string, NULL);
1617 g_variant_unref (string);
1628 * g_variant_dup_strv:
1629 * @value: an array of strings #GVariant
1630 * @length: (out) (allow-none): the length of the result, or %NULL
1632 * Gets the contents of an array of strings #GVariant. This call
1633 * makes a deep copy; the return result should be released with
1636 * If @length is non-%NULL then the number of elements in the result
1637 * is stored there. In any case, the resulting array will be
1640 * For an empty array, @length will be set to 0 and a pointer to a
1641 * %NULL pointer will be returned.
1643 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1648 g_variant_dup_strv (GVariant *value,
1655 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1657 n = g_variant_n_children (value);
1658 strv = g_new (gchar *, n + 1);
1660 for (i = 0; i < n; i++)
1664 string = g_variant_get_child_value (value, i);
1665 strv[i] = g_variant_dup_string (string, NULL);
1666 g_variant_unref (string);
1677 * g_variant_new_objv:
1678 * @strv: (array length=length) (element-type utf8): an array of strings
1679 * @length: the length of @strv, or -1
1681 * Constructs an array of object paths #GVariant from the given array of
1684 * Each string must be a valid #GVariant object path; see
1685 * g_variant_is_object_path().
1687 * If @length is -1 then @strv is %NULL-terminated.
1689 * Returns: (transfer none): a new floating #GVariant instance
1694 g_variant_new_objv (const gchar * const *strv,
1700 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1703 length = g_strv_length ((gchar **) strv);
1705 strings = g_new (GVariant *, length);
1706 for (i = 0; i < length; i++)
1707 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1709 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1710 strings, length, TRUE);
1714 * g_variant_get_objv:
1715 * @value: an array of object paths #GVariant
1716 * @length: (out) (allow-none): the length of the result, or %NULL
1718 * Gets the contents of an array of object paths #GVariant. This call
1719 * makes a shallow copy; the return result should be released with
1720 * g_free(), but the individual strings must not be modified.
1722 * If @length is non-%NULL then the number of elements in the result
1723 * is stored there. In any case, the resulting array will be
1726 * For an empty array, @length will be set to 0 and a pointer to a
1727 * %NULL pointer will be returned.
1729 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1734 g_variant_get_objv (GVariant *value,
1741 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1743 g_variant_get_data (value);
1744 n = g_variant_n_children (value);
1745 strv = g_new (const gchar *, n + 1);
1747 for (i = 0; i < n; i++)
1751 string = g_variant_get_child_value (value, i);
1752 strv[i] = g_variant_get_string (string, NULL);
1753 g_variant_unref (string);
1764 * g_variant_dup_objv:
1765 * @value: an array of object paths #GVariant
1766 * @length: (out) (allow-none): the length of the result, or %NULL
1768 * Gets the contents of an array of object paths #GVariant. This call
1769 * makes a deep copy; the return result should be released with
1772 * If @length is non-%NULL then the number of elements in the result
1773 * is stored there. In any case, the resulting array will be
1776 * For an empty array, @length will be set to 0 and a pointer to a
1777 * %NULL pointer will be returned.
1779 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1784 g_variant_dup_objv (GVariant *value,
1791 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1793 n = g_variant_n_children (value);
1794 strv = g_new (gchar *, n + 1);
1796 for (i = 0; i < n; i++)
1800 string = g_variant_get_child_value (value, i);
1801 strv[i] = g_variant_dup_string (string, NULL);
1802 g_variant_unref (string);
1814 * g_variant_new_bytestring:
1815 * @string: (array zero-terminated=1) (element-type guint8): a normal
1816 * nul-terminated string in no particular encoding
1818 * Creates an array-of-bytes #GVariant with the contents of @string.
1819 * This function is just like g_variant_new_string() except that the
1820 * string need not be valid utf8.
1822 * The nul terminator character at the end of the string is stored in
1825 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1830 g_variant_new_bytestring (const gchar *string)
1832 g_return_val_if_fail (string != NULL, NULL);
1834 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1835 string, strlen (string) + 1);
1839 * g_variant_get_bytestring:
1840 * @value: an array-of-bytes #GVariant instance
1842 * Returns the string value of a #GVariant instance with an
1843 * array-of-bytes type. The string has no particular encoding.
1845 * If the array does not end with a nul terminator character, the empty
1846 * string is returned. For this reason, you can always trust that a
1847 * non-%NULL nul-terminated string will be returned by this function.
1849 * If the array contains a nul terminator character somewhere other than
1850 * the last byte then the returned string is the string, up to the first
1851 * such nul character.
1853 * It is an error to call this function with a @value that is not an
1856 * The return value remains valid as long as @value exists.
1858 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1859 * the constant string
1864 g_variant_get_bytestring (GVariant *value)
1866 const gchar *string;
1869 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1871 /* Won't be NULL since this is an array type */
1872 string = g_variant_get_data (value);
1873 size = g_variant_get_size (value);
1875 if (size && string[size - 1] == '\0')
1882 * g_variant_dup_bytestring:
1883 * @value: an array-of-bytes #GVariant instance
1884 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1885 * the length (not including the nul terminator)
1887 * Similar to g_variant_get_bytestring() except that instead of
1888 * returning a constant string, the string is duplicated.
1890 * The return value must be freed using g_free().
1892 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1893 * a newly allocated string
1898 g_variant_dup_bytestring (GVariant *value,
1901 const gchar *original = g_variant_get_bytestring (value);
1904 /* don't crash in case get_bytestring() had an assert failure */
1905 if (original == NULL)
1908 size = strlen (original);
1913 return g_memdup (original, size + 1);
1917 * g_variant_new_bytestring_array:
1918 * @strv: (array length=length): an array of strings
1919 * @length: the length of @strv, or -1
1921 * Constructs an array of bytestring #GVariant from the given array of
1924 * If @length is -1 then @strv is %NULL-terminated.
1926 * Returns: (transfer none): a new floating #GVariant instance
1931 g_variant_new_bytestring_array (const gchar * const *strv,
1937 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1940 length = g_strv_length ((gchar **) strv);
1942 strings = g_new (GVariant *, length);
1943 for (i = 0; i < length; i++)
1944 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1946 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1947 strings, length, TRUE);
1951 * g_variant_get_bytestring_array:
1952 * @value: an array of array of bytes #GVariant ('aay')
1953 * @length: (out) (allow-none): the length of the result, or %NULL
1955 * Gets the contents of an array of array of bytes #GVariant. This call
1956 * makes a shallow copy; the return result should be released with
1957 * g_free(), but the individual strings must not be modified.
1959 * If @length is non-%NULL then the number of elements in the result is
1960 * stored there. In any case, the resulting array will be
1963 * For an empty array, @length will be set to 0 and a pointer to a
1964 * %NULL pointer will be returned.
1966 * Returns: (array length=length) (transfer container): an array of constant strings
1971 g_variant_get_bytestring_array (GVariant *value,
1978 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1980 g_variant_get_data (value);
1981 n = g_variant_n_children (value);
1982 strv = g_new (const gchar *, n + 1);
1984 for (i = 0; i < n; i++)
1988 string = g_variant_get_child_value (value, i);
1989 strv[i] = g_variant_get_bytestring (string);
1990 g_variant_unref (string);
2001 * g_variant_dup_bytestring_array:
2002 * @value: an array of array of bytes #GVariant ('aay')
2003 * @length: (out) (allow-none): the length of the result, or %NULL
2005 * Gets the contents of an array of array of bytes #GVariant. This call
2006 * makes a deep copy; the return result should be released with
2009 * If @length is non-%NULL then the number of elements in the result is
2010 * stored there. In any case, the resulting array will be
2013 * For an empty array, @length will be set to 0 and a pointer to a
2014 * %NULL pointer will be returned.
2016 * Returns: (array length=length) (transfer full): an array of strings
2021 g_variant_dup_bytestring_array (GVariant *value,
2028 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2030 g_variant_get_data (value);
2031 n = g_variant_n_children (value);
2032 strv = g_new (gchar *, n + 1);
2034 for (i = 0; i < n; i++)
2038 string = g_variant_get_child_value (value, i);
2039 strv[i] = g_variant_dup_bytestring (string, NULL);
2040 g_variant_unref (string);
2050 /* Type checking and querying {{{1 */
2052 * g_variant_get_type:
2053 * @value: a #GVariant
2055 * Determines the type of @value.
2057 * The return value is valid for the lifetime of @value and must not
2060 * Returns: a #GVariantType
2064 const GVariantType *
2065 g_variant_get_type (GVariant *value)
2067 GVariantTypeInfo *type_info;
2069 g_return_val_if_fail (value != NULL, NULL);
2071 type_info = g_variant_get_type_info (value);
2073 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2077 * g_variant_get_type_string:
2078 * @value: a #GVariant
2080 * Returns the type string of @value. Unlike the result of calling
2081 * g_variant_type_peek_string(), this string is nul-terminated. This
2082 * string belongs to #GVariant and must not be freed.
2084 * Returns: the type string for the type of @value
2089 g_variant_get_type_string (GVariant *value)
2091 GVariantTypeInfo *type_info;
2093 g_return_val_if_fail (value != NULL, NULL);
2095 type_info = g_variant_get_type_info (value);
2097 return g_variant_type_info_get_type_string (type_info);
2101 * g_variant_is_of_type:
2102 * @value: a #GVariant instance
2103 * @type: a #GVariantType
2105 * Checks if a value has a type matching the provided type.
2107 * Returns: %TRUE if the type of @value matches @type
2112 g_variant_is_of_type (GVariant *value,
2113 const GVariantType *type)
2115 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2119 * g_variant_is_container:
2120 * @value: a #GVariant instance
2122 * Checks if @value is a container.
2124 * Returns: %TRUE if @value is a container
2129 g_variant_is_container (GVariant *value)
2131 return g_variant_type_is_container (g_variant_get_type (value));
2136 * g_variant_classify:
2137 * @value: a #GVariant
2139 * Classifies @value according to its top-level type.
2141 * Returns: the #GVariantClass of @value
2147 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2148 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2149 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2150 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2151 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2152 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2153 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2154 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2155 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2156 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2158 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2159 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2161 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2162 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2163 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2164 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2165 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2166 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2168 * The range of possible top-level types of #GVariant instances.
2173 g_variant_classify (GVariant *value)
2175 g_return_val_if_fail (value != NULL, 0);
2177 return *g_variant_get_type_string (value);
2180 /* Pretty printer {{{1 */
2181 /* This function is not introspectable because if @string is NULL,
2182 @returns is (transfer full), otherwise it is (transfer none), which
2183 is not supported by GObjectIntrospection */
2185 * g_variant_print_string: (skip)
2186 * @value: a #GVariant
2187 * @string: (allow-none) (default NULL): a #GString, or %NULL
2188 * @type_annotate: %TRUE if type information should be included in
2191 * Behaves as g_variant_print(), but operates on a #GString.
2193 * If @string is non-%NULL then it is appended to and returned. Else,
2194 * a new empty #GString is allocated and it is returned.
2196 * Returns: a #GString containing the string
2201 g_variant_print_string (GVariant *value,
2203 gboolean type_annotate)
2205 if G_UNLIKELY (string == NULL)
2206 string = g_string_new (NULL);
2208 switch (g_variant_classify (value))
2210 case G_VARIANT_CLASS_MAYBE:
2212 g_string_append_printf (string, "@%s ",
2213 g_variant_get_type_string (value));
2215 if (g_variant_n_children (value))
2217 gchar *printed_child;
2222 * Consider the case of the type "mmi". In this case we could
2223 * write "just just 4", but "4" alone is totally unambiguous,
2224 * so we try to drop "just" where possible.
2226 * We have to be careful not to always drop "just", though,
2227 * since "nothing" needs to be distinguishable from "just
2228 * nothing". The case where we need to ensure we keep the
2229 * "just" is actually exactly the case where we have a nested
2232 * Instead of searching for that nested Nothing, we just print
2233 * the contained value into a separate string and see if we
2234 * end up with "nothing" at the end of it. If so, we need to
2235 * add "just" at our level.
2237 element = g_variant_get_child_value (value, 0);
2238 printed_child = g_variant_print (element, FALSE);
2239 g_variant_unref (element);
2241 if (g_str_has_suffix (printed_child, "nothing"))
2242 g_string_append (string, "just ");
2243 g_string_append (string, printed_child);
2244 g_free (printed_child);
2247 g_string_append (string, "nothing");
2251 case G_VARIANT_CLASS_ARRAY:
2252 /* it's an array so the first character of the type string is 'a'
2254 * if the first two characters are 'ay' then it's a bytestring.
2255 * under certain conditions we print those as strings.
2257 if (g_variant_get_type_string (value)[1] == 'y')
2263 /* first determine if it is a byte string.
2264 * that's when there's a single nul character: at the end.
2266 str = g_variant_get_data (value);
2267 size = g_variant_get_size (value);
2269 for (i = 0; i < size; i++)
2273 /* first nul byte is the last byte -> it's a byte string. */
2276 gchar *escaped = g_strescape (str, NULL);
2278 /* use double quotes only if a ' is in the string */
2279 if (strchr (str, '\''))
2280 g_string_append_printf (string, "b\"%s\"", escaped);
2282 g_string_append_printf (string, "b'%s'", escaped);
2289 /* fall through and handle normally... */;
2293 * if the first two characters are 'a{' then it's an array of
2294 * dictionary entries (ie: a dictionary) so we print that
2297 if (g_variant_get_type_string (value)[1] == '{')
2300 const gchar *comma = "";
2303 if ((n = g_variant_n_children (value)) == 0)
2306 g_string_append_printf (string, "@%s ",
2307 g_variant_get_type_string (value));
2308 g_string_append (string, "{}");
2312 g_string_append_c (string, '{');
2313 for (i = 0; i < n; i++)
2315 GVariant *entry, *key, *val;
2317 g_string_append (string, comma);
2320 entry = g_variant_get_child_value (value, i);
2321 key = g_variant_get_child_value (entry, 0);
2322 val = g_variant_get_child_value (entry, 1);
2323 g_variant_unref (entry);
2325 g_variant_print_string (key, string, type_annotate);
2326 g_variant_unref (key);
2327 g_string_append (string, ": ");
2328 g_variant_print_string (val, string, type_annotate);
2329 g_variant_unref (val);
2330 type_annotate = FALSE;
2332 g_string_append_c (string, '}');
2335 /* normal (non-dictionary) array */
2337 const gchar *comma = "";
2340 if ((n = g_variant_n_children (value)) == 0)
2343 g_string_append_printf (string, "@%s ",
2344 g_variant_get_type_string (value));
2345 g_string_append (string, "[]");
2349 g_string_append_c (string, '[');
2350 for (i = 0; i < n; i++)
2354 g_string_append (string, comma);
2357 element = g_variant_get_child_value (value, i);
2359 g_variant_print_string (element, string, type_annotate);
2360 g_variant_unref (element);
2361 type_annotate = FALSE;
2363 g_string_append_c (string, ']');
2368 case G_VARIANT_CLASS_TUPLE:
2372 n = g_variant_n_children (value);
2374 g_string_append_c (string, '(');
2375 for (i = 0; i < n; i++)
2379 element = g_variant_get_child_value (value, i);
2380 g_variant_print_string (element, string, type_annotate);
2381 g_string_append (string, ", ");
2382 g_variant_unref (element);
2385 /* for >1 item: remove final ", "
2386 * for 1 item: remove final " ", but leave the ","
2387 * for 0 items: there is only "(", so remove nothing
2389 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2390 g_string_append_c (string, ')');
2394 case G_VARIANT_CLASS_DICT_ENTRY:
2398 g_string_append_c (string, '{');
2400 element = g_variant_get_child_value (value, 0);
2401 g_variant_print_string (element, string, type_annotate);
2402 g_variant_unref (element);
2404 g_string_append (string, ", ");
2406 element = g_variant_get_child_value (value, 1);
2407 g_variant_print_string (element, string, type_annotate);
2408 g_variant_unref (element);
2410 g_string_append_c (string, '}');
2414 case G_VARIANT_CLASS_VARIANT:
2416 GVariant *child = g_variant_get_variant (value);
2418 /* Always annotate types in nested variants, because they are
2419 * (by nature) of variable type.
2421 g_string_append_c (string, '<');
2422 g_variant_print_string (child, string, TRUE);
2423 g_string_append_c (string, '>');
2425 g_variant_unref (child);
2429 case G_VARIANT_CLASS_BOOLEAN:
2430 if (g_variant_get_boolean (value))
2431 g_string_append (string, "true");
2433 g_string_append (string, "false");
2436 case G_VARIANT_CLASS_STRING:
2438 const gchar *str = g_variant_get_string (value, NULL);
2439 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2441 g_string_append_c (string, quote);
2445 gunichar c = g_utf8_get_char (str);
2447 if (c == quote || c == '\\')
2448 g_string_append_c (string, '\\');
2450 if (g_unichar_isprint (c))
2451 g_string_append_unichar (string, c);
2455 g_string_append_c (string, '\\');
2460 g_string_append_c (string, 'a');
2464 g_string_append_c (string, 'b');
2468 g_string_append_c (string, 'f');
2472 g_string_append_c (string, 'n');
2476 g_string_append_c (string, 'r');
2480 g_string_append_c (string, 't');
2484 g_string_append_c (string, 'v');
2488 g_string_append_printf (string, "u%04x", c);
2492 g_string_append_printf (string, "U%08x", c);
2495 str = g_utf8_next_char (str);
2498 g_string_append_c (string, quote);
2502 case G_VARIANT_CLASS_BYTE:
2504 g_string_append (string, "byte ");
2505 g_string_append_printf (string, "0x%02x",
2506 g_variant_get_byte (value));
2509 case G_VARIANT_CLASS_INT16:
2511 g_string_append (string, "int16 ");
2512 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2513 g_variant_get_int16 (value));
2516 case G_VARIANT_CLASS_UINT16:
2518 g_string_append (string, "uint16 ");
2519 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2520 g_variant_get_uint16 (value));
2523 case G_VARIANT_CLASS_INT32:
2524 /* Never annotate this type because it is the default for numbers
2525 * (and this is a *pretty* printer)
2527 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2528 g_variant_get_int32 (value));
2531 case G_VARIANT_CLASS_HANDLE:
2533 g_string_append (string, "handle ");
2534 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2535 g_variant_get_handle (value));
2538 case G_VARIANT_CLASS_UINT32:
2540 g_string_append (string, "uint32 ");
2541 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2542 g_variant_get_uint32 (value));
2545 case G_VARIANT_CLASS_INT64:
2547 g_string_append (string, "int64 ");
2548 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2549 g_variant_get_int64 (value));
2552 case G_VARIANT_CLASS_UINT64:
2554 g_string_append (string, "uint64 ");
2555 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2556 g_variant_get_uint64 (value));
2559 case G_VARIANT_CLASS_DOUBLE:
2564 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2566 for (i = 0; buffer[i]; i++)
2567 if (buffer[i] == '.' || buffer[i] == 'e' ||
2568 buffer[i] == 'n' || buffer[i] == 'N')
2571 /* if there is no '.' or 'e' in the float then add one */
2572 if (buffer[i] == '\0')
2579 g_string_append (string, buffer);
2583 case G_VARIANT_CLASS_OBJECT_PATH:
2585 g_string_append (string, "objectpath ");
2586 g_string_append_printf (string, "\'%s\'",
2587 g_variant_get_string (value, NULL));
2590 case G_VARIANT_CLASS_SIGNATURE:
2592 g_string_append (string, "signature ");
2593 g_string_append_printf (string, "\'%s\'",
2594 g_variant_get_string (value, NULL));
2598 g_assert_not_reached ();
2606 * @value: a #GVariant
2607 * @type_annotate: %TRUE if type information should be included in
2610 * Pretty-prints @value in the format understood by g_variant_parse().
2612 * The format is described <link linkend='gvariant-text'>here</link>.
2614 * If @type_annotate is %TRUE, then type information is included in
2617 * Returns: (transfer full): a newly-allocated string holding the result.
2622 g_variant_print (GVariant *value,
2623 gboolean type_annotate)
2625 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2629 /* Hash, Equal, Compare {{{1 */
2632 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2634 * Generates a hash value for a #GVariant instance.
2636 * The output of this function is guaranteed to be the same for a given
2637 * value only per-process. It may change between different processor
2638 * architectures or even different versions of GLib. Do not use this
2639 * function as a basis for building protocols or file formats.
2641 * The type of @value is #gconstpointer only to allow use of this
2642 * function with #GHashTable. @value must be a #GVariant.
2644 * Returns: a hash value corresponding to @value
2649 g_variant_hash (gconstpointer value_)
2651 GVariant *value = (GVariant *) value_;
2653 switch (g_variant_classify (value))
2655 case G_VARIANT_CLASS_STRING:
2656 case G_VARIANT_CLASS_OBJECT_PATH:
2657 case G_VARIANT_CLASS_SIGNATURE:
2658 return g_str_hash (g_variant_get_string (value, NULL));
2660 case G_VARIANT_CLASS_BOOLEAN:
2661 /* this is a very odd thing to hash... */
2662 return g_variant_get_boolean (value);
2664 case G_VARIANT_CLASS_BYTE:
2665 return g_variant_get_byte (value);
2667 case G_VARIANT_CLASS_INT16:
2668 case G_VARIANT_CLASS_UINT16:
2672 ptr = g_variant_get_data (value);
2680 case G_VARIANT_CLASS_INT32:
2681 case G_VARIANT_CLASS_UINT32:
2682 case G_VARIANT_CLASS_HANDLE:
2686 ptr = g_variant_get_data (value);
2694 case G_VARIANT_CLASS_INT64:
2695 case G_VARIANT_CLASS_UINT64:
2696 case G_VARIANT_CLASS_DOUBLE:
2697 /* need a separate case for these guys because otherwise
2698 * performance could be quite bad on big endian systems
2703 ptr = g_variant_get_data (value);
2706 return ptr[0] + ptr[1];
2712 g_return_val_if_fail (!g_variant_is_container (value), 0);
2713 g_assert_not_reached ();
2719 * @one: (type GVariant): a #GVariant instance
2720 * @two: (type GVariant): a #GVariant instance
2722 * Checks if @one and @two have the same type and value.
2724 * The types of @one and @two are #gconstpointer only to allow use of
2725 * this function with #GHashTable. They must each be a #GVariant.
2727 * Returns: %TRUE if @one and @two are equal
2732 g_variant_equal (gconstpointer one,
2737 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2739 if (g_variant_get_type_info ((GVariant *) one) !=
2740 g_variant_get_type_info ((GVariant *) two))
2743 /* if both values are trusted to be in their canonical serialised form
2744 * then a simple memcmp() of their serialised data will answer the
2747 * if not, then this might generate a false negative (since it is
2748 * possible for two different byte sequences to represent the same
2749 * value). for now we solve this by pretty-printing both values and
2750 * comparing the result.
2752 if (g_variant_is_trusted ((GVariant *) one) &&
2753 g_variant_is_trusted ((GVariant *) two))
2755 gconstpointer data_one, data_two;
2756 gsize size_one, size_two;
2758 size_one = g_variant_get_size ((GVariant *) one);
2759 size_two = g_variant_get_size ((GVariant *) two);
2761 if (size_one != size_two)
2764 data_one = g_variant_get_data ((GVariant *) one);
2765 data_two = g_variant_get_data ((GVariant *) two);
2767 equal = memcmp (data_one, data_two, size_one) == 0;
2771 gchar *strone, *strtwo;
2773 strone = g_variant_print ((GVariant *) one, FALSE);
2774 strtwo = g_variant_print ((GVariant *) two, FALSE);
2775 equal = strcmp (strone, strtwo) == 0;
2784 * g_variant_compare:
2785 * @one: (type GVariant): a basic-typed #GVariant instance
2786 * @two: (type GVariant): a #GVariant instance of the same type
2788 * Compares @one and @two.
2790 * The types of @one and @two are #gconstpointer only to allow use of
2791 * this function with #GTree, #GPtrArray, etc. They must each be a
2794 * Comparison is only defined for basic types (ie: booleans, numbers,
2795 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2796 * ordered in the usual way. Strings are in ASCII lexographical order.
2798 * It is a programmer error to attempt to compare container values or
2799 * two values that have types that are not exactly equal. For example,
2800 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2801 * integer. Also note that this function is not particularly
2802 * well-behaved when it comes to comparison of doubles; in particular,
2803 * the handling of incomparable values (ie: NaN) is undefined.
2805 * If you only require an equality comparison, g_variant_equal() is more
2808 * Returns: negative value if a < b;
2810 * positive value if a > b.
2815 g_variant_compare (gconstpointer one,
2818 GVariant *a = (GVariant *) one;
2819 GVariant *b = (GVariant *) two;
2821 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2823 switch (g_variant_classify (a))
2825 case G_VARIANT_CLASS_BOOLEAN:
2826 return g_variant_get_boolean (a) -
2827 g_variant_get_boolean (b);
2829 case G_VARIANT_CLASS_BYTE:
2830 return ((gint) g_variant_get_byte (a)) -
2831 ((gint) g_variant_get_byte (b));
2833 case G_VARIANT_CLASS_INT16:
2834 return ((gint) g_variant_get_int16 (a)) -
2835 ((gint) g_variant_get_int16 (b));
2837 case G_VARIANT_CLASS_UINT16:
2838 return ((gint) g_variant_get_uint16 (a)) -
2839 ((gint) g_variant_get_uint16 (b));
2841 case G_VARIANT_CLASS_INT32:
2843 gint32 a_val = g_variant_get_int32 (a);
2844 gint32 b_val = g_variant_get_int32 (b);
2846 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2849 case G_VARIANT_CLASS_UINT32:
2851 guint32 a_val = g_variant_get_uint32 (a);
2852 guint32 b_val = g_variant_get_uint32 (b);
2854 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2857 case G_VARIANT_CLASS_INT64:
2859 gint64 a_val = g_variant_get_int64 (a);
2860 gint64 b_val = g_variant_get_int64 (b);
2862 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2865 case G_VARIANT_CLASS_UINT64:
2867 guint64 a_val = g_variant_get_uint64 (a);
2868 guint64 b_val = g_variant_get_uint64 (b);
2870 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2873 case G_VARIANT_CLASS_DOUBLE:
2875 gdouble a_val = g_variant_get_double (a);
2876 gdouble b_val = g_variant_get_double (b);
2878 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2881 case G_VARIANT_CLASS_STRING:
2882 case G_VARIANT_CLASS_OBJECT_PATH:
2883 case G_VARIANT_CLASS_SIGNATURE:
2884 return strcmp (g_variant_get_string (a, NULL),
2885 g_variant_get_string (b, NULL));
2888 g_return_val_if_fail (!g_variant_is_container (a), 0);
2889 g_assert_not_reached ();
2893 /* GVariantIter {{{1 */
2895 * GVariantIter: (skip)
2897 * #GVariantIter is an opaque data structure and can only be accessed
2898 * using the following functions.
2905 const gchar *loop_format;
2911 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2915 struct stack_iter iter;
2917 GVariant *value_ref;
2921 #define GVSI(i) ((struct stack_iter *) (i))
2922 #define GVHI(i) ((struct heap_iter *) (i))
2923 #define GVSI_MAGIC ((gsize) 3579507750u)
2924 #define GVHI_MAGIC ((gsize) 1450270775u)
2925 #define is_valid_iter(i) (i != NULL && \
2926 GVSI(i)->magic == GVSI_MAGIC)
2927 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2931 * g_variant_iter_new:
2932 * @value: a container #GVariant
2934 * Creates a heap-allocated #GVariantIter for iterating over the items
2937 * Use g_variant_iter_free() to free the return value when you no longer
2940 * A reference is taken to @value and will be released only when
2941 * g_variant_iter_free() is called.
2943 * Returns: (transfer full): a new heap-allocated #GVariantIter
2948 g_variant_iter_new (GVariant *value)
2952 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2953 GVHI(iter)->value_ref = g_variant_ref (value);
2954 GVHI(iter)->magic = GVHI_MAGIC;
2956 g_variant_iter_init (iter, value);
2962 * g_variant_iter_init: (skip)
2963 * @iter: a pointer to a #GVariantIter
2964 * @value: a container #GVariant
2966 * Initialises (without allocating) a #GVariantIter. @iter may be
2967 * completely uninitialised prior to this call; its old value is
2970 * The iterator remains valid for as long as @value exists, and need not
2971 * be freed in any way.
2973 * Returns: the number of items in @value
2978 g_variant_iter_init (GVariantIter *iter,
2981 GVSI(iter)->magic = GVSI_MAGIC;
2982 GVSI(iter)->value = value;
2983 GVSI(iter)->n = g_variant_n_children (value);
2985 GVSI(iter)->loop_format = NULL;
2987 return GVSI(iter)->n;
2991 * g_variant_iter_copy:
2992 * @iter: a #GVariantIter
2994 * Creates a new heap-allocated #GVariantIter to iterate over the
2995 * container that was being iterated over by @iter. Iteration begins on
2996 * the new iterator from the current position of the old iterator but
2997 * the two copies are independent past that point.
2999 * Use g_variant_iter_free() to free the return value when you no longer
3002 * A reference is taken to the container that @iter is iterating over
3003 * and will be releated only when g_variant_iter_free() is called.
3005 * Returns: (transfer full): a new heap-allocated #GVariantIter
3010 g_variant_iter_copy (GVariantIter *iter)
3014 g_return_val_if_fail (is_valid_iter (iter), 0);
3016 copy = g_variant_iter_new (GVSI(iter)->value);
3017 GVSI(copy)->i = GVSI(iter)->i;
3023 * g_variant_iter_n_children:
3024 * @iter: a #GVariantIter
3026 * Queries the number of child items in the container that we are
3027 * iterating over. This is the total number of items -- not the number
3028 * of items remaining.
3030 * This function might be useful for preallocation of arrays.
3032 * Returns: the number of children in the container
3037 g_variant_iter_n_children (GVariantIter *iter)
3039 g_return_val_if_fail (is_valid_iter (iter), 0);
3041 return GVSI(iter)->n;
3045 * g_variant_iter_free:
3046 * @iter: (transfer full): a heap-allocated #GVariantIter
3048 * Frees a heap-allocated #GVariantIter. Only call this function on
3049 * iterators that were returned by g_variant_iter_new() or
3050 * g_variant_iter_copy().
3055 g_variant_iter_free (GVariantIter *iter)
3057 g_return_if_fail (is_valid_heap_iter (iter));
3059 g_variant_unref (GVHI(iter)->value_ref);
3060 GVHI(iter)->magic = 0;
3062 g_slice_free (struct heap_iter, GVHI(iter));
3066 * g_variant_iter_next_value:
3067 * @iter: a #GVariantIter
3069 * Gets the next item in the container. If no more items remain then
3070 * %NULL is returned.
3072 * Use g_variant_unref() to drop your reference on the return value when
3073 * you no longer need it.
3076 * <title>Iterating with g_variant_iter_next_value()</title>
3078 * /<!-- -->* recursively iterate a container *<!-- -->/
3080 * iterate_container_recursive (GVariant *container)
3082 * GVariantIter iter;
3085 * g_variant_iter_init (&iter, container);
3086 * while ((child = g_variant_iter_next_value (&iter)))
3088 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3090 * if (g_variant_is_container (child))
3091 * iterate_container_recursive (child);
3093 * g_variant_unref (child);
3099 * Returns: (allow-none) (transfer full): a #GVariant, or %NULL
3104 g_variant_iter_next_value (GVariantIter *iter)
3106 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3108 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3110 g_critical ("g_variant_iter_next_value: must not be called again "
3111 "after NULL has already been returned.");
3117 if (GVSI(iter)->i < GVSI(iter)->n)
3118 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3123 /* GVariantBuilder {{{1 */
3127 * A utility type for constructing container-type #GVariant instances.
3129 * This is an opaque structure and may only be accessed using the
3130 * following functions.
3132 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3133 * access it from more than one thread.
3136 struct stack_builder
3138 GVariantBuilder *parent;
3141 /* type constraint explicitly specified by 'type'.
3142 * for tuple types, this moves along as we add more items.
3144 const GVariantType *expected_type;
3146 /* type constraint implied by previous array item.
3148 const GVariantType *prev_item_type;
3150 /* constraints on the number of children. max = -1 for unlimited. */
3154 /* dynamically-growing pointer array */
3155 GVariant **children;
3156 gsize allocated_children;
3159 /* set to '1' if all items in the container will have the same type
3160 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3162 guint uniform_item_types : 1;
3164 /* set to '1' initially and changed to '0' if an untrusted value is
3172 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3176 GVariantBuilder builder;
3182 #define GVSB(b) ((struct stack_builder *) (b))
3183 #define GVHB(b) ((struct heap_builder *) (b))
3184 #define GVSB_MAGIC ((gsize) 1033660112u)
3185 #define GVHB_MAGIC ((gsize) 3087242682u)
3186 #define is_valid_builder(b) (b != NULL && \
3187 GVSB(b)->magic == GVSB_MAGIC)
3188 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3191 * g_variant_builder_new:
3192 * @type: a container type
3194 * Allocates and initialises a new #GVariantBuilder.
3196 * You should call g_variant_builder_unref() on the return value when it
3197 * is no longer needed. The memory will not be automatically freed by
3200 * In most cases it is easier to place a #GVariantBuilder directly on
3201 * the stack of the calling function and initialise it with
3202 * g_variant_builder_init().
3204 * Returns: (transfer full): a #GVariantBuilder
3209 g_variant_builder_new (const GVariantType *type)
3211 GVariantBuilder *builder;
3213 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3214 g_variant_builder_init (builder, type);
3215 GVHB(builder)->magic = GVHB_MAGIC;
3216 GVHB(builder)->ref_count = 1;
3222 * g_variant_builder_unref:
3223 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3225 * Decreases the reference count on @builder.
3227 * In the event that there are no more references, releases all memory
3228 * associated with the #GVariantBuilder.
3230 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3231 * things will happen.
3236 g_variant_builder_unref (GVariantBuilder *builder)
3238 g_return_if_fail (is_valid_heap_builder (builder));
3240 if (--GVHB(builder)->ref_count)
3243 g_variant_builder_clear (builder);
3244 GVHB(builder)->magic = 0;
3246 g_slice_free (struct heap_builder, GVHB(builder));
3250 * g_variant_builder_ref:
3251 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3253 * Increases the reference count on @builder.
3255 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3256 * things will happen.
3258 * Returns: (transfer full): a new reference to @builder
3263 g_variant_builder_ref (GVariantBuilder *builder)
3265 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3267 GVHB(builder)->ref_count++;
3273 * g_variant_builder_clear: (skip)
3274 * @builder: a #GVariantBuilder
3276 * Releases all memory associated with a #GVariantBuilder without
3277 * freeing the #GVariantBuilder structure itself.
3279 * It typically only makes sense to do this on a stack-allocated
3280 * #GVariantBuilder if you want to abort building the value part-way
3281 * through. This function need not be called if you call
3282 * g_variant_builder_end() and it also doesn't need to be called on
3283 * builders allocated with g_variant_builder_new (see
3284 * g_variant_builder_unref() for that).
3286 * This function leaves the #GVariantBuilder structure set to all-zeros.
3287 * It is valid to call this function on either an initialised
3288 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3289 * to call this function on uninitialised memory.
3294 g_variant_builder_clear (GVariantBuilder *builder)
3298 if (GVSB(builder)->magic == 0)
3299 /* all-zeros case */
3302 g_return_if_fail (is_valid_builder (builder));
3304 g_variant_type_free (GVSB(builder)->type);
3306 for (i = 0; i < GVSB(builder)->offset; i++)
3307 g_variant_unref (GVSB(builder)->children[i]);
3309 g_free (GVSB(builder)->children);
3311 if (GVSB(builder)->parent)
3313 g_variant_builder_clear (GVSB(builder)->parent);
3314 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3317 memset (builder, 0, sizeof (GVariantBuilder));
3321 * g_variant_builder_init: (skip)
3322 * @builder: a #GVariantBuilder
3323 * @type: a container type
3325 * Initialises a #GVariantBuilder structure.
3327 * @type must be non-%NULL. It specifies the type of container to
3328 * construct. It can be an indefinite type such as
3329 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3330 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3333 * After the builder is initialised, values are added using
3334 * g_variant_builder_add_value() or g_variant_builder_add().
3336 * After all the child values are added, g_variant_builder_end() frees
3337 * the memory associated with the builder and returns the #GVariant that
3340 * This function completely ignores the previous contents of @builder.
3341 * On one hand this means that it is valid to pass in completely
3342 * uninitialised memory. On the other hand, this means that if you are
3343 * initialising over top of an existing #GVariantBuilder you need to
3344 * first call g_variant_builder_clear() in order to avoid leaking
3347 * You must not call g_variant_builder_ref() or
3348 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3349 * with this function. If you ever pass a reference to a
3350 * #GVariantBuilder outside of the control of your own code then you
3351 * should assume that the person receiving that reference may try to use
3352 * reference counting; you should use g_variant_builder_new() instead of
3358 g_variant_builder_init (GVariantBuilder *builder,
3359 const GVariantType *type)
3361 g_return_if_fail (type != NULL);
3362 g_return_if_fail (g_variant_type_is_container (type));
3364 memset (builder, 0, sizeof (GVariantBuilder));
3366 GVSB(builder)->type = g_variant_type_copy (type);
3367 GVSB(builder)->magic = GVSB_MAGIC;
3368 GVSB(builder)->trusted = TRUE;
3370 switch (*(const gchar *) type)
3372 case G_VARIANT_CLASS_VARIANT:
3373 GVSB(builder)->uniform_item_types = TRUE;
3374 GVSB(builder)->allocated_children = 1;
3375 GVSB(builder)->expected_type = NULL;
3376 GVSB(builder)->min_items = 1;
3377 GVSB(builder)->max_items = 1;
3380 case G_VARIANT_CLASS_ARRAY:
3381 GVSB(builder)->uniform_item_types = TRUE;
3382 GVSB(builder)->allocated_children = 8;
3383 GVSB(builder)->expected_type =
3384 g_variant_type_element (GVSB(builder)->type);
3385 GVSB(builder)->min_items = 0;
3386 GVSB(builder)->max_items = -1;
3389 case G_VARIANT_CLASS_MAYBE:
3390 GVSB(builder)->uniform_item_types = TRUE;
3391 GVSB(builder)->allocated_children = 1;
3392 GVSB(builder)->expected_type =
3393 g_variant_type_element (GVSB(builder)->type);
3394 GVSB(builder)->min_items = 0;
3395 GVSB(builder)->max_items = 1;
3398 case G_VARIANT_CLASS_DICT_ENTRY:
3399 GVSB(builder)->uniform_item_types = FALSE;
3400 GVSB(builder)->allocated_children = 2;
3401 GVSB(builder)->expected_type =
3402 g_variant_type_key (GVSB(builder)->type);
3403 GVSB(builder)->min_items = 2;
3404 GVSB(builder)->max_items = 2;
3407 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3408 GVSB(builder)->uniform_item_types = FALSE;
3409 GVSB(builder)->allocated_children = 8;
3410 GVSB(builder)->expected_type = NULL;
3411 GVSB(builder)->min_items = 0;
3412 GVSB(builder)->max_items = -1;
3415 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3416 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3417 GVSB(builder)->expected_type =
3418 g_variant_type_first (GVSB(builder)->type);
3419 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3420 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3421 GVSB(builder)->uniform_item_types = FALSE;
3425 g_assert_not_reached ();
3428 GVSB(builder)->children = g_new (GVariant *,
3429 GVSB(builder)->allocated_children);
3433 g_variant_builder_make_room (struct stack_builder *builder)
3435 if (builder->offset == builder->allocated_children)
3437 builder->allocated_children *= 2;
3438 builder->children = g_renew (GVariant *, builder->children,
3439 builder->allocated_children);
3444 * g_variant_builder_add_value:
3445 * @builder: a #GVariantBuilder
3446 * @value: a #GVariant
3448 * Adds @value to @builder.
3450 * It is an error to call this function in any way that would create an
3451 * inconsistent value to be constructed. Some examples of this are
3452 * putting different types of items into an array, putting the wrong
3453 * types or number of items in a tuple, putting more than one value into
3456 * If @value is a floating reference (see g_variant_ref_sink()),
3457 * the @builder instance takes ownership of @value.
3462 g_variant_builder_add_value (GVariantBuilder *builder,
3465 g_return_if_fail (is_valid_builder (builder));
3466 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3467 g_return_if_fail (!GVSB(builder)->expected_type ||
3468 g_variant_is_of_type (value,
3469 GVSB(builder)->expected_type));
3470 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3471 g_variant_is_of_type (value,
3472 GVSB(builder)->prev_item_type));
3474 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3476 if (!GVSB(builder)->uniform_item_types)
3478 /* advance our expected type pointers */
3479 if (GVSB(builder)->expected_type)
3480 GVSB(builder)->expected_type =
3481 g_variant_type_next (GVSB(builder)->expected_type);
3483 if (GVSB(builder)->prev_item_type)
3484 GVSB(builder)->prev_item_type =
3485 g_variant_type_next (GVSB(builder)->prev_item_type);
3488 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3490 g_variant_builder_make_room (GVSB(builder));
3492 GVSB(builder)->children[GVSB(builder)->offset++] =
3493 g_variant_ref_sink (value);
3497 * g_variant_builder_open:
3498 * @builder: a #GVariantBuilder
3499 * @type: a #GVariantType
3501 * Opens a subcontainer inside the given @builder. When done adding
3502 * items to the subcontainer, g_variant_builder_close() must be called.
3504 * It is an error to call this function in any way that would cause an
3505 * inconsistent value to be constructed (ie: adding too many values or
3506 * a value of an incorrect type).
3511 g_variant_builder_open (GVariantBuilder *builder,
3512 const GVariantType *type)
3514 GVariantBuilder *parent;
3516 g_return_if_fail (is_valid_builder (builder));
3517 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3518 g_return_if_fail (!GVSB(builder)->expected_type ||
3519 g_variant_type_is_subtype_of (type,
3520 GVSB(builder)->expected_type));
3521 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3522 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3525 parent = g_slice_dup (GVariantBuilder, builder);
3526 g_variant_builder_init (builder, type);
3527 GVSB(builder)->parent = parent;
3529 /* push the prev_item_type down into the subcontainer */
3530 if (GVSB(parent)->prev_item_type)
3532 if (!GVSB(builder)->uniform_item_types)
3533 /* tuples and dict entries */
3534 GVSB(builder)->prev_item_type =
3535 g_variant_type_first (GVSB(parent)->prev_item_type);
3537 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3538 /* maybes and arrays */
3539 GVSB(builder)->prev_item_type =
3540 g_variant_type_element (GVSB(parent)->prev_item_type);
3545 * g_variant_builder_close:
3546 * @builder: a #GVariantBuilder
3548 * Closes the subcontainer inside the given @builder that was opened by
3549 * the most recent call to g_variant_builder_open().
3551 * It is an error to call this function in any way that would create an
3552 * inconsistent value to be constructed (ie: too few values added to the
3558 g_variant_builder_close (GVariantBuilder *builder)
3560 GVariantBuilder *parent;
3562 g_return_if_fail (is_valid_builder (builder));
3563 g_return_if_fail (GVSB(builder)->parent != NULL);
3565 parent = GVSB(builder)->parent;
3566 GVSB(builder)->parent = NULL;
3568 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3571 g_slice_free (GVariantBuilder, parent);
3575 * g_variant_make_maybe_type:
3576 * @element: a #GVariant
3578 * Return the type of a maybe containing @element.
3580 static GVariantType *
3581 g_variant_make_maybe_type (GVariant *element)
3583 return g_variant_type_new_maybe (g_variant_get_type (element));
3587 * g_variant_make_array_type:
3588 * @element: a #GVariant
3590 * Return the type of an array containing @element.
3592 static GVariantType *
3593 g_variant_make_array_type (GVariant *element)
3595 return g_variant_type_new_array (g_variant_get_type (element));
3599 * g_variant_builder_end:
3600 * @builder: a #GVariantBuilder
3602 * Ends the builder process and returns the constructed value.
3604 * It is not permissible to use @builder in any way after this call
3605 * except for reference counting operations (in the case of a
3606 * heap-allocated #GVariantBuilder) or by reinitialising it with
3607 * g_variant_builder_init() (in the case of stack-allocated).
3609 * It is an error to call this function in any way that would create an
3610 * inconsistent value to be constructed (ie: insufficient number of
3611 * items added to a container with a specific number of children
3612 * required). It is also an error to call this function if the builder
3613 * was created with an indefinite array or maybe type and no children
3614 * have been added; in this case it is impossible to infer the type of
3617 * Returns: (transfer none): a new, floating, #GVariant
3622 g_variant_builder_end (GVariantBuilder *builder)
3624 GVariantType *my_type;
3627 g_return_val_if_fail (is_valid_builder (builder), NULL);
3628 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3630 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3631 GVSB(builder)->prev_item_type != NULL ||
3632 g_variant_type_is_definite (GVSB(builder)->type),
3635 if (g_variant_type_is_definite (GVSB(builder)->type))
3636 my_type = g_variant_type_copy (GVSB(builder)->type);
3638 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3639 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3641 else if (g_variant_type_is_array (GVSB(builder)->type))
3642 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3644 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3645 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3646 GVSB(builder)->offset);
3648 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3649 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3650 GVSB(builder)->children[1]);
3652 g_assert_not_reached ();
3654 value = g_variant_new_from_children (my_type,
3655 g_renew (GVariant *,
3656 GVSB(builder)->children,
3657 GVSB(builder)->offset),
3658 GVSB(builder)->offset,
3659 GVSB(builder)->trusted);
3660 GVSB(builder)->children = NULL;
3661 GVSB(builder)->offset = 0;
3663 g_variant_builder_clear (builder);
3664 g_variant_type_free (my_type);
3669 /* Format strings {{{1 */
3671 * g_variant_format_string_scan:
3672 * @string: a string that may be prefixed with a format string
3673 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3675 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3678 * Checks the string pointed to by @string for starting with a properly
3679 * formed #GVariant varargs format string. If no valid format string is
3680 * found then %FALSE is returned.
3682 * If @string does start with a valid format string then %TRUE is
3683 * returned. If @endptr is non-%NULL then it is updated to point to the
3684 * first character after the format string.
3686 * If @limit is non-%NULL then @limit (and any charater after it) will
3687 * not be accessed and the effect is otherwise equivalent to if the
3688 * character at @limit were nul.
3690 * See the section on <link linkend='gvariant-format-strings'>GVariant
3691 * Format Strings</link>.
3693 * Returns: %TRUE if there was a valid format string
3698 g_variant_format_string_scan (const gchar *string,
3700 const gchar **endptr)
3702 #define next_char() (string == limit ? '\0' : *string++)
3703 #define peek_char() (string == limit ? '\0' : *string)
3706 switch (next_char())
3708 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
3709 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
3710 case 'g': case 'v': case '*': case '?': case 'r':
3714 return g_variant_format_string_scan (string, limit, endptr);
3718 return g_variant_type_string_scan (string, limit, endptr);
3721 while (peek_char() != ')')
3722 if (!g_variant_format_string_scan (string, limit, &string))
3725 next_char(); /* consume ')' */
3735 if (c != 's' && c != 'o' && c != 'g')
3743 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3744 * The terminating null character is considered to be
3745 * part of the string.
3747 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3751 if (!g_variant_format_string_scan (string, limit, &string))
3754 if (next_char() != '}')
3760 if ((c = next_char()) == 'a')
3762 if ((c = next_char()) == '&')
3764 if ((c = next_char()) == 'a')
3766 if ((c = next_char()) == 'y')
3767 break; /* '^a&ay' */
3770 else if (c == 's' || c == 'o')
3771 break; /* '^a&s', '^a&o' */
3776 if ((c = next_char()) == 'y')
3780 else if (c == 's' || c == 'o')
3781 break; /* '^as', '^ao' */
3788 if ((c = next_char()) == 'a')
3790 if ((c = next_char()) == 'y')
3800 if (c != 's' && c != 'o' && c != 'g')
3819 * g_variant_check_format_string:
3820 * @value: a #GVariant
3821 * @format_string: a valid #GVariant format string
3822 * @copy_only: %TRUE to ensure the format string makes deep copies
3824 * Checks if calling g_variant_get() with @format_string on @value would
3825 * be valid from a type-compatibility standpoint. @format_string is
3826 * assumed to be a valid format string (from a syntactic standpoint).
3828 * If @copy_only is %TRUE then this function additionally checks that it
3829 * would be safe to call g_variant_unref() on @value immediately after
3830 * the call to g_variant_get() without invalidating the result. This is
3831 * only possible if deep copies are made (ie: there are no pointers to
3832 * the data inside of the soon-to-be-freed #GVariant instance). If this
3833 * check fails then a g_critical() is printed and %FALSE is returned.
3835 * This function is meant to be used by functions that wish to provide
3836 * varargs accessors to #GVariant values of uncertain values (eg:
3837 * g_variant_lookup() or g_menu_model_get_item_attribute()).
3839 * Returns: %TRUE if @format_string is safe to use
3844 g_variant_check_format_string (GVariant *value,
3845 const gchar *format_string,
3848 const gchar *original_format = format_string;
3849 const gchar *type_string;
3851 /* Interesting factoid: assuming a format string is valid, it can be
3852 * converted to a type string by removing all '@' '&' and '^'
3855 * Instead of doing that, we can just skip those characters when
3856 * comparing it to the type string of @value.
3858 * For the copy-only case we can just drop the '&' from the list of
3859 * characters to skip over. A '&' will never appear in a type string
3860 * so we know that it won't be possible to return %TRUE if it is in a
3863 type_string = g_variant_get_type_string (value);
3865 while (*type_string || *format_string)
3867 gchar format = *format_string++;
3872 if G_UNLIKELY (copy_only)
3874 /* for the love of all that is good, please don't mark this string for translation... */
3875 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
3876 "interface to validate the passed format string for type safety. The passed format "
3877 "(%s) contains a '&' character which would result in a pointer being returned to the "
3878 "data inside of a GVariant instance that may no longer exist by the time the function "
3879 "returns. Modify your code to use a format string without '&'.", original_format);
3886 /* ignore these 2 (or 3) */
3890 /* attempt to consume one of 'bynqiuxthdsog' */
3892 char s = *type_string++;
3894 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
3900 /* ensure it's a tuple */
3901 if (*type_string != '(')
3906 /* consume a full type string for the '*' or 'r' */
3907 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
3913 /* attempt to consume exactly one character equal to the format */
3914 if (format != *type_string++)
3923 * g_variant_format_string_scan_type:
3924 * @string: a string that may be prefixed with a format string
3925 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3927 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3930 * If @string starts with a valid format string then this function will
3931 * return the type that the format string corresponds to. Otherwise
3932 * this function returns %NULL.
3934 * Use g_variant_type_free() to free the return value when you no longer
3937 * This function is otherwise exactly like
3938 * g_variant_format_string_scan().
3940 * Returns: (allow-none): a #GVariantType if there was a valid format string
3945 g_variant_format_string_scan_type (const gchar *string,
3947 const gchar **endptr)
3949 const gchar *my_end;
3956 if (!g_variant_format_string_scan (string, limit, endptr))
3959 dest = new = g_malloc (*endptr - string + 1);
3960 while (string != *endptr)
3962 if (*string != '@' && *string != '&' && *string != '^')
3968 return (GVariantType *) G_VARIANT_TYPE (new);
3972 valid_format_string (const gchar *format_string,
3976 const gchar *endptr;
3979 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3981 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3984 g_critical ("'%s' is not a valid GVariant format string",
3987 g_critical ("'%s' does not have a valid GVariant format "
3988 "string as a prefix", format_string);
3991 g_variant_type_free (type);
3996 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4001 fragment = g_strndup (format_string, endptr - format_string);
4002 typestr = g_variant_type_dup_string (type);
4004 g_critical ("the GVariant format string '%s' has a type of "
4005 "'%s' but the given value has a type of '%s'",
4006 fragment, typestr, g_variant_get_type_string (value));
4008 g_variant_type_free (type);
4015 g_variant_type_free (type);
4020 /* Variable Arguments {{{1 */
4021 /* We consider 2 main classes of format strings:
4023 * - recursive format strings
4024 * these are ones that result in recursion and the collection of
4025 * possibly more than one argument. Maybe types, tuples,
4026 * dictionary entries.
4028 * - leaf format string
4029 * these result in the collection of a single argument.
4031 * Leaf format strings are further subdivided into two categories:
4033 * - single non-null pointer ("nnp")
4034 * these either collect or return a single non-null pointer.
4037 * these collect or return something else (bool, number, etc).
4039 * Based on the above, the varargs handling code is split into 4 main parts:
4041 * - nnp handling code
4042 * - leaf handling code (which may invoke nnp code)
4043 * - generic handling code (may be recursive, may invoke leaf code)
4044 * - user-facing API (which invokes the generic code)
4046 * Each section implements some of the following functions:
4049 * collect the arguments for the format string as if
4050 * g_variant_new() had been called, but do nothing with them. used
4051 * for skipping over arguments when constructing a Nothing maybe
4055 * create a GVariant *
4058 * unpack a GVariant *
4060 * - free (nnp only):
4061 * free a previously allocated item
4065 g_variant_format_string_is_leaf (const gchar *str)
4067 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4071 g_variant_format_string_is_nnp (const gchar *str)
4073 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4074 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4075 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4078 /* Single non-null pointer ("nnp") {{{2 */
4080 g_variant_valist_free_nnp (const gchar *str,
4086 g_variant_iter_free (ptr);
4090 if (str[2] != '&') /* '^as', '^ao' */
4092 else /* '^a&s', '^a&o' */
4106 g_variant_unref (ptr);
4113 g_assert_not_reached ();
4118 g_variant_scan_convenience (const gchar **str,
4141 g_variant_valist_new_nnp (const gchar **str,
4152 const GVariantType *type;
4155 value = g_variant_builder_end (ptr);
4156 type = g_variant_get_type (value);
4158 if G_UNLIKELY (!g_variant_type_is_array (type))
4159 g_error ("g_variant_new: expected array GVariantBuilder but "
4160 "the built value has type '%s'",
4161 g_variant_get_type_string (value));
4163 type = g_variant_type_element (type);
4165 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4166 g_error ("g_variant_new: expected GVariantBuilder array element "
4167 "type '%s' but the built value has element type '%s'",
4168 g_variant_type_dup_string ((GVariantType *) *str),
4169 g_variant_get_type_string (value) + 1);
4171 g_variant_type_string_scan (*str, NULL, str);
4177 /* special case: NULL pointer for empty array */
4179 const GVariantType *type = (GVariantType *) *str;
4181 g_variant_type_string_scan (*str, NULL, str);
4183 if G_UNLIKELY (!g_variant_type_is_definite (type))
4184 g_error ("g_variant_new: NULL pointer given with indefinite "
4185 "array type; unable to determine which type of empty "
4186 "array to construct.");
4188 return g_variant_new_array (type, NULL, 0);
4195 value = g_variant_new_string (ptr);
4198 value = g_variant_new_string ("[Invalid UTF-8]");
4204 return g_variant_new_object_path (ptr);
4207 return g_variant_new_signature (ptr);
4215 type = g_variant_scan_convenience (str, &constant, &arrays);
4218 return g_variant_new_strv (ptr, -1);
4221 return g_variant_new_objv (ptr, -1);
4224 return g_variant_new_bytestring_array (ptr, -1);
4226 return g_variant_new_bytestring (ptr);
4230 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4231 g_error ("g_variant_new: expected GVariant of type '%s' but "
4232 "received value has type '%s'",
4233 g_variant_type_dup_string ((GVariantType *) *str),
4234 g_variant_get_type_string (ptr));
4236 g_variant_type_string_scan (*str, NULL, str);
4244 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4245 g_error ("g_variant_new: format string '?' expects basic-typed "
4246 "GVariant, but received value has type '%s'",
4247 g_variant_get_type_string (ptr));
4252 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4253 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4254 "GVariant, but received value has type '%s'",
4255 g_variant_get_type_string (ptr));
4260 return g_variant_new_variant (ptr);
4263 g_assert_not_reached ();
4268 g_variant_valist_get_nnp (const gchar **str,
4274 g_variant_type_string_scan (*str, NULL, str);
4275 return g_variant_iter_new (value);
4279 return (gchar *) g_variant_get_string (value, NULL);
4284 return g_variant_dup_string (value, NULL);
4292 type = g_variant_scan_convenience (str, &constant, &arrays);
4297 return g_variant_get_strv (value, NULL);
4299 return g_variant_dup_strv (value, NULL);
4302 else if (type == 'o')
4305 return g_variant_get_objv (value, NULL);
4307 return g_variant_dup_objv (value, NULL);
4310 else if (arrays > 1)
4313 return g_variant_get_bytestring_array (value, NULL);
4315 return g_variant_dup_bytestring_array (value, NULL);
4321 return (gchar *) g_variant_get_bytestring (value);
4323 return g_variant_dup_bytestring (value, NULL);
4328 g_variant_type_string_scan (*str, NULL, str);
4334 return g_variant_ref (value);
4337 return g_variant_get_variant (value);
4340 g_assert_not_reached ();
4346 g_variant_valist_skip_leaf (const gchar **str,
4349 if (g_variant_format_string_is_nnp (*str))
4351 g_variant_format_string_scan (*str, NULL, str);
4352 va_arg (*app, gpointer);
4370 va_arg (*app, guint64);
4374 va_arg (*app, gdouble);
4378 g_assert_not_reached ();
4383 g_variant_valist_new_leaf (const gchar **str,
4386 if (g_variant_format_string_is_nnp (*str))
4387 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4392 return g_variant_new_boolean (va_arg (*app, gboolean));
4395 return g_variant_new_byte (va_arg (*app, guint));
4398 return g_variant_new_int16 (va_arg (*app, gint));
4401 return g_variant_new_uint16 (va_arg (*app, guint));
4404 return g_variant_new_int32 (va_arg (*app, gint));
4407 return g_variant_new_uint32 (va_arg (*app, guint));
4410 return g_variant_new_int64 (va_arg (*app, gint64));
4413 return g_variant_new_uint64 (va_arg (*app, guint64));
4416 return g_variant_new_handle (va_arg (*app, gint));
4419 return g_variant_new_double (va_arg (*app, gdouble));
4422 g_assert_not_reached ();
4426 /* The code below assumes this */
4427 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4428 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4431 g_variant_valist_get_leaf (const gchar **str,
4436 gpointer ptr = va_arg (*app, gpointer);
4440 g_variant_format_string_scan (*str, NULL, str);
4444 if (g_variant_format_string_is_nnp (*str))
4446 gpointer *nnp = (gpointer *) ptr;
4448 if (free && *nnp != NULL)
4449 g_variant_valist_free_nnp (*str, *nnp);
4454 *nnp = g_variant_valist_get_nnp (str, value);
4456 g_variant_format_string_scan (*str, NULL, str);
4466 *(gboolean *) ptr = g_variant_get_boolean (value);
4470 *(guchar *) ptr = g_variant_get_byte (value);
4474 *(gint16 *) ptr = g_variant_get_int16 (value);
4478 *(guint16 *) ptr = g_variant_get_uint16 (value);
4482 *(gint32 *) ptr = g_variant_get_int32 (value);
4486 *(guint32 *) ptr = g_variant_get_uint32 (value);
4490 *(gint64 *) ptr = g_variant_get_int64 (value);
4494 *(guint64 *) ptr = g_variant_get_uint64 (value);
4498 *(gint32 *) ptr = g_variant_get_handle (value);
4502 *(gdouble *) ptr = g_variant_get_double (value);
4511 *(guchar *) ptr = 0;
4516 *(guint16 *) ptr = 0;
4523 *(guint32 *) ptr = 0;
4529 *(guint64 *) ptr = 0;
4534 g_assert_not_reached ();
4537 /* Generic (recursive) {{{2 */
4539 g_variant_valist_skip (const gchar **str,
4542 if (g_variant_format_string_is_leaf (*str))
4543 g_variant_valist_skip_leaf (str, app);
4545 else if (**str == 'm') /* maybe */
4549 if (!g_variant_format_string_is_nnp (*str))
4550 va_arg (*app, gboolean);
4552 g_variant_valist_skip (str, app);
4554 else /* tuple, dictionary entry */
4556 g_assert (**str == '(' || **str == '{');
4558 while (**str != ')' && **str != '}')
4559 g_variant_valist_skip (str, app);
4565 g_variant_valist_new (const gchar **str,
4568 if (g_variant_format_string_is_leaf (*str))
4569 return g_variant_valist_new_leaf (str, app);
4571 if (**str == 'm') /* maybe */
4573 GVariantType *type = NULL;
4574 GVariant *value = NULL;
4578 if (g_variant_format_string_is_nnp (*str))
4580 gpointer nnp = va_arg (*app, gpointer);
4583 value = g_variant_valist_new_nnp (str, nnp);
4585 type = g_variant_format_string_scan_type (*str, NULL, str);
4589 gboolean just = va_arg (*app, gboolean);
4592 value = g_variant_valist_new (str, app);
4595 type = g_variant_format_string_scan_type (*str, NULL, NULL);
4596 g_variant_valist_skip (str, app);
4600 value = g_variant_new_maybe (type, value);
4603 g_variant_type_free (type);
4607 else /* tuple, dictionary entry */
4612 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
4615 g_assert (**str == '{');
4616 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
4620 while (**str != ')' && **str != '}')
4621 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
4624 return g_variant_builder_end (&b);
4629 g_variant_valist_get (const gchar **str,
4634 if (g_variant_format_string_is_leaf (*str))
4635 g_variant_valist_get_leaf (str, value, free, app);
4637 else if (**str == 'm')
4642 value = g_variant_get_maybe (value);
4644 if (!g_variant_format_string_is_nnp (*str))
4646 gboolean *ptr = va_arg (*app, gboolean *);
4649 *ptr = value != NULL;
4652 g_variant_valist_get (str, value, free, app);
4655 g_variant_unref (value);
4658 else /* tuple, dictionary entry */
4662 g_assert (**str == '(' || **str == '{');
4665 while (**str != ')' && **str != '}')
4669 GVariant *child = g_variant_get_child_value (value, index++);
4670 g_variant_valist_get (str, child, free, app);
4671 g_variant_unref (child);
4674 g_variant_valist_get (str, NULL, free, app);
4680 /* User-facing API {{{2 */
4682 * g_variant_new: (skip)
4683 * @format_string: a #GVariant format string
4684 * @...: arguments, as per @format_string
4686 * Creates a new #GVariant instance.
4688 * Think of this function as an analogue to g_strdup_printf().
4690 * The type of the created instance and the arguments that are
4691 * expected by this function are determined by @format_string. See the
4692 * section on <link linkend='gvariant-format-strings'>GVariant Format
4693 * Strings</link>. Please note that the syntax of the format string is
4694 * very likely to be extended in the future.
4696 * The first character of the format string must not be '*' '?' '@' or
4697 * 'r'; in essence, a new #GVariant must always be constructed by this
4698 * function (and not merely passed through it unmodified).
4700 * Returns: a new floating #GVariant instance
4705 g_variant_new (const gchar *format_string,
4711 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
4712 format_string[0] != '?' && format_string[0] != '@' &&
4713 format_string[0] != '*' && format_string[0] != 'r',
4716 va_start (ap, format_string);
4717 value = g_variant_new_va (format_string, NULL, &ap);
4724 * g_variant_new_va: (skip)
4725 * @format_string: a string that is prefixed with a format string
4726 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4728 * @app: a pointer to a #va_list
4730 * This function is intended to be used by libraries based on
4731 * #GVariant that want to provide g_variant_new()-like functionality
4734 * The API is more general than g_variant_new() to allow a wider range
4737 * @format_string must still point to a valid format string, but it only
4738 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
4739 * non-%NULL then it is updated to point to the first character past the
4740 * end of the format string.
4742 * @app is a pointer to a #va_list. The arguments, according to
4743 * @format_string, are collected from this #va_list and the list is left
4744 * pointing to the argument following the last.
4746 * These two generalisations allow mixing of multiple calls to
4747 * g_variant_new_va() and g_variant_get_va() within a single actual
4748 * varargs call by the user.
4750 * The return value will be floating if it was a newly created GVariant
4751 * instance (for example, if the format string was "(ii)"). In the case
4752 * that the format_string was '*', '?', 'r', or a format starting with
4753 * '@' then the collected #GVariant pointer will be returned unmodified,
4754 * without adding any additional references.
4756 * In order to behave correctly in all cases it is necessary for the
4757 * calling function to g_variant_ref_sink() the return result before
4758 * returning control to the user that originally provided the pointer.
4759 * At this point, the caller will have their own full reference to the
4760 * result. This can also be done by adding the result to a container,
4761 * or by passing it to another g_variant_new() call.
4763 * Returns: a new, usually floating, #GVariant
4768 g_variant_new_va (const gchar *format_string,
4769 const gchar **endptr,
4774 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
4776 g_return_val_if_fail (app != NULL, NULL);
4778 value = g_variant_valist_new (&format_string, app);
4781 *endptr = format_string;
4787 * g_variant_get: (skip)
4788 * @value: a #GVariant instance
4789 * @format_string: a #GVariant format string
4790 * @...: arguments, as per @format_string
4792 * Deconstructs a #GVariant instance.
4794 * Think of this function as an analogue to scanf().
4796 * The arguments that are expected by this function are entirely
4797 * determined by @format_string. @format_string also restricts the
4798 * permissible types of @value. It is an error to give a value with
4799 * an incompatible type. See the section on <link
4800 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
4801 * Please note that the syntax of the format string is very likely to be
4802 * extended in the future.
4804 * @format_string determines the C types that are used for unpacking
4805 * the values and also determines if the values are copied or borrowed,
4806 * see the section on
4807 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4812 g_variant_get (GVariant *value,
4813 const gchar *format_string,
4818 g_return_if_fail (valid_format_string (format_string, TRUE, value));
4820 /* if any direct-pointer-access formats are in use, flatten first */
4821 if (strchr (format_string, '&'))
4822 g_variant_get_data (value);
4824 va_start (ap, format_string);
4825 g_variant_get_va (value, format_string, NULL, &ap);
4830 * g_variant_get_va: (skip)
4831 * @value: a #GVariant
4832 * @format_string: a string that is prefixed with a format string
4833 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4835 * @app: a pointer to a #va_list
4837 * This function is intended to be used by libraries based on #GVariant
4838 * that want to provide g_variant_get()-like functionality to their
4841 * The API is more general than g_variant_get() to allow a wider range
4844 * @format_string must still point to a valid format string, but it only
4845 * need to be nul-terminated if @endptr is %NULL. If @endptr is
4846 * non-%NULL then it is updated to point to the first character past the
4847 * end of the format string.
4849 * @app is a pointer to a #va_list. The arguments, according to
4850 * @format_string, are collected from this #va_list and the list is left
4851 * pointing to the argument following the last.
4853 * These two generalisations allow mixing of multiple calls to
4854 * g_variant_new_va() and g_variant_get_va() within a single actual
4855 * varargs call by the user.
4857 * @format_string determines the C types that are used for unpacking
4858 * the values and also determines if the values are copied or borrowed,
4859 * see the section on
4860 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4865 g_variant_get_va (GVariant *value,
4866 const gchar *format_string,
4867 const gchar **endptr,
4870 g_return_if_fail (valid_format_string (format_string, !endptr, value));
4871 g_return_if_fail (value != NULL);
4872 g_return_if_fail (app != NULL);
4874 /* if any direct-pointer-access formats are in use, flatten first */
4875 if (strchr (format_string, '&'))
4876 g_variant_get_data (value);
4878 g_variant_valist_get (&format_string, value, FALSE, app);
4881 *endptr = format_string;
4884 /* Varargs-enabled Utility Functions {{{1 */
4887 * g_variant_builder_add: (skip)
4888 * @builder: a #GVariantBuilder
4889 * @format_string: a #GVariant varargs format string
4890 * @...: arguments, as per @format_string
4892 * Adds to a #GVariantBuilder.
4894 * This call is a convenience wrapper that is exactly equivalent to
4895 * calling g_variant_new() followed by g_variant_builder_add_value().
4897 * This function might be used as follows:
4901 * make_pointless_dictionary (void)
4903 * GVariantBuilder builder;
4906 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
4907 * for (i = 0; i < 16; i++)
4911 * sprintf (buf, "%d", i);
4912 * g_variant_builder_add (&builder, "{is}", i, buf);
4915 * return g_variant_builder_end (&builder);
4922 g_variant_builder_add (GVariantBuilder *builder,
4923 const gchar *format_string,
4929 va_start (ap, format_string);
4930 variant = g_variant_new_va (format_string, NULL, &ap);
4933 g_variant_builder_add_value (builder, variant);
4937 * g_variant_get_child: (skip)
4938 * @value: a container #GVariant
4939 * @index_: the index of the child to deconstruct
4940 * @format_string: a #GVariant format string
4941 * @...: arguments, as per @format_string
4943 * Reads a child item out of a container #GVariant instance and
4944 * deconstructs it according to @format_string. This call is
4945 * essentially a combination of g_variant_get_child_value() and
4948 * @format_string determines the C types that are used for unpacking
4949 * the values and also determines if the values are copied or borrowed,
4950 * see the section on
4951 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
4956 g_variant_get_child (GVariant *value,
4958 const gchar *format_string,
4964 child = g_variant_get_child_value (value, index_);
4965 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4967 va_start (ap, format_string);
4968 g_variant_get_va (child, format_string, NULL, &ap);
4971 g_variant_unref (child);
4975 * g_variant_iter_next: (skip)
4976 * @iter: a #GVariantIter
4977 * @format_string: a GVariant format string
4978 * @...: the arguments to unpack the value into
4980 * Gets the next item in the container and unpacks it into the variable
4981 * argument list according to @format_string, returning %TRUE.
4983 * If no more items remain then %FALSE is returned.
4985 * All of the pointers given on the variable arguments list of this
4986 * function are assumed to point at uninitialised memory. It is the
4987 * responsibility of the caller to free all of the values returned by
4988 * the unpacking process.
4990 * See the section on <link linkend='gvariant-format-strings'>GVariant
4991 * Format Strings</link>.
4994 * <title>Memory management with g_variant_iter_next()</title>
4996 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4998 * iterate_dictionary (GVariant *dictionary)
5000 * GVariantIter iter;
5004 * g_variant_iter_init (&iter, dictionary);
5005 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5007 * g_print ("Item '%s' has type '%s'\n", key,
5008 * g_variant_get_type_string (value));
5010 * /<!-- -->* must free data for ourselves *<!-- -->/
5011 * g_variant_unref (value);
5018 * For a solution that is likely to be more convenient to C programmers
5019 * when dealing with loops, see g_variant_iter_loop().
5021 * @format_string determines the C types that are used for unpacking
5022 * the values and also determines if the values are copied or borrowed,
5023 * see the section on
5024 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5026 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5031 g_variant_iter_next (GVariantIter *iter,
5032 const gchar *format_string,
5037 value = g_variant_iter_next_value (iter);
5039 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5046 va_start (ap, format_string);
5047 g_variant_valist_get (&format_string, value, FALSE, &ap);
5050 g_variant_unref (value);
5053 return value != NULL;
5057 * g_variant_iter_loop: (skip)
5058 * @iter: a #GVariantIter
5059 * @format_string: a GVariant format string
5060 * @...: the arguments to unpack the value into
5062 * Gets the next item in the container and unpacks it into the variable
5063 * argument list according to @format_string, returning %TRUE.
5065 * If no more items remain then %FALSE is returned.
5067 * On the first call to this function, the pointers appearing on the
5068 * variable argument list are assumed to point at uninitialised memory.
5069 * On the second and later calls, it is assumed that the same pointers
5070 * will be given and that they will point to the memory as set by the
5071 * previous call to this function. This allows the previous values to
5072 * be freed, as appropriate.
5074 * This function is intended to be used with a while loop as
5075 * demonstrated in the following example. This function can only be
5076 * used when iterating over an array. It is only valid to call this
5077 * function with a string constant for the format string and the same
5078 * string constant must be used each time. Mixing calls to this
5079 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5080 * the same iterator causes undefined behavior.
5082 * If you break out of a such a while loop using g_variant_iter_loop() then
5083 * you must free or unreference all the unpacked values as you would with
5084 * g_variant_get(). Failure to do so will cause a memory leak.
5086 * See the section on <link linkend='gvariant-format-strings'>GVariant
5087 * Format Strings</link>.
5090 * <title>Memory management with g_variant_iter_loop()</title>
5092 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
5094 * iterate_dictionary (GVariant *dictionary)
5096 * GVariantIter iter;
5100 * g_variant_iter_init (&iter, dictionary);
5101 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5103 * g_print ("Item '%s' has type '%s'\n", key,
5104 * g_variant_get_type_string (value));
5106 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
5107 * /<!-- -->* unless breaking out of this loop *<!-- -->/
5113 * For most cases you should use g_variant_iter_next().
5115 * This function is really only useful when unpacking into #GVariant or
5116 * #GVariantIter in order to allow you to skip the call to
5117 * g_variant_unref() or g_variant_iter_free().
5119 * For example, if you are only looping over simple integer and string
5120 * types, g_variant_iter_next() is definitely preferred. For string
5121 * types, use the '&' prefix to avoid allocating any memory at all (and
5122 * thereby avoiding the need to free anything as well).
5124 * @format_string determines the C types that are used for unpacking
5125 * the values and also determines if the values are copied or borrowed,
5126 * see the section on
5127 * <link linkend='gvariant-format-strings-pointers'>GVariant Format Strings</link>.
5129 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5135 g_variant_iter_loop (GVariantIter *iter,
5136 const gchar *format_string,
5139 gboolean first_time = GVSI(iter)->loop_format == NULL;
5143 g_return_val_if_fail (first_time ||
5144 format_string == GVSI(iter)->loop_format,
5149 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5150 GVSI(iter)->loop_format = format_string;
5152 if (strchr (format_string, '&'))
5153 g_variant_get_data (GVSI(iter)->value);
5156 value = g_variant_iter_next_value (iter);
5158 g_return_val_if_fail (!first_time ||
5159 valid_format_string (format_string, TRUE, value),
5162 va_start (ap, format_string);
5163 g_variant_valist_get (&format_string, value, !first_time, &ap);
5167 g_variant_unref (value);
5169 return value != NULL;
5172 /* Serialised data {{{1 */
5174 g_variant_deep_copy (GVariant *value)
5176 switch (g_variant_classify (value))
5178 case G_VARIANT_CLASS_MAYBE:
5179 case G_VARIANT_CLASS_ARRAY:
5180 case G_VARIANT_CLASS_TUPLE:
5181 case G_VARIANT_CLASS_DICT_ENTRY:
5182 case G_VARIANT_CLASS_VARIANT:
5184 GVariantBuilder builder;
5188 g_variant_builder_init (&builder, g_variant_get_type (value));
5189 g_variant_iter_init (&iter, value);
5191 while ((child = g_variant_iter_next_value (&iter)))
5193 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5194 g_variant_unref (child);
5197 return g_variant_builder_end (&builder);
5200 case G_VARIANT_CLASS_BOOLEAN:
5201 return g_variant_new_boolean (g_variant_get_boolean (value));
5203 case G_VARIANT_CLASS_BYTE:
5204 return g_variant_new_byte (g_variant_get_byte (value));
5206 case G_VARIANT_CLASS_INT16:
5207 return g_variant_new_int16 (g_variant_get_int16 (value));
5209 case G_VARIANT_CLASS_UINT16:
5210 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5212 case G_VARIANT_CLASS_INT32:
5213 return g_variant_new_int32 (g_variant_get_int32 (value));
5215 case G_VARIANT_CLASS_UINT32:
5216 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5218 case G_VARIANT_CLASS_INT64:
5219 return g_variant_new_int64 (g_variant_get_int64 (value));
5221 case G_VARIANT_CLASS_UINT64:
5222 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5224 case G_VARIANT_CLASS_HANDLE:
5225 return g_variant_new_handle (g_variant_get_handle (value));
5227 case G_VARIANT_CLASS_DOUBLE:
5228 return g_variant_new_double (g_variant_get_double (value));
5230 case G_VARIANT_CLASS_STRING:
5231 return g_variant_new_string (g_variant_get_string (value, NULL));
5233 case G_VARIANT_CLASS_OBJECT_PATH:
5234 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5236 case G_VARIANT_CLASS_SIGNATURE:
5237 return g_variant_new_signature (g_variant_get_string (value, NULL));
5240 g_assert_not_reached ();
5244 * g_variant_get_normal_form:
5245 * @value: a #GVariant
5247 * Gets a #GVariant instance that has the same value as @value and is
5248 * trusted to be in normal form.
5250 * If @value is already trusted to be in normal form then a new
5251 * reference to @value is returned.
5253 * If @value is not already trusted, then it is scanned to check if it
5254 * is in normal form. If it is found to be in normal form then it is
5255 * marked as trusted and a new reference to it is returned.
5257 * If @value is found not to be in normal form then a new trusted
5258 * #GVariant is created with the same value as @value.
5260 * It makes sense to call this function if you've received #GVariant
5261 * data from untrusted sources and you want to ensure your serialised
5262 * output is definitely in normal form.
5264 * Returns: (transfer full): a trusted #GVariant
5269 g_variant_get_normal_form (GVariant *value)
5273 if (g_variant_is_normal_form (value))
5274 return g_variant_ref (value);
5276 trusted = g_variant_deep_copy (value);
5277 g_assert (g_variant_is_trusted (trusted));
5279 return g_variant_ref_sink (trusted);
5283 * g_variant_byteswap:
5284 * @value: a #GVariant
5286 * Performs a byteswapping operation on the contents of @value. The
5287 * result is that all multi-byte numeric data contained in @value is
5288 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5289 * integers as well as file handles and double precision floating point
5292 * This function is an identity mapping on any value that does not
5293 * contain multi-byte numeric data. That include strings, booleans,
5294 * bytes and containers containing only these things (recursively).
5296 * The returned value is always in normal form and is marked as trusted.
5298 * Returns: (transfer full): the byteswapped form of @value
5303 g_variant_byteswap (GVariant *value)
5305 GVariantTypeInfo *type_info;
5309 type_info = g_variant_get_type_info (value);
5311 g_variant_type_info_query (type_info, &alignment, NULL);
5314 /* (potentially) contains multi-byte numeric data */
5316 GVariantSerialised serialised;
5320 trusted = g_variant_get_normal_form (value);
5321 serialised.type_info = g_variant_get_type_info (trusted);
5322 serialised.size = g_variant_get_size (trusted);
5323 serialised.data = g_malloc (serialised.size);
5324 g_variant_store (trusted, serialised.data);
5325 g_variant_unref (trusted);
5327 g_variant_serialised_byteswap (serialised);
5329 bytes = g_bytes_new_take (serialised.data, serialised.size);
5330 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5331 g_bytes_unref (bytes);
5334 /* contains no multi-byte data */
5337 return g_variant_ref_sink (new);
5341 * g_variant_new_from_data:
5342 * @type: a definite #GVariantType
5343 * @data: (array length=size) (element-type guint8): the serialised data
5344 * @size: the size of @data
5345 * @trusted: %TRUE if @data is definitely in normal form
5346 * @notify: (scope async): function to call when @data is no longer needed
5347 * @user_data: data for @notify
5349 * Creates a new #GVariant instance from serialised data.
5351 * @type is the type of #GVariant instance that will be constructed.
5352 * The interpretation of @data depends on knowing the type.
5354 * @data is not modified by this function and must remain valid with an
5355 * unchanging value until such a time as @notify is called with
5356 * @user_data. If the contents of @data change before that time then
5357 * the result is undefined.
5359 * If @data is trusted to be serialised data in normal form then
5360 * @trusted should be %TRUE. This applies to serialised data created
5361 * within this process or read from a trusted location on the disk (such
5362 * as a file installed in /usr/lib alongside your application). You
5363 * should set trusted to %FALSE if @data is read from the network, a
5364 * file in the user's home directory, etc.
5366 * If @data was not stored in this machine's native endianness, any multi-byte
5367 * numeric values in the returned variant will also be in non-native
5368 * endianness. g_variant_byteswap() can be used to recover the original values.
5370 * @notify will be called with @user_data when @data is no longer
5371 * needed. The exact time of this call is unspecified and might even be
5372 * before this function returns.
5374 * Returns: (transfer none): a new floating #GVariant of type @type
5379 g_variant_new_from_data (const GVariantType *type,
5383 GDestroyNotify notify,
5389 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5390 g_return_val_if_fail (data != NULL || size == 0, NULL);
5393 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5395 bytes = g_bytes_new_static (data, size);
5397 value = g_variant_new_from_bytes (type, bytes, trusted);
5398 g_bytes_unref (bytes);
5404 /* vim:set foldmethod=marker: */