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/ghash.h>
33 #include <glib/gmem.h>
41 * @short_description: strongly typed value datatype
42 * @see_also: GVariantType
44 * #GVariant is a variant datatype; it stores a value along with
45 * information about the type of that value. The range of possible
46 * values is determined by the type. The type system used by #GVariant
49 * #GVariant instances always have a type and a value (which are given
50 * at construction time). The type and value of a #GVariant instance
51 * can never change other than by the #GVariant itself being
52 * destroyed. A #GVariant can not contain a pointer.
54 * #GVariant is reference counted using g_variant_ref() and
55 * g_variant_unref(). #GVariant also has floating reference counts --
56 * see g_variant_ref_sink().
58 * #GVariant is completely threadsafe. A #GVariant instance can be
59 * concurrently accessed in any way from any number of threads without
62 * #GVariant is heavily optimised for dealing with data in serialised
63 * form. It works particularly well with data located in memory-mapped
64 * files. It can perform nearly all deserialisation operations in a
65 * small constant time, usually touching only a single memory page.
66 * Serialised #GVariant data can also be sent over the network.
68 * #GVariant is largely compatible with DBus. Almost all types of
69 * #GVariant instances can be sent over DBus. See #GVariantType for
72 * For convenience to C programmers, #GVariant features powerful
73 * varargs-based value construction and destruction. This feature is
74 * designed to be embedded in other libraries.
76 * There is a Python-inspired text language for describing #GVariant
77 * values. #GVariant includes a printer for this language and a parser
78 * with type inferencing.
81 * <title>Memory Use</title>
83 * #GVariant tries to be quite efficient with respect to memory use.
84 * This section gives a rough idea of how much memory is used by the
85 * current implementation. The information here is subject to change
89 * The memory allocated by #GVariant can be grouped into 4 broad
90 * purposes: memory for serialised data, memory for the type
91 * information cache, buffer management memory and memory for the
92 * #GVariant structure itself.
95 * <title>Serialised Data Memory</title>
97 * This is the memory that is used for storing GVariant data in
98 * serialised form. This is what would be sent over the network or
99 * what would end up on disk.
102 * The amount of memory required to store a boolean is 1 byte. 16,
103 * 32 and 64 bit integers and double precision floating point numbers
104 * use their "natural" size. Strings (including object path and
105 * signature strings) are stored with a nul terminator, and as such
106 * use the length of the string plus 1 byte.
109 * Maybe types use no space at all to represent the null value and
110 * use the same amount of space (sometimes plus one byte) as the
111 * equivalent non-maybe-typed value to represent the non-null case.
114 * Arrays use the amount of space required to store each of their
115 * members, concatenated. Additionally, if the items stored in an
116 * array are not of a fixed-size (ie: strings, other arrays, etc)
117 * then an additional framing offset is stored for each item. The
118 * size of this offset is either 1, 2 or 4 bytes depending on the
119 * overall size of the container. Additionally, extra padding bytes
120 * are added as required for alignment of child values.
123 * Tuples (including dictionary entries) use the amount of space
124 * required to store each of their members, concatenated, plus one
125 * framing offset (as per arrays) for each non-fixed-sized item in
126 * the tuple, except for the last one. Additionally, extra padding
127 * bytes are added as required for alignment of child values.
130 * Variants use the same amount of space as the item inside of the
131 * variant, plus 1 byte, plus the length of the type string for the
132 * item inside the variant.
135 * As an example, consider a dictionary mapping strings to variants.
136 * In the case that the dictionary is empty, 0 bytes are required for
140 * If we add an item "width" that maps to the int32 value of 500 then
141 * we will use 4 byte to store the int32 (so 6 for the variant
142 * containing it) and 6 bytes for the string. The variant must be
143 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
144 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
145 * for the dictionary entry. An additional 1 byte is added to the
146 * array as a framing offset making a total of 15 bytes.
149 * If we add another entry, "title" that maps to a nullable string
150 * that happens to have a value of null, then we use 0 bytes for the
151 * null value (and 3 bytes for the variant to contain it along with
152 * its type string) plus 6 bytes for the string. Again, we need 2
153 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
156 * We now require extra padding between the two items in the array.
157 * After the 14 bytes of the first item, that's 2 bytes required. We
158 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
159 * + 2 = 29 bytes to encode the entire two-item dictionary.
163 * <title>Type Information Cache</title>
165 * For each GVariant type that currently exists in the program a type
166 * information structure is kept in the type information cache. The
167 * type information structure is required for rapid deserialisation.
170 * Continuing with the above example, if a #GVariant exists with the
171 * type "a{sv}" then a type information struct will exist for
172 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
173 * will share the same type information. Additionally, all
174 * single-digit types are stored in read-only static memory and do
175 * not contribute to the writable memory footprint of a program using
179 * Aside from the type information structures stored in read-only
180 * memory, there are two forms of type information. One is used for
181 * container types where there is a single element type: arrays and
182 * maybe types. The other is used for container types where there
183 * are multiple element types: tuples and dictionary entries.
186 * Array type info structures are 6 * sizeof (void *), plus the
187 * memory required to store the type string itself. This means that
188 * on 32bit systems, the cache entry for "a{sv}" would require 30
189 * bytes of memory (plus malloc overhead).
192 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
193 * sizeof (void *) for each item in the tuple, plus the memory
194 * required to store the type string itself. A 2-item tuple, for
195 * example, would have a type information structure that consumed
196 * writable memory in the size of 14 * sizeof (void *) (plus type
197 * string) This means that on 32bit systems, the cache entry for
198 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
201 * This means that in total, for our "a{sv}" example, 91 bytes of
202 * type information would be allocated.
205 * The type information cache, additionally, uses a #GHashTable to
206 * store and lookup the cached items and stores a pointer to this
207 * hash table in static storage. The hash table is freed when there
208 * are zero items in the type cache.
211 * Although these sizes may seem large it is important to remember
212 * that a program will probably only have a very small number of
213 * different types of values in it and that only one type information
214 * structure is required for many different values of the same type.
218 * <title>Buffer Management Memory</title>
220 * #GVariant uses an internal buffer management structure to deal
221 * with the various different possible sources of serialised data
222 * that it uses. The buffer is responsible for ensuring that the
223 * correct call is made when the data is no longer in use by
224 * #GVariant. This may involve a g_free() or a g_slice_free() or
225 * even g_mapped_file_unref().
228 * One buffer management structure is used for each chunk of
229 * serialised data. The size of the buffer management structure is 4
230 * * (void *). On 32bit systems, that's 16 bytes.
234 * <title>GVariant structure</title>
236 * The size of a #GVariant structure is 6 * (void *). On 32 bit
237 * systems, that's 24 bytes.
240 * #GVariant structures only exist if they are explicitly created
241 * with API calls. For example, if a #GVariant is constructed out of
242 * serialised data for the example given above (with the dictionary)
243 * then although there are 9 individual values that comprise the
244 * entire dictionary (two keys, two values, two variants containing
245 * the values, two dictionary entries, plus the dictionary itself),
246 * only 1 #GVariant instance exists -- the one refering to the
250 * If calls are made to start accessing the other values then
251 * #GVariant instances will exist for those values only for as long
252 * as they are in use (ie: until you call g_variant_unref()). The
253 * type information is shared. The serialised data and the buffer
254 * management structure for that serialised data is shared by the
259 * <title>Summary</title>
261 * To put the entire example together, for our dictionary mapping
262 * strings to variants (with two entries, as given above), we are
263 * using 91 bytes of memory for type information, 29 byes of memory
264 * for the serialised data, 16 bytes for buffer management and 24
265 * bytes for the #GVariant instance, or a total of 160 bytes, plus
266 * malloc overhead. If we were to use g_variant_get_child_value() to
267 * access the two dictionary entries, we would use an additional 48
268 * bytes. If we were to have other dictionaries of the same type, we
269 * would use more memory for the serialised data and buffer
270 * management for those dictionaries, but the type information would
277 /* definition of GVariant structure is in gvariant-core.c */
279 /* this is a g_return_val_if_fail() for making
280 * sure a (GVariant *) has the required type.
282 #define TYPE_CHECK(value, TYPE, val) \
283 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
284 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
285 "g_variant_is_of_type (" #value \
290 /* Numeric Type Constructor/Getters {{{1 */
292 * g_variant_new_from_trusted:
293 * @type: the #GVariantType
294 * @data: the data to use
295 * @size: the size of @data
296 * @returns: a new floating #GVariant
298 * Constructs a new trusted #GVariant instance from the provided data.
299 * This is used to implement g_variant_new_* for all the basic types.
302 g_variant_new_from_trusted (const GVariantType *type,
309 buffer = g_buffer_new_from_data (data, size);
310 value = g_variant_new_from_buffer (type, buffer, TRUE);
311 g_buffer_unref (buffer);
317 * g_variant_new_boolean:
318 * @boolean: a #gboolean value
319 * @returns: a floating reference to a new boolean #GVariant instance
321 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
326 g_variant_new_boolean (gboolean value)
330 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
334 * g_variant_get_boolean:
335 * @value: a boolean #GVariant instance
336 * @returns: %TRUE or %FALSE
338 * Returns the boolean value of @value.
340 * It is an error to call this function with a @value of any type
341 * other than %G_VARIANT_TYPE_BOOLEAN.
346 g_variant_get_boolean (GVariant *value)
350 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
352 data = g_variant_get_data (value);
354 return data != NULL ? *data != 0 : FALSE;
357 /* the constructors and accessors for byte, int{16,32,64}, handles and
358 * doubles all look pretty much exactly the same, so we reduce
361 #define NUMERIC_TYPE(TYPE, type, ctype) \
362 GVariant *g_variant_new_##type (ctype value) { \
363 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
364 &value, sizeof value); \
366 ctype g_variant_get_##type (GVariant *value) { \
368 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
369 data = g_variant_get_data (value); \
370 return data != NULL ? *data : 0; \
375 * g_variant_new_byte:
376 * @byte: a #guint8 value
377 * @returns: a floating reference to a new byte #GVariant instance
379 * Creates a new byte #GVariant instance.
384 * g_variant_get_byte:
385 * @value: a byte #GVariant instance
386 * @returns: a #guchar
388 * Returns the byte value of @value.
390 * It is an error to call this function with a @value of any type
391 * other than %G_VARIANT_TYPE_BYTE.
395 NUMERIC_TYPE (BYTE, byte, guchar)
398 * g_variant_new_int16:
399 * @int16: a #gint16 value
400 * @returns: a floating reference to a new int16 #GVariant instance
402 * Creates a new int16 #GVariant instance.
407 * g_variant_get_int16:
408 * @value: a int16 #GVariant instance
409 * @returns: a #gint16
411 * Returns the 16-bit signed integer value of @value.
413 * It is an error to call this function with a @value of any type
414 * other than %G_VARIANT_TYPE_INT16.
418 NUMERIC_TYPE (INT16, int16, gint16)
421 * g_variant_new_uint16:
422 * @uint16: a #guint16 value
423 * @returns: a floating reference to a new uint16 #GVariant instance
425 * Creates a new uint16 #GVariant instance.
430 * g_variant_get_uint16:
431 * @value: a uint16 #GVariant instance
432 * @returns: a #guint16
434 * Returns the 16-bit unsigned integer value of @value.
436 * It is an error to call this function with a @value of any type
437 * other than %G_VARIANT_TYPE_UINT16.
441 NUMERIC_TYPE (UINT16, uint16, guint16)
444 * g_variant_new_int32:
445 * @int32: a #gint32 value
446 * @returns: a floating reference to a new int32 #GVariant instance
448 * Creates a new int32 #GVariant instance.
453 * g_variant_get_int32:
454 * @value: a int32 #GVariant instance
455 * @returns: a #gint32
457 * Returns the 32-bit signed 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_INT32.
464 NUMERIC_TYPE (INT32, int32, gint32)
467 * g_variant_new_uint32:
468 * @uint32: a #guint32 value
469 * @returns: a floating reference to a new uint32 #GVariant instance
471 * Creates a new uint32 #GVariant instance.
476 * g_variant_get_uint32:
477 * @value: a uint32 #GVariant instance
478 * @returns: a #guint32
480 * Returns the 32-bit unsigned integer value of @value.
482 * It is an error to call this function with a @value of any type
483 * other than %G_VARIANT_TYPE_UINT32.
487 NUMERIC_TYPE (UINT32, uint32, guint32)
490 * g_variant_new_int64:
491 * @int64: a #gint64 value
492 * @returns: a floating reference to a new int64 #GVariant instance
494 * Creates a new int64 #GVariant instance.
499 * g_variant_get_int64:
500 * @value: a int64 #GVariant instance
501 * @returns: a #gint64
503 * Returns the 64-bit signed integer value of @value.
505 * It is an error to call this function with a @value of any type
506 * other than %G_VARIANT_TYPE_INT64.
510 NUMERIC_TYPE (INT64, int64, gint64)
513 * g_variant_new_uint64:
514 * @uint64: a #guint64 value
515 * @returns: a floating reference to a new uint64 #GVariant instance
517 * Creates a new uint64 #GVariant instance.
522 * g_variant_get_uint64:
523 * @value: a uint64 #GVariant instance
524 * @returns: a #guint64
526 * Returns the 64-bit unsigned integer value of @value.
528 * It is an error to call this function with a @value of any type
529 * other than %G_VARIANT_TYPE_UINT64.
533 NUMERIC_TYPE (UINT64, uint64, guint64)
536 * g_variant_new_handle:
537 * @handle: a #gint32 value
538 * @returns: a floating reference to a new handle #GVariant instance
540 * Creates a new handle #GVariant instance.
542 * By convention, handles are indexes into an array of file descriptors
543 * that are sent alongside a DBus message. If you're not interacting
544 * with DBus, you probably don't need them.
549 * g_variant_get_handle:
550 * @value: a handle #GVariant instance
551 * @returns: a #gint32
553 * Returns the 32-bit signed integer value of @value.
555 * It is an error to call this function with a @value of any type other
556 * than %G_VARIANT_TYPE_HANDLE.
558 * By convention, handles are indexes into an array of file descriptors
559 * that are sent alongside a DBus message. If you're not interacting
560 * with DBus, you probably don't need them.
564 NUMERIC_TYPE (HANDLE, handle, gint32)
567 * g_variant_new_double:
568 * @floating: a #gdouble floating point value
569 * @returns: a floating reference to a new double #GVariant instance
571 * Creates a new double #GVariant instance.
576 * g_variant_get_double:
577 * @value: a double #GVariant instance
578 * @returns: a #gdouble
580 * Returns the double precision floating point value of @value.
582 * It is an error to call this function with a @value of any type
583 * other than %G_VARIANT_TYPE_DOUBLE.
587 NUMERIC_TYPE (DOUBLE, double, gdouble)
589 /* Container type Constructor / Deconstructors {{{1 */
591 * g_variant_new_maybe:
592 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
593 * @child: (allow-none): the child value, or %NULL
594 * @returns: a floating reference to a new #GVariant maybe instance
596 * Depending on if @child is %NULL, either wraps @child inside of a
597 * maybe container or creates a Nothing instance for the given @type.
599 * At least one of @child_type and @child must be non-%NULL.
600 * If @child_type is non-%NULL then it must be a definite type.
601 * If they are both non-%NULL then @child_type must be the type
604 * If @child is a floating reference (see g_variant_ref_sink()), the new
605 * instance takes ownership of @child.
610 g_variant_new_maybe (const GVariantType *child_type,
613 GVariantType *maybe_type;
616 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
618 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
619 g_return_val_if_fail (child_type == NULL || child == NULL ||
620 g_variant_is_of_type (child, child_type),
623 if (child_type == NULL)
624 child_type = g_variant_get_type (child);
626 maybe_type = g_variant_type_new_maybe (child_type);
633 children = g_new (GVariant *, 1);
634 children[0] = g_variant_ref_sink (child);
635 trusted = g_variant_is_trusted (children[0]);
637 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
640 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
642 g_variant_type_free (maybe_type);
648 * g_variant_get_maybe:
649 * @value: a maybe-typed value
650 * @returns: (allow-none): the contents of @value, or %NULL
652 * Given a maybe-typed #GVariant instance, extract its value. If the
653 * value is Nothing, then this function returns %NULL.
658 g_variant_get_maybe (GVariant *value)
660 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
662 if (g_variant_n_children (value))
663 return g_variant_get_child_value (value, 0);
669 * g_variant_new_variant:
670 * @value: a #GVariance instance
671 * @returns: a floating reference to a new variant #GVariant instance
673 * Boxes @value. The result is a #GVariant instance representing a
674 * variant containing the original value.
676 * If @child is a floating reference (see g_variant_ref_sink()), the new
677 * instance takes ownership of @child.
682 g_variant_new_variant (GVariant *value)
684 g_return_val_if_fail (value != NULL, NULL);
686 g_variant_ref_sink (value);
688 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
689 g_memdup (&value, sizeof value),
690 1, g_variant_is_trusted (value));
694 * g_variant_get_variant:
695 * @value: a variant #GVariance instance
696 * @returns: the item contained in the variant
698 * Unboxes @value. The result is the #GVariant instance that was
699 * contained in @value.
704 g_variant_get_variant (GVariant *value)
706 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
708 return g_variant_get_child_value (value, 0);
712 * g_variant_new_array:
713 * @child_type: (allow-none): the element type of the new array
714 * @children: (allow-none) (array length=n_children): an array of
715 * #GVariant pointers, the children
716 * @n_children: the length of @children
717 * @returns: a floating reference to a new #GVariant array
719 * Creates a new #GVariant array from @children.
721 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
722 * child type is determined by inspecting the first element of the
723 * @children array. If @child_type is non-%NULL then it must be a
726 * The items of the array are taken from the @children array. No entry
727 * in the @children array may be %NULL.
729 * All items in the array must have the same type, which must be the
730 * same as @child_type, if given.
732 * If the @children are floating references (see g_variant_ref_sink()), the
733 * new instance takes ownership of them as if via g_variant_ref_sink().
738 g_variant_new_array (const GVariantType *child_type,
739 GVariant * const *children,
742 GVariantType *array_type;
743 GVariant **my_children;
748 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
749 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
750 g_return_val_if_fail (child_type == NULL ||
751 g_variant_type_is_definite (child_type), NULL);
753 my_children = g_new (GVariant *, n_children);
756 if (child_type == NULL)
757 child_type = g_variant_get_type (children[0]);
758 array_type = g_variant_type_new_array (child_type);
760 for (i = 0; i < n_children; i++)
762 TYPE_CHECK (children[i], child_type, NULL);
763 my_children[i] = g_variant_ref_sink (children[i]);
764 trusted &= g_variant_is_trusted (children[i]);
767 value = g_variant_new_from_children (array_type, my_children,
768 n_children, trusted);
769 g_variant_type_free (array_type);
775 * g_variant_make_tuple_type:
776 * @children: (array length=n_children): an array of GVariant *
777 * @n_children: the length of @children
779 * Return the type of a tuple containing @children as its items.
781 static GVariantType *
782 g_variant_make_tuple_type (GVariant * const *children,
785 const GVariantType **types;
789 types = g_new (const GVariantType *, n_children);
791 for (i = 0; i < n_children; i++)
792 types[i] = g_variant_get_type (children[i]);
794 type = g_variant_type_new_tuple (types, n_children);
801 * g_variant_new_tuple:
802 * @children: (array length=n_children): the items to make the tuple out of
803 * @n_children: the length of @children
804 * @returns: a floating reference to a new #GVariant tuple
806 * Creates a new tuple #GVariant out of the items in @children. The
807 * type is determined from the types of @children. No entry in the
808 * @children array may be %NULL.
810 * If @n_children is 0 then the unit tuple is constructed.
812 * If the @children are floating references (see g_variant_ref_sink()), the
813 * new instance takes ownership of them as if via g_variant_ref_sink().
818 g_variant_new_tuple (GVariant * const *children,
821 GVariantType *tuple_type;
822 GVariant **my_children;
827 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
829 my_children = g_new (GVariant *, n_children);
832 for (i = 0; i < n_children; i++)
834 my_children[i] = g_variant_ref_sink (children[i]);
835 trusted &= g_variant_is_trusted (children[i]);
838 tuple_type = g_variant_make_tuple_type (children, n_children);
839 value = g_variant_new_from_children (tuple_type, my_children,
840 n_children, trusted);
841 g_variant_type_free (tuple_type);
847 * g_variant_make_dict_entry_type:
848 * @key: a #GVariant, the key
849 * @val: a #GVariant, the value
851 * Return the type of a dictionary entry containing @key and @val as its
854 static GVariantType *
855 g_variant_make_dict_entry_type (GVariant *key,
858 return g_variant_type_new_dict_entry (g_variant_get_type (key),
859 g_variant_get_type (val));
863 * g_variant_new_dict_entry:
864 * @key: a basic #GVariant, the key
865 * @value: a #GVariant, the value
866 * @returns: a floating reference to a new dictionary entry #GVariant
868 * Creates a new dictionary entry #GVariant. @key and @value must be
871 * @key must be a value of a basic type (ie: not a container).
873 * If the @key or @value are floating references (see g_variant_ref_sink()),
874 * the new instance takes ownership of them as if via g_variant_ref_sink().
879 g_variant_new_dict_entry (GVariant *key,
882 GVariantType *dict_type;
886 g_return_val_if_fail (key != NULL && value != NULL, NULL);
887 g_return_val_if_fail (!g_variant_is_container (key), NULL);
889 children = g_new (GVariant *, 2);
890 children[0] = g_variant_ref_sink (key);
891 children[1] = g_variant_ref_sink (value);
892 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
894 dict_type = g_variant_make_dict_entry_type (key, value);
895 value = g_variant_new_from_children (dict_type, children, 2, trusted);
896 g_variant_type_free (dict_type);
903 * @dictionary: a dictionary #GVariant
904 * @key: the key to lookup in the dictionary
905 * @format_string: a GVariant format string
906 * @...: the arguments to unpack the value into
908 * Looks up a value in a dictionary #GVariant.
910 * This function is a wrapper around g_variant_lookup_value() and
911 * g_variant_get(). In the case that %NULL would have been returned,
912 * this function returns %FALSE. Otherwise, it unpacks the returned
913 * value and returns %TRUE.
915 * See g_variant_get() for information about @format_string.
917 * Returns: %TRUE if a value was unpacked
922 g_variant_lookup (GVariant *dictionary,
924 const gchar *format_string,
931 g_variant_get_data (dictionary);
933 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
934 value = g_variant_lookup_value (dictionary, key, type);
935 g_variant_type_free (type);
941 va_start (ap, format_string);
942 g_variant_get_va (value, format_string, NULL, &ap);
943 g_variant_unref (value);
955 * @dictionary: a dictionary #GVariant
956 * @key: the key to lookup in the dictionary
957 * @expected_type: a #GVariantType, or %NULL
959 * Looks up a value in a dictionary #GVariant.
961 * This function works with dictionaries of the type
962 * <literal>a{s*}</literal> (and equally well with type
963 * <literal>a{o*}</literal>, but we only further discuss the string case
964 * for sake of clarity).
966 * In the event that @dictionary has the type <literal>a{sv}</literal>,
967 * the @expected_type string specifies what type of value is expected to
968 * be inside of the variant. If the value inside the variant has a
969 * different type then %NULL is returned. In the event that @dictionary
970 * has a value type other than <literal>v</literal> then @expected_type
971 * must directly match the key type and it is used to unpack the value
972 * directly or an error occurs.
974 * In either case, if @key is not found in @dictionary, %NULL is
977 * If the key is found and the value has the correct type, it is
978 * returned. If @expected_type was specified then any non-%NULL return
979 * value will have this type.
981 * Returns: the value of the dictionary key, or %NULL
986 g_variant_lookup_value (GVariant *dictionary,
988 const GVariantType *expected_type)
994 g_return_val_if_fail (g_variant_is_of_type (dictionary,
995 G_VARIANT_TYPE ("a{s*}")) ||
996 g_variant_is_of_type (dictionary,
997 G_VARIANT_TYPE ("a{o*}")),
1000 g_variant_iter_init (&iter, dictionary);
1002 while ((entry = g_variant_iter_next_value (&iter)))
1004 GVariant *entry_key;
1007 entry_key = g_variant_get_child_value (entry, 0);
1008 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1009 g_variant_unref (entry_key);
1014 g_variant_unref (entry);
1020 value = g_variant_get_child_value (entry, 1);
1021 g_variant_unref (entry);
1023 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1027 tmp = g_variant_get_variant (value);
1028 g_variant_unref (value);
1030 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1032 g_variant_unref (tmp);
1039 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1040 g_variant_is_of_type (value, expected_type), NULL);
1046 * g_variant_get_fixed_array:
1047 * @value: a #GVariant array with fixed-sized elements
1048 * @n_elements: a pointer to the location to store the number of items
1049 * @element_size: the size of each element
1050 * @returns: (array length=n_elements): a pointer to the fixed array
1052 * Provides access to the serialised data for an array of fixed-sized
1055 * @value must be an array with fixed-sized elements. Numeric types are
1056 * fixed-size as are tuples containing only other fixed-sized types.
1058 * @element_size must be the size of a single element in the array. For
1059 * example, if calling this function for an array of 32 bit integers,
1060 * you might say <code>sizeof (gint32)</code>. This value isn't used
1061 * except for the purpose of a double-check that the form of the
1062 * seralised data matches the caller's expectation.
1064 * @n_elements, which must be non-%NULL is set equal to the number of
1065 * items in the array.
1070 g_variant_get_fixed_array (GVariant *value,
1074 GVariantTypeInfo *array_info;
1075 gsize array_element_size;
1079 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1081 g_return_val_if_fail (n_elements != NULL, NULL);
1082 g_return_val_if_fail (element_size > 0, NULL);
1084 array_info = g_variant_get_type_info (value);
1085 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1087 g_return_val_if_fail (array_element_size, NULL);
1089 if G_UNLIKELY (array_element_size != element_size)
1091 if (array_element_size)
1092 g_critical ("g_variant_get_fixed_array: assertion "
1093 "`g_variant_array_has_fixed_size (value, element_size)' "
1094 "failed: array size %"G_GSIZE_FORMAT" does not match "
1095 "given element_size %"G_GSIZE_FORMAT".",
1096 array_element_size, element_size);
1098 g_critical ("g_variant_get_fixed_array: assertion "
1099 "`g_variant_array_has_fixed_size (value, element_size)' "
1100 "failed: array does not have fixed size.");
1103 data = g_variant_get_data (value);
1104 size = g_variant_get_size (value);
1106 if (size % element_size)
1109 *n_elements = size / element_size;
1117 /* String type constructor/getters/validation {{{1 */
1119 * g_variant_new_string:
1120 * @string: a normal utf8 nul-terminated string
1121 * @returns: a floating reference to a new string #GVariant instance
1123 * Creates a string #GVariant with the contents of @string.
1125 * @string must be valid utf8.
1130 g_variant_new_string (const gchar *string)
1132 g_return_val_if_fail (string != NULL, NULL);
1133 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1135 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1136 string, strlen (string) + 1);
1140 * g_variant_new_object_path:
1141 * @object_path: a normal C nul-terminated string
1142 * @returns: a floating reference to a new object path #GVariant instance
1144 * Creates a DBus object path #GVariant with the contents of @string.
1145 * @string must be a valid DBus object path. Use
1146 * g_variant_is_object_path() if you're not sure.
1151 g_variant_new_object_path (const gchar *object_path)
1153 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1155 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1156 object_path, strlen (object_path) + 1);
1160 * g_variant_is_object_path:
1161 * @string: a normal C nul-terminated string
1162 * @returns: %TRUE if @string is a DBus object path
1164 * Determines if a given string is a valid DBus object path. You
1165 * should ensure that a string is a valid DBus object path before
1166 * passing it to g_variant_new_object_path().
1168 * A valid object path starts with '/' followed by zero or more
1169 * sequences of characters separated by '/' characters. Each sequence
1170 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1171 * (including the one following the final '/' character) may be empty.
1176 g_variant_is_object_path (const gchar *string)
1178 g_return_val_if_fail (string != NULL, FALSE);
1180 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1184 * g_variant_new_signature:
1185 * @signature: a normal C nul-terminated string
1186 * @returns: a floating reference to a new signature #GVariant instance
1188 * Creates a DBus type signature #GVariant with the contents of
1189 * @string. @string must be a valid DBus type signature. Use
1190 * g_variant_is_signature() if you're not sure.
1195 g_variant_new_signature (const gchar *signature)
1197 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1199 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1200 signature, strlen (signature) + 1);
1204 * g_variant_is_signature:
1205 * @string: a normal C nul-terminated string
1206 * @returns: %TRUE if @string is a DBus type signature
1208 * Determines if a given string is a valid DBus type signature. You
1209 * should ensure that a string is a valid DBus type signature before
1210 * passing it to g_variant_new_signature().
1212 * DBus type signatures consist of zero or more definite #GVariantType
1213 * strings in sequence.
1218 g_variant_is_signature (const gchar *string)
1220 g_return_val_if_fail (string != NULL, FALSE);
1222 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1226 * g_variant_get_string:
1227 * @value: a string #GVariant instance
1228 * @length: (allow-none) (default NULL) (out): a pointer to a #gsize,
1229 * to store the length
1230 * @returns: the constant string, utf8 encoded
1232 * Returns the string value of a #GVariant instance with a string
1233 * type. This includes the types %G_VARIANT_TYPE_STRING,
1234 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1236 * The string will always be utf8 encoded.
1238 * If @length is non-%NULL then the length of the string (in bytes) is
1239 * returned there. For trusted values, this information is already
1240 * known. For untrusted values, a strlen() will be performed.
1242 * It is an error to call this function with a @value of any type
1243 * other than those three.
1245 * The return value remains valid as long as @value exists.
1250 g_variant_get_string (GVariant *value,
1256 g_return_val_if_fail (value != NULL, NULL);
1257 g_return_val_if_fail (
1258 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1259 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1260 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1262 data = g_variant_get_data (value);
1263 size = g_variant_get_size (value);
1265 if (!g_variant_is_trusted (value))
1267 switch (g_variant_classify (value))
1269 case G_VARIANT_CLASS_STRING:
1270 if (g_variant_serialiser_is_string (data, size))
1277 case G_VARIANT_CLASS_OBJECT_PATH:
1278 if (g_variant_serialiser_is_object_path (data, size))
1285 case G_VARIANT_CLASS_SIGNATURE:
1286 if (g_variant_serialiser_is_signature (data, size))
1294 g_assert_not_reached ();
1305 * g_variant_dup_string:
1306 * @value: a string #GVariant instance
1307 * @length: a pointer to a #gsize, to store the length
1308 * @returns: a newly allocated string, utf8 encoded
1310 * Similar to g_variant_get_string() except that instead of returning
1311 * a constant string, the string is duplicated.
1313 * The string will always be utf8 encoded.
1315 * The return value must be freed using g_free().
1320 g_variant_dup_string (GVariant *value,
1323 return g_strdup (g_variant_get_string (value, length));
1327 * g_variant_new_strv:
1328 * @strv: (array length=length) (element-type utf8): an array of strings
1329 * @length: the length of @strv, or -1
1330 * @returns: a new floating #GVariant instance
1332 * Constructs an array of strings #GVariant from the given array of
1335 * If @length is -1 then @strv is %NULL-terminated.
1340 g_variant_new_strv (const gchar * const *strv,
1346 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1349 length = g_strv_length ((gchar **) strv);
1351 strings = g_new (GVariant *, length);
1352 for (i = 0; i < length; i++)
1353 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1355 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1356 strings, length, TRUE);
1360 * g_variant_get_strv:
1361 * @value: an array of strings #GVariant
1362 * @length: (allow-none): the length of the result, or %NULL
1363 * @returns: (array length=length) (transfer container): an array of constant
1366 * Gets the contents of an array of strings #GVariant. This call
1367 * makes a shallow copy; the return result should be released with
1368 * g_free(), but the individual strings must not be modified.
1370 * If @length is non-%NULL then the number of elements in the result
1371 * is stored there. In any case, the resulting array will be
1374 * For an empty array, @length will be set to 0 and a pointer to a
1375 * %NULL pointer will be returned.
1380 g_variant_get_strv (GVariant *value,
1387 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1389 g_variant_get_data (value);
1390 n = g_variant_n_children (value);
1391 strv = g_new (const gchar *, n + 1);
1393 for (i = 0; i < n; i++)
1397 string = g_variant_get_child_value (value, i);
1398 strv[i] = g_variant_get_string (string, NULL);
1399 g_variant_unref (string);
1410 * g_variant_dup_strv:
1411 * @value: an array of strings #GVariant
1412 * @length: (allow-none): the length of the result, or %NULL
1413 * @returns: (array length=length): an array of strings
1415 * Gets the contents of an array of strings #GVariant. This call
1416 * makes a deep copy; the return result should be released with
1419 * If @length is non-%NULL then the number of elements in the result
1420 * is stored there. In any case, the resulting array will be
1423 * For an empty array, @length will be set to 0 and a pointer to a
1424 * %NULL pointer will be returned.
1429 g_variant_dup_strv (GVariant *value,
1436 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1438 n = g_variant_n_children (value);
1439 strv = g_new (gchar *, n + 1);
1441 for (i = 0; i < n; i++)
1445 string = g_variant_get_child_value (value, i);
1446 strv[i] = g_variant_dup_string (string, NULL);
1447 g_variant_unref (string);
1458 * g_variant_new_bytestring:
1459 * @string: a normal nul-terminated string in no particular encoding
1460 * @returns: a floating reference to a new bytestring #GVariant instance
1462 * Creates an array-of-bytes #GVariant with the contents of @string.
1463 * This function is just like g_variant_new_string() except that the
1464 * string need not be valid utf8.
1466 * The nul terminator character at the end of the string is stored in
1472 g_variant_new_bytestring (const gchar *string)
1474 g_return_val_if_fail (string != NULL, NULL);
1476 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1477 string, strlen (string) + 1);
1481 * g_variant_get_bytestring:
1482 * @value: an array-of-bytes #GVariant instance
1483 * @returns: the constant string
1485 * Returns the string value of a #GVariant instance with an
1486 * array-of-bytes type. The string has no particular encoding.
1488 * If the array does not end with a nul terminator character, the empty
1489 * string is returned. For this reason, you can always trust that a
1490 * non-%NULL nul-terminated string will be returned by this function.
1492 * If the array contains a nul terminator character somewhere other than
1493 * the last byte then the returned string is the string, up to the first
1494 * such nul character.
1496 * It is an error to call this function with a @value that is not an
1499 * The return value remains valid as long as @value exists.
1504 g_variant_get_bytestring (GVariant *value)
1506 const gchar *string;
1509 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1511 /* Won't be NULL since this is an array type */
1512 string = g_variant_get_data (value);
1513 size = g_variant_get_size (value);
1515 if (size && string[size - 1] == '\0')
1522 * g_variant_dup_bytestring:
1523 * @value: an array-of-bytes #GVariant instance
1524 * @length: (allow-none) (default NULL): a pointer to a #gsize, to store
1525 * the length (not including the nul terminator)
1526 * @returns: a newly allocated string
1528 * Similar to g_variant_get_bytestring() except that instead of
1529 * returning a constant string, the string is duplicated.
1531 * The return value must be freed using g_free().
1536 g_variant_dup_bytestring (GVariant *value,
1539 const gchar *original = g_variant_get_bytestring (value);
1542 /* don't crash in case get_bytestring() had an assert failure */
1543 if (original == NULL)
1546 size = strlen (original);
1551 return g_memdup (original, size + 1);
1555 * g_variant_new_bytestring_array:
1556 * @strv: (array length=length): an array of strings
1557 * @length: the length of @strv, or -1
1558 * @returns: a new floating #GVariant instance
1560 * Constructs an array of bytestring #GVariant from the given array of
1563 * If @length is -1 then @strv is %NULL-terminated.
1568 g_variant_new_bytestring_array (const gchar * const *strv,
1574 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1577 length = g_strv_length ((gchar **) strv);
1579 strings = g_new (GVariant *, length);
1580 for (i = 0; i < length; i++)
1581 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1583 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1584 strings, length, TRUE);
1588 * g_variant_get_bytestring_array:
1589 * @value: an array of array of bytes #GVariant ('aay')
1590 * @length: (allow-none): the length of the result, or %NULL
1591 * @returns: (array length=length): an array of constant strings
1593 * Gets the contents of an array of array of bytes #GVariant. This call
1594 * makes a shallow copy; the return result should be released with
1595 * g_free(), but the individual strings must not be modified.
1597 * If @length is non-%NULL then the number of elements in the result is
1598 * stored there. In any case, the resulting array will be
1601 * For an empty array, @length will be set to 0 and a pointer to a
1602 * %NULL pointer will be returned.
1607 g_variant_get_bytestring_array (GVariant *value,
1614 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1616 g_variant_get_data (value);
1617 n = g_variant_n_children (value);
1618 strv = g_new (const gchar *, n + 1);
1620 for (i = 0; i < n; i++)
1624 string = g_variant_get_child_value (value, i);
1625 strv[i] = g_variant_get_bytestring (string);
1626 g_variant_unref (string);
1637 * g_variant_dup_bytestring_array:
1638 * @value: an array of array of bytes #GVariant ('aay')
1639 * @length: (allow-none): the length of the result, or %NULL
1640 * @returns: (array length=length): an array of strings
1642 * Gets the contents of an array of array of bytes #GVariant. This call
1643 * makes a deep copy; the return result should be released with
1646 * If @length is non-%NULL then the number of elements in the result is
1647 * stored there. In any case, the resulting array will be
1650 * For an empty array, @length will be set to 0 and a pointer to a
1651 * %NULL pointer will be returned.
1656 g_variant_dup_bytestring_array (GVariant *value,
1663 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1665 g_variant_get_data (value);
1666 n = g_variant_n_children (value);
1667 strv = g_new (gchar *, n + 1);
1669 for (i = 0; i < n; i++)
1673 string = g_variant_get_child_value (value, i);
1674 strv[i] = g_variant_dup_bytestring (string, NULL);
1675 g_variant_unref (string);
1685 /* Type checking and querying {{{1 */
1687 * g_variant_get_type:
1688 * @value: a #GVariant
1689 * @returns: a #GVariantType
1691 * Determines the type of @value.
1693 * The return value is valid for the lifetime of @value and must not
1698 const GVariantType *
1699 g_variant_get_type (GVariant *value)
1701 GVariantTypeInfo *type_info;
1703 g_return_val_if_fail (value != NULL, NULL);
1705 type_info = g_variant_get_type_info (value);
1707 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1711 * g_variant_get_type_string:
1712 * @value: a #GVariant
1713 * @returns: the type string for the type of @value
1715 * Returns the type string of @value. Unlike the result of calling
1716 * g_variant_type_peek_string(), this string is nul-terminated. This
1717 * string belongs to #GVariant and must not be freed.
1722 g_variant_get_type_string (GVariant *value)
1724 GVariantTypeInfo *type_info;
1726 g_return_val_if_fail (value != NULL, NULL);
1728 type_info = g_variant_get_type_info (value);
1730 return g_variant_type_info_get_type_string (type_info);
1734 * g_variant_is_of_type:
1735 * @value: a #GVariant instance
1736 * @type: a #GVariantType
1737 * @returns: %TRUE if the type of @value matches @type
1739 * Checks if a value has a type matching the provided type.
1744 g_variant_is_of_type (GVariant *value,
1745 const GVariantType *type)
1747 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1751 * g_variant_is_container:
1752 * @value: a #GVariant instance
1753 * @returns: %TRUE if @value is a container
1755 * Checks if @value is a container.
1758 g_variant_is_container (GVariant *value)
1760 return g_variant_type_is_container (g_variant_get_type (value));
1765 * g_variant_classify:
1766 * @value: a #GVariant
1767 * @returns: the #GVariantClass of @value
1769 * Classifies @value according to its top-level type.
1775 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
1776 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
1777 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
1778 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
1779 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
1780 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
1781 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
1782 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
1783 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
1784 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
1786 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
1787 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a DBus object path
1789 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a DBus signature string.
1790 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
1791 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
1792 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
1793 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
1794 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
1796 * The range of possible top-level types of #GVariant instances.
1801 g_variant_classify (GVariant *value)
1803 g_return_val_if_fail (value != NULL, 0);
1805 return *g_variant_get_type_string (value);
1808 /* Pretty printer {{{1 */
1810 * g_variant_print_string:
1811 * @value: a #GVariant
1812 * @string: (allow-none) (default NULL): a #GString, or %NULL
1813 * @type_annotate: %TRUE if type information should be included in
1815 * @returns: a #GString containing the string
1817 * Behaves as g_variant_print(), but operates on a #GString.
1819 * If @string is non-%NULL then it is appended to and returned. Else,
1820 * a new empty #GString is allocated and it is returned.
1825 g_variant_print_string (GVariant *value,
1827 gboolean type_annotate)
1829 if G_UNLIKELY (string == NULL)
1830 string = g_string_new (NULL);
1832 switch (g_variant_classify (value))
1834 case G_VARIANT_CLASS_MAYBE:
1836 g_string_append_printf (string, "@%s ",
1837 g_variant_get_type_string (value));
1839 if (g_variant_n_children (value))
1841 gchar *printed_child;
1846 * Consider the case of the type "mmi". In this case we could
1847 * write "just just 4", but "4" alone is totally unambiguous,
1848 * so we try to drop "just" where possible.
1850 * We have to be careful not to always drop "just", though,
1851 * since "nothing" needs to be distinguishable from "just
1852 * nothing". The case where we need to ensure we keep the
1853 * "just" is actually exactly the case where we have a nested
1856 * Instead of searching for that nested Nothing, we just print
1857 * the contained value into a separate string and see if we
1858 * end up with "nothing" at the end of it. If so, we need to
1859 * add "just" at our level.
1861 element = g_variant_get_child_value (value, 0);
1862 printed_child = g_variant_print (element, FALSE);
1863 g_variant_unref (element);
1865 if (g_str_has_suffix (printed_child, "nothing"))
1866 g_string_append (string, "just ");
1867 g_string_append (string, printed_child);
1868 g_free (printed_child);
1871 g_string_append (string, "nothing");
1875 case G_VARIANT_CLASS_ARRAY:
1876 /* it's an array so the first character of the type string is 'a'
1878 * if the first two characters are 'ay' then it's a bytestring.
1879 * under certain conditions we print those as strings.
1881 if (g_variant_get_type_string (value)[1] == 'y')
1887 /* first determine if it is a byte string.
1888 * that's when there's a single nul character: at the end.
1890 str = g_variant_get_data (value);
1891 size = g_variant_get_size (value);
1893 for (i = 0; i < size; i++)
1897 /* first nul byte is the last byte -> it's a byte string. */
1900 gchar *escaped = g_strescape (str, NULL);
1902 /* use double quotes only if a ' is in the string */
1903 if (strchr (str, '\''))
1904 g_string_append_printf (string, "b\"%s\"", escaped);
1906 g_string_append_printf (string, "b'%s'", escaped);
1913 /* fall through and handle normally... */;
1917 * if the first two characters are 'a{' then it's an array of
1918 * dictionary entries (ie: a dictionary) so we print that
1921 if (g_variant_get_type_string (value)[1] == '{')
1924 const gchar *comma = "";
1927 if ((n = g_variant_n_children (value)) == 0)
1930 g_string_append_printf (string, "@%s ",
1931 g_variant_get_type_string (value));
1932 g_string_append (string, "{}");
1936 g_string_append_c (string, '{');
1937 for (i = 0; i < n; i++)
1939 GVariant *entry, *key, *val;
1941 g_string_append (string, comma);
1944 entry = g_variant_get_child_value (value, i);
1945 key = g_variant_get_child_value (entry, 0);
1946 val = g_variant_get_child_value (entry, 1);
1947 g_variant_unref (entry);
1949 g_variant_print_string (key, string, type_annotate);
1950 g_variant_unref (key);
1951 g_string_append (string, ": ");
1952 g_variant_print_string (val, string, type_annotate);
1953 g_variant_unref (val);
1954 type_annotate = FALSE;
1956 g_string_append_c (string, '}');
1959 /* normal (non-dictionary) array */
1961 const gchar *comma = "";
1964 if ((n = g_variant_n_children (value)) == 0)
1967 g_string_append_printf (string, "@%s ",
1968 g_variant_get_type_string (value));
1969 g_string_append (string, "[]");
1973 g_string_append_c (string, '[');
1974 for (i = 0; i < n; i++)
1978 g_string_append (string, comma);
1981 element = g_variant_get_child_value (value, i);
1983 g_variant_print_string (element, string, type_annotate);
1984 g_variant_unref (element);
1985 type_annotate = FALSE;
1987 g_string_append_c (string, ']');
1992 case G_VARIANT_CLASS_TUPLE:
1996 n = g_variant_n_children (value);
1998 g_string_append_c (string, '(');
1999 for (i = 0; i < n; i++)
2003 element = g_variant_get_child_value (value, i);
2004 g_variant_print_string (element, string, type_annotate);
2005 g_string_append (string, ", ");
2006 g_variant_unref (element);
2009 /* for >1 item: remove final ", "
2010 * for 1 item: remove final " ", but leave the ","
2011 * for 0 items: there is only "(", so remove nothing
2013 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2014 g_string_append_c (string, ')');
2018 case G_VARIANT_CLASS_DICT_ENTRY:
2022 g_string_append_c (string, '{');
2024 element = g_variant_get_child_value (value, 0);
2025 g_variant_print_string (element, string, type_annotate);
2026 g_variant_unref (element);
2028 g_string_append (string, ", ");
2030 element = g_variant_get_child_value (value, 1);
2031 g_variant_print_string (element, string, type_annotate);
2032 g_variant_unref (element);
2034 g_string_append_c (string, '}');
2038 case G_VARIANT_CLASS_VARIANT:
2040 GVariant *child = g_variant_get_variant (value);
2042 /* Always annotate types in nested variants, because they are
2043 * (by nature) of variable type.
2045 g_string_append_c (string, '<');
2046 g_variant_print_string (child, string, TRUE);
2047 g_string_append_c (string, '>');
2049 g_variant_unref (child);
2053 case G_VARIANT_CLASS_BOOLEAN:
2054 if (g_variant_get_boolean (value))
2055 g_string_append (string, "true");
2057 g_string_append (string, "false");
2060 case G_VARIANT_CLASS_STRING:
2062 const gchar *str = g_variant_get_string (value, NULL);
2063 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2065 g_string_append_c (string, quote);
2069 gunichar c = g_utf8_get_char (str);
2071 if (c == quote || c == '\\')
2072 g_string_append_c (string, '\\');
2074 if (g_unichar_isprint (c))
2075 g_string_append_unichar (string, c);
2079 g_string_append_c (string, '\\');
2084 g_string_append_c (string, 'a');
2088 g_string_append_c (string, 'b');
2092 g_string_append_c (string, 'f');
2096 g_string_append_c (string, 'n');
2100 g_string_append_c (string, 'r');
2104 g_string_append_c (string, 't');
2108 g_string_append_c (string, 'v');
2112 g_string_append_printf (string, "u%04x", c);
2116 g_string_append_printf (string, "U%08x", c);
2119 str = g_utf8_next_char (str);
2122 g_string_append_c (string, quote);
2126 case G_VARIANT_CLASS_BYTE:
2128 g_string_append (string, "byte ");
2129 g_string_append_printf (string, "0x%02x",
2130 g_variant_get_byte (value));
2133 case G_VARIANT_CLASS_INT16:
2135 g_string_append (string, "int16 ");
2136 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2137 g_variant_get_int16 (value));
2140 case G_VARIANT_CLASS_UINT16:
2142 g_string_append (string, "uint16 ");
2143 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2144 g_variant_get_uint16 (value));
2147 case G_VARIANT_CLASS_INT32:
2148 /* Never annotate this type because it is the default for numbers
2149 * (and this is a *pretty* printer)
2151 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2152 g_variant_get_int32 (value));
2155 case G_VARIANT_CLASS_HANDLE:
2157 g_string_append (string, "handle ");
2158 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2159 g_variant_get_handle (value));
2162 case G_VARIANT_CLASS_UINT32:
2164 g_string_append (string, "uint32 ");
2165 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2166 g_variant_get_uint32 (value));
2169 case G_VARIANT_CLASS_INT64:
2171 g_string_append (string, "int64 ");
2172 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2173 g_variant_get_int64 (value));
2176 case G_VARIANT_CLASS_UINT64:
2178 g_string_append (string, "uint64 ");
2179 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2180 g_variant_get_uint64 (value));
2183 case G_VARIANT_CLASS_DOUBLE:
2188 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2190 for (i = 0; buffer[i]; i++)
2191 if (buffer[i] == '.' || buffer[i] == 'e' ||
2192 buffer[i] == 'n' || buffer[i] == 'N')
2195 /* if there is no '.' or 'e' in the float then add one */
2196 if (buffer[i] == '\0')
2203 g_string_append (string, buffer);
2207 case G_VARIANT_CLASS_OBJECT_PATH:
2209 g_string_append (string, "objectpath ");
2210 g_string_append_printf (string, "\'%s\'",
2211 g_variant_get_string (value, NULL));
2214 case G_VARIANT_CLASS_SIGNATURE:
2216 g_string_append (string, "signature ");
2217 g_string_append_printf (string, "\'%s\'",
2218 g_variant_get_string (value, NULL));
2222 g_assert_not_reached ();
2230 * @value: a #GVariant
2231 * @type_annotate: %TRUE if type information should be included in
2233 * @returns: a newly-allocated string holding the result.
2235 * Pretty-prints @value in the format understood by g_variant_parse().
2237 * If @type_annotate is %TRUE, then type information is included in
2241 g_variant_print (GVariant *value,
2242 gboolean type_annotate)
2244 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2248 /* Hash, Equal, Compare {{{1 */
2251 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2252 * @returns: a hash value corresponding to @value
2254 * Generates a hash value for a #GVariant instance.
2256 * The output of this function is guaranteed to be the same for a given
2257 * value only per-process. It may change between different processor
2258 * architectures or even different versions of GLib. Do not use this
2259 * function as a basis for building protocols or file formats.
2261 * The type of @value is #gconstpointer only to allow use of this
2262 * function with #GHashTable. @value must be a #GVariant.
2267 g_variant_hash (gconstpointer value_)
2269 GVariant *value = (GVariant *) value_;
2271 switch (g_variant_classify (value))
2273 case G_VARIANT_CLASS_STRING:
2274 case G_VARIANT_CLASS_OBJECT_PATH:
2275 case G_VARIANT_CLASS_SIGNATURE:
2276 return g_str_hash (g_variant_get_string (value, NULL));
2278 case G_VARIANT_CLASS_BOOLEAN:
2279 /* this is a very odd thing to hash... */
2280 return g_variant_get_boolean (value);
2282 case G_VARIANT_CLASS_BYTE:
2283 return g_variant_get_byte (value);
2285 case G_VARIANT_CLASS_INT16:
2286 case G_VARIANT_CLASS_UINT16:
2290 ptr = g_variant_get_data (value);
2298 case G_VARIANT_CLASS_INT32:
2299 case G_VARIANT_CLASS_UINT32:
2300 case G_VARIANT_CLASS_HANDLE:
2304 ptr = g_variant_get_data (value);
2312 case G_VARIANT_CLASS_INT64:
2313 case G_VARIANT_CLASS_UINT64:
2314 case G_VARIANT_CLASS_DOUBLE:
2315 /* need a separate case for these guys because otherwise
2316 * performance could be quite bad on big endian systems
2321 ptr = g_variant_get_data (value);
2324 return ptr[0] + ptr[1];
2330 g_return_val_if_fail (!g_variant_is_container (value), 0);
2331 g_assert_not_reached ();
2337 * @one: (type GVariant): a #GVariant instance
2338 * @two: (type GVariant): a #GVariant instance
2339 * @returns: %TRUE if @one and @two are equal
2341 * Checks if @one and @two have the same type and value.
2343 * The types of @one and @two are #gconstpointer only to allow use of
2344 * this function with #GHashTable. They must each be a #GVariant.
2349 g_variant_equal (gconstpointer one,
2354 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2356 if (g_variant_get_type_info ((GVariant *) one) !=
2357 g_variant_get_type_info ((GVariant *) two))
2360 /* if both values are trusted to be in their canonical serialised form
2361 * then a simple memcmp() of their serialised data will answer the
2364 * if not, then this might generate a false negative (since it is
2365 * possible for two different byte sequences to represent the same
2366 * value). for now we solve this by pretty-printing both values and
2367 * comparing the result.
2369 if (g_variant_is_trusted ((GVariant *) one) &&
2370 g_variant_is_trusted ((GVariant *) two))
2372 gconstpointer data_one, data_two;
2373 gsize size_one, size_two;
2375 size_one = g_variant_get_size ((GVariant *) one);
2376 size_two = g_variant_get_size ((GVariant *) two);
2378 if (size_one != size_two)
2381 data_one = g_variant_get_data ((GVariant *) one);
2382 data_two = g_variant_get_data ((GVariant *) two);
2384 equal = memcmp (data_one, data_two, size_one) == 0;
2388 gchar *strone, *strtwo;
2390 strone = g_variant_print ((GVariant *) one, FALSE);
2391 strtwo = g_variant_print ((GVariant *) two, FALSE);
2392 equal = strcmp (strone, strtwo) == 0;
2401 * g_variant_compare:
2402 * @one: (type GVariant): a basic-typed #GVariant instance
2403 * @two: (type GVariant): a #GVariant instance of the same type
2404 * @returns: negative value if a < b;
2406 * positive value if a > b.
2408 * Compares @one and @two.
2410 * The types of @one and @two are #gconstpointer only to allow use of
2411 * this function with #GTree, #GPtrArray, etc. They must each be a
2414 * Comparison is only defined for basic types (ie: booleans, numbers,
2415 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2416 * ordered in the usual way. Strings are in ASCII lexographical order.
2418 * It is a programmer error to attempt to compare container values or
2419 * two values that have types that are not exactly equal. For example,
2420 * you can not compare a 32-bit signed integer with a 32-bit unsigned
2421 * integer. Also note that this function is not particularly
2422 * well-behaved when it comes to comparison of doubles; in particular,
2423 * the handling of incomparable values (ie: NaN) is undefined.
2425 * If you only require an equality comparison, g_variant_equal() is more
2431 g_variant_compare (gconstpointer one,
2434 GVariant *a = (GVariant *) one;
2435 GVariant *b = (GVariant *) two;
2437 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2439 switch (g_variant_classify (a))
2441 case G_VARIANT_CLASS_BYTE:
2442 return ((gint) g_variant_get_byte (a)) -
2443 ((gint) g_variant_get_byte (b));
2445 case G_VARIANT_CLASS_INT16:
2446 return ((gint) g_variant_get_int16 (a)) -
2447 ((gint) g_variant_get_int16 (b));
2449 case G_VARIANT_CLASS_UINT16:
2450 return ((gint) g_variant_get_uint16 (a)) -
2451 ((gint) g_variant_get_uint16 (b));
2453 case G_VARIANT_CLASS_INT32:
2455 gint32 a_val = g_variant_get_int32 (a);
2456 gint32 b_val = g_variant_get_int32 (b);
2458 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2461 case G_VARIANT_CLASS_UINT32:
2463 guint32 a_val = g_variant_get_uint32 (a);
2464 guint32 b_val = g_variant_get_uint32 (b);
2466 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2469 case G_VARIANT_CLASS_INT64:
2471 gint64 a_val = g_variant_get_int64 (a);
2472 gint64 b_val = g_variant_get_int64 (b);
2474 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2477 case G_VARIANT_CLASS_UINT64:
2479 guint64 a_val = g_variant_get_int32 (a);
2480 guint64 b_val = g_variant_get_int32 (b);
2482 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2485 case G_VARIANT_CLASS_DOUBLE:
2487 gdouble a_val = g_variant_get_double (a);
2488 gdouble b_val = g_variant_get_double (b);
2490 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2493 case G_VARIANT_CLASS_STRING:
2494 case G_VARIANT_CLASS_OBJECT_PATH:
2495 case G_VARIANT_CLASS_SIGNATURE:
2496 return strcmp (g_variant_get_string (a, NULL),
2497 g_variant_get_string (b, NULL));
2500 g_return_val_if_fail (!g_variant_is_container (a), 0);
2501 g_assert_not_reached ();
2505 /* GVariantIter {{{1 */
2509 * #GVariantIter is an opaque data structure and can only be accessed
2510 * using the following functions.
2517 const gchar *loop_format;
2523 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2527 struct stack_iter iter;
2529 GVariant *value_ref;
2533 #define GVSI(i) ((struct stack_iter *) (i))
2534 #define GVHI(i) ((struct heap_iter *) (i))
2535 #define GVSI_MAGIC ((gsize) 3579507750u)
2536 #define GVHI_MAGIC ((gsize) 1450270775u)
2537 #define is_valid_iter(i) (i != NULL && \
2538 GVSI(i)->magic == GVSI_MAGIC)
2539 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2543 * g_variant_iter_new:
2544 * @value: a container #GVariant
2545 * @returns: a new heap-allocated #GVariantIter
2547 * Creates a heap-allocated #GVariantIter for iterating over the items
2550 * Use g_variant_iter_free() to free the return value when you no longer
2553 * A reference is taken to @value and will be released only when
2554 * g_variant_iter_free() is called.
2559 g_variant_iter_new (GVariant *value)
2563 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2564 GVHI(iter)->value_ref = g_variant_ref (value);
2565 GVHI(iter)->magic = GVHI_MAGIC;
2567 g_variant_iter_init (iter, value);
2573 * g_variant_iter_init:
2574 * @iter: a pointer to a #GVariantIter
2575 * @value: a container #GVariant
2576 * @returns: the number of items in @value
2578 * Initialises (without allocating) a #GVariantIter. @iter may be
2579 * completely uninitialised prior to this call; its old value is
2582 * The iterator remains valid for as long as @value exists, and need not
2583 * be freed in any way.
2588 g_variant_iter_init (GVariantIter *iter,
2591 GVSI(iter)->magic = GVSI_MAGIC;
2592 GVSI(iter)->value = value;
2593 GVSI(iter)->n = g_variant_n_children (value);
2595 GVSI(iter)->loop_format = NULL;
2597 return GVSI(iter)->n;
2601 * g_variant_iter_copy:
2602 * @iter: a #GVariantIter
2603 * @returns: a new heap-allocated #GVariantIter
2605 * Creates a new heap-allocated #GVariantIter to iterate over the
2606 * container that was being iterated over by @iter. Iteration begins on
2607 * the new iterator from the current position of the old iterator but
2608 * the two copies are independent past that point.
2610 * Use g_variant_iter_free() to free the return value when you no longer
2613 * A reference is taken to the container that @iter is iterating over
2614 * and will be releated only when g_variant_iter_free() is called.
2619 g_variant_iter_copy (GVariantIter *iter)
2623 g_return_val_if_fail (is_valid_iter (iter), 0);
2625 copy = g_variant_iter_new (GVSI(iter)->value);
2626 GVSI(copy)->i = GVSI(iter)->i;
2632 * g_variant_iter_n_children:
2633 * @iter: a #GVariantIter
2634 * @returns: the number of children in the container
2636 * Queries the number of child items in the container that we are
2637 * iterating over. This is the total number of items -- not the number
2638 * of items remaining.
2640 * This function might be useful for preallocation of arrays.
2645 g_variant_iter_n_children (GVariantIter *iter)
2647 g_return_val_if_fail (is_valid_iter (iter), 0);
2649 return GVSI(iter)->n;
2653 * g_variant_iter_free:
2654 * @iter: a heap-allocated #GVariantIter
2656 * Frees a heap-allocated #GVariantIter. Only call this function on
2657 * iterators that were returned by g_variant_iter_new() or
2658 * g_variant_iter_copy().
2663 g_variant_iter_free (GVariantIter *iter)
2665 g_return_if_fail (is_valid_heap_iter (iter));
2667 g_variant_unref (GVHI(iter)->value_ref);
2668 GVHI(iter)->magic = 0;
2670 g_slice_free (struct heap_iter, GVHI(iter));
2674 * g_variant_iter_next_value:
2675 * @iter: a #GVariantIter
2676 * @returns: (allow-none): a #GVariant, or %NULL
2678 * Gets the next item in the container. If no more items remain then
2679 * %NULL is returned.
2681 * Use g_variant_unref() to drop your reference on the return value when
2682 * you no longer need it.
2685 * <title>Iterating with g_variant_iter_next_value()</title>
2687 * /<!-- -->* recursively iterate a container *<!-- -->/
2689 * iterate_container_recursive (GVariant *container)
2691 * GVariantIter iter;
2694 * g_variant_iter_init (&iter, dictionary);
2695 * while ((child = g_variant_iter_next_value (&iter)))
2697 * g_print ("type '%s'\n", g_variant_get_type_string (child));
2699 * if (g_variant_is_container (child))
2700 * iterate_container_recursive (child);
2702 * g_variant_unref (child);
2711 g_variant_iter_next_value (GVariantIter *iter)
2713 g_return_val_if_fail (is_valid_iter (iter), FALSE);
2715 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2717 g_critical ("g_variant_iter_next_value: must not be called again "
2718 "after NULL has already been returned.");
2724 if (GVSI(iter)->i < GVSI(iter)->n)
2725 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2730 /* GVariantBuilder {{{1 */
2734 * A utility type for constructing container-type #GVariant instances.
2736 * This is an opaque structure and may only be accessed using the
2737 * following functions.
2739 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
2740 * access it from more than one thread.
2743 struct stack_builder
2745 GVariantBuilder *parent;
2748 /* type constraint explicitly specified by 'type'.
2749 * for tuple types, this moves along as we add more items.
2751 const GVariantType *expected_type;
2753 /* type constraint implied by previous array item.
2755 const GVariantType *prev_item_type;
2757 /* constraints on the number of children. max = -1 for unlimited. */
2761 /* dynamically-growing pointer array */
2762 GVariant **children;
2763 gsize allocated_children;
2766 /* set to '1' if all items in the container will have the same type
2767 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
2769 guint uniform_item_types : 1;
2771 /* set to '1' initially and changed to '0' if an untrusted value is
2779 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
2783 GVariantBuilder builder;
2789 #define GVSB(b) ((struct stack_builder *) (b))
2790 #define GVHB(b) ((struct heap_builder *) (b))
2791 #define GVSB_MAGIC ((gsize) 1033660112u)
2792 #define GVHB_MAGIC ((gsize) 3087242682u)
2793 #define is_valid_builder(b) (b != NULL && \
2794 GVSB(b)->magic == GVSB_MAGIC)
2795 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
2798 * g_variant_builder_new:
2799 * @type: a container type
2800 * @returns: a #GVariantBuilder
2802 * Allocates and initialises a new #GVariantBuilder.
2804 * You should call g_variant_builder_unref() on the return value when it
2805 * is no longer needed. The memory will not be automatically freed by
2808 * In most cases it is easier to place a #GVariantBuilder directly on
2809 * the stack of the calling function and initialise it with
2810 * g_variant_builder_init().
2815 g_variant_builder_new (const GVariantType *type)
2817 GVariantBuilder *builder;
2819 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
2820 g_variant_builder_init (builder, type);
2821 GVHB(builder)->magic = GVHB_MAGIC;
2822 GVHB(builder)->ref_count = 1;
2828 * g_variant_builder_unref:
2829 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2831 * Decreases the reference count on @builder.
2833 * In the event that there are no more references, releases all memory
2834 * associated with the #GVariantBuilder.
2836 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2837 * things will happen.
2842 g_variant_builder_unref (GVariantBuilder *builder)
2844 g_return_if_fail (is_valid_heap_builder (builder));
2846 if (--GVHB(builder)->ref_count)
2849 g_variant_builder_clear (builder);
2850 GVHB(builder)->magic = 0;
2852 g_slice_free (struct heap_builder, GVHB(builder));
2856 * g_variant_builder_ref:
2857 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2858 * @returns: a new reference to @builder
2860 * Increases the reference count on @builder.
2862 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2863 * things will happen.
2868 g_variant_builder_ref (GVariantBuilder *builder)
2870 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
2872 GVHB(builder)->ref_count++;
2878 * g_variant_builder_clear:
2879 * @builder: a #GVariantBuilder
2881 * Releases all memory associated with a #GVariantBuilder without
2882 * freeing the #GVariantBuilder structure itself.
2884 * It typically only makes sense to do this on a stack-allocated
2885 * #GVariantBuilder if you want to abort building the value part-way
2886 * through. This function need not be called if you call
2887 * g_variant_builder_end() and it also doesn't need to be called on
2888 * builders allocated with g_variant_builder_new (see
2889 * g_variant_builder_free() for that).
2891 * This function leaves the #GVariantBuilder structure set to all-zeros.
2892 * It is valid to call this function on either an initialised
2893 * #GVariantBuilder or one that is set to all-zeros but it is not valid
2894 * to call this function on uninitialised memory.
2899 g_variant_builder_clear (GVariantBuilder *builder)
2903 if (GVSB(builder)->magic == 0)
2904 /* all-zeros case */
2907 g_return_if_fail (is_valid_builder (builder));
2909 g_variant_type_free (GVSB(builder)->type);
2911 for (i = 0; i < GVSB(builder)->offset; i++)
2912 g_variant_unref (GVSB(builder)->children[i]);
2914 g_free (GVSB(builder)->children);
2916 if (GVSB(builder)->parent)
2918 g_variant_builder_clear (GVSB(builder)->parent);
2919 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
2922 memset (builder, 0, sizeof (GVariantBuilder));
2926 * g_variant_builder_init:
2927 * @builder: a #GVariantBuilder
2928 * @type: a container type
2930 * Initialises a #GVariantBuilder structure.
2932 * @type must be non-%NULL. It specifies the type of container to
2933 * construct. It can be an indefinite type such as
2934 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
2935 * Maybe, array, tuple, dictionary entry and variant-typed values may be
2938 * After the builder is initialised, values are added using
2939 * g_variant_builder_add_value() or g_variant_builder_add().
2941 * After all the child values are added, g_variant_builder_end() frees
2942 * the memory associated with the builder and returns the #GVariant that
2945 * This function completely ignores the previous contents of @builder.
2946 * On one hand this means that it is valid to pass in completely
2947 * uninitialised memory. On the other hand, this means that if you are
2948 * initialising over top of an existing #GVariantBuilder you need to
2949 * first call g_variant_builder_clear() in order to avoid leaking
2952 * You must not call g_variant_builder_ref() or
2953 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
2954 * with this function. If you ever pass a reference to a
2955 * #GVariantBuilder outside of the control of your own code then you
2956 * should assume that the person receiving that reference may try to use
2957 * reference counting; you should use g_variant_builder_new() instead of
2963 g_variant_builder_init (GVariantBuilder *builder,
2964 const GVariantType *type)
2966 g_return_if_fail (type != NULL);
2967 g_return_if_fail (g_variant_type_is_container (type));
2969 memset (builder, 0, sizeof (GVariantBuilder));
2971 GVSB(builder)->type = g_variant_type_copy (type);
2972 GVSB(builder)->magic = GVSB_MAGIC;
2973 GVSB(builder)->trusted = TRUE;
2975 switch (*(const gchar *) type)
2977 case G_VARIANT_CLASS_VARIANT:
2978 GVSB(builder)->uniform_item_types = TRUE;
2979 GVSB(builder)->allocated_children = 1;
2980 GVSB(builder)->expected_type = NULL;
2981 GVSB(builder)->min_items = 1;
2982 GVSB(builder)->max_items = 1;
2985 case G_VARIANT_CLASS_ARRAY:
2986 GVSB(builder)->uniform_item_types = TRUE;
2987 GVSB(builder)->allocated_children = 8;
2988 GVSB(builder)->expected_type =
2989 g_variant_type_element (GVSB(builder)->type);
2990 GVSB(builder)->min_items = 0;
2991 GVSB(builder)->max_items = -1;
2994 case G_VARIANT_CLASS_MAYBE:
2995 GVSB(builder)->uniform_item_types = TRUE;
2996 GVSB(builder)->allocated_children = 1;
2997 GVSB(builder)->expected_type =
2998 g_variant_type_element (GVSB(builder)->type);
2999 GVSB(builder)->min_items = 0;
3000 GVSB(builder)->max_items = 1;
3003 case G_VARIANT_CLASS_DICT_ENTRY:
3004 GVSB(builder)->uniform_item_types = FALSE;
3005 GVSB(builder)->allocated_children = 2;
3006 GVSB(builder)->expected_type =
3007 g_variant_type_key (GVSB(builder)->type);
3008 GVSB(builder)->min_items = 2;
3009 GVSB(builder)->max_items = 2;
3012 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3013 GVSB(builder)->uniform_item_types = FALSE;
3014 GVSB(builder)->allocated_children = 8;
3015 GVSB(builder)->expected_type = NULL;
3016 GVSB(builder)->min_items = 0;
3017 GVSB(builder)->max_items = -1;
3020 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3021 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3022 GVSB(builder)->expected_type =
3023 g_variant_type_first (GVSB(builder)->type);
3024 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3025 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3026 GVSB(builder)->uniform_item_types = FALSE;
3030 g_assert_not_reached ();
3033 GVSB(builder)->children = g_new (GVariant *,
3034 GVSB(builder)->allocated_children);
3038 g_variant_builder_make_room (struct stack_builder *builder)
3040 if (builder->offset == builder->allocated_children)
3042 builder->allocated_children *= 2;
3043 builder->children = g_renew (GVariant *, builder->children,
3044 builder->allocated_children);
3049 * g_variant_builder_add_value:
3050 * @builder: a #GVariantBuilder
3051 * @value: a #GVariant
3053 * Adds @value to @builder.
3055 * It is an error to call this function in any way that would create an
3056 * inconsistent value to be constructed. Some examples of this are
3057 * putting different types of items into an array, putting the wrong
3058 * types or number of items in a tuple, putting more than one value into
3064 g_variant_builder_add_value (GVariantBuilder *builder,
3067 g_return_if_fail (is_valid_builder (builder));
3068 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3069 g_return_if_fail (!GVSB(builder)->expected_type ||
3070 g_variant_is_of_type (value,
3071 GVSB(builder)->expected_type));
3072 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3073 g_variant_is_of_type (value,
3074 GVSB(builder)->prev_item_type));
3076 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3078 if (!GVSB(builder)->uniform_item_types)
3080 /* advance our expected type pointers */
3081 if (GVSB(builder)->expected_type)
3082 GVSB(builder)->expected_type =
3083 g_variant_type_next (GVSB(builder)->expected_type);
3085 if (GVSB(builder)->prev_item_type)
3086 GVSB(builder)->prev_item_type =
3087 g_variant_type_next (GVSB(builder)->prev_item_type);
3090 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3092 g_variant_builder_make_room (GVSB(builder));
3094 GVSB(builder)->children[GVSB(builder)->offset++] =
3095 g_variant_ref_sink (value);
3099 * g_variant_builder_open:
3100 * @builder: a #GVariantBuilder
3101 * @type: a #GVariantType
3103 * Opens a subcontainer inside the given @builder. When done adding
3104 * items to the subcontainer, g_variant_builder_close() must be called.
3106 * It is an error to call this function in any way that would cause an
3107 * inconsistent value to be constructed (ie: adding too many values or
3108 * a value of an incorrect type).
3113 g_variant_builder_open (GVariantBuilder *builder,
3114 const GVariantType *type)
3116 GVariantBuilder *parent;
3118 g_return_if_fail (is_valid_builder (builder));
3119 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3120 g_return_if_fail (!GVSB(builder)->expected_type ||
3121 g_variant_type_is_subtype_of (type,
3122 GVSB(builder)->expected_type));
3123 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3124 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3127 parent = g_slice_dup (GVariantBuilder, builder);
3128 g_variant_builder_init (builder, type);
3129 GVSB(builder)->parent = parent;
3131 /* push the prev_item_type down into the subcontainer */
3132 if (GVSB(parent)->prev_item_type)
3134 if (!GVSB(builder)->uniform_item_types)
3135 /* tuples and dict entries */
3136 GVSB(builder)->prev_item_type =
3137 g_variant_type_first (GVSB(parent)->prev_item_type);
3139 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3140 /* maybes and arrays */
3141 GVSB(builder)->prev_item_type =
3142 g_variant_type_element (GVSB(parent)->prev_item_type);
3147 * g_variant_builder_close:
3148 * @builder: a #GVariantBuilder
3150 * Closes the subcontainer inside the given @builder that was opened by
3151 * the most recent call to g_variant_builder_open().
3153 * It is an error to call this function in any way that would create an
3154 * inconsistent value to be constructed (ie: too few values added to the
3160 g_variant_builder_close (GVariantBuilder *builder)
3162 GVariantBuilder *parent;
3164 g_return_if_fail (is_valid_builder (builder));
3165 g_return_if_fail (GVSB(builder)->parent != NULL);
3167 parent = GVSB(builder)->parent;
3168 GVSB(builder)->parent = NULL;
3170 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3173 g_slice_free (GVariantBuilder, parent);
3177 * g_variant_make_maybe_type:
3178 * @element: a #GVariant
3180 * Return the type of a maybe containing @element.
3182 static GVariantType *
3183 g_variant_make_maybe_type (GVariant *element)
3185 return g_variant_type_new_maybe (g_variant_get_type (element));
3189 * g_variant_make_array_type:
3190 * @element: a #GVariant
3192 * Return the type of an array containing @element.
3194 static GVariantType *
3195 g_variant_make_array_type (GVariant *element)
3197 return g_variant_type_new_array (g_variant_get_type (element));
3201 * g_variant_builder_end:
3202 * @builder: a #GVariantBuilder
3203 * @returns: (transfer none): a new, floating, #GVariant
3205 * Ends the builder process and returns the constructed value.
3207 * It is not permissible to use @builder in any way after this call
3208 * except for reference counting operations (in the case of a
3209 * heap-allocated #GVariantBuilder) or by reinitialising it with
3210 * g_variant_builder_init() (in the case of stack-allocated).
3212 * It is an error to call this function in any way that would create an
3213 * inconsistent value to be constructed (ie: insufficient number of
3214 * items added to a container with a specific number of children
3215 * required). It is also an error to call this function if the builder
3216 * was created with an indefinite array or maybe type and no children
3217 * have been added; in this case it is impossible to infer the type of
3223 g_variant_builder_end (GVariantBuilder *builder)
3225 GVariantType *my_type;
3228 g_return_val_if_fail (is_valid_builder (builder), NULL);
3229 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3231 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3232 GVSB(builder)->prev_item_type != NULL ||
3233 g_variant_type_is_definite (GVSB(builder)->type),
3236 if (g_variant_type_is_definite (GVSB(builder)->type))
3237 my_type = g_variant_type_copy (GVSB(builder)->type);
3239 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3240 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3242 else if (g_variant_type_is_array (GVSB(builder)->type))
3243 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3245 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3246 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3247 GVSB(builder)->offset);
3249 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3250 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3251 GVSB(builder)->children[1]);
3253 g_assert_not_reached ();
3255 value = g_variant_new_from_children (my_type,
3256 g_renew (GVariant *,
3257 GVSB(builder)->children,
3258 GVSB(builder)->offset),
3259 GVSB(builder)->offset,
3260 GVSB(builder)->trusted);
3261 GVSB(builder)->children = NULL;
3262 GVSB(builder)->offset = 0;
3264 g_variant_builder_clear (builder);
3265 g_variant_type_free (my_type);
3270 /* Format strings {{{1 */
3272 * g_variant_format_string_scan:
3273 * @string: a string that may be prefixed with a format string
3274 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3276 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3278 * @returns: %TRUE if there was a valid format string
3280 * Checks the string pointed to by @string for starting with a properly
3281 * formed #GVariant varargs format string. If no valid format string is
3282 * found then %FALSE is returned.
3284 * If @string does start with a valid format string then %TRUE is
3285 * returned. If @endptr is non-%NULL then it is updated to point to the
3286 * first character after the format string.
3288 * If @limit is non-%NULL then @limit (and any charater after it) will
3289 * not be accessed and the effect is otherwise equivalent to if the
3290 * character at @limit were nul.
3292 * See the section on <link linkend='gvariant-format-strings'>GVariant
3293 * Format Strings</link>.
3298 g_variant_format_string_scan (const gchar *string,
3300 const gchar **endptr)
3302 #define next_char() (string == limit ? '\0' : *string++)
3303 #define peek_char() (string == limit ? '\0' : *string)
3306 switch (next_char())
3308 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
3309 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
3310 case 'g': case 'v': case '*': case '?': case 'r':
3314 return g_variant_format_string_scan (string, limit, endptr);
3318 return g_variant_type_string_scan (string, limit, endptr);
3321 while (peek_char() != ')')
3322 if (!g_variant_format_string_scan (string, limit, &string))
3325 next_char(); /* consume ')' */
3335 if (c != 's' && c != 'o' && c != 'g')
3343 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3344 * The terminating null character is considered to be
3345 * part of the string.
3347 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3351 if (!g_variant_format_string_scan (string, limit, &string))
3354 if (next_char() != '}')
3360 if ((c = next_char()) == 'a')
3362 if ((c = next_char()) == '&')
3364 if ((c = next_char()) == 'a')
3366 if ((c = next_char()) == 'y')
3367 break; /* '^a&ay' */
3376 if ((c = next_char()) == 'y')
3388 if ((c = next_char()) == 'a')
3390 if ((c = next_char()) == 'y')
3400 if (c != 's' && c != 'o' && c != 'g')
3419 * g_variant_format_string_scan_type:
3420 * @string: a string that may be prefixed with a format string
3421 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3423 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3425 * @returns: (allow-none): a #GVariantType if there was a valid format string
3427 * If @string starts with a valid format string then this function will
3428 * return the type that the format string corresponds to. Otherwise
3429 * this function returns %NULL.
3431 * Use g_variant_type_free() to free the return value when you no longer
3434 * This function is otherwise exactly like
3435 * g_variant_format_string_scan().
3440 g_variant_format_string_scan_type (const gchar *string,
3442 const gchar **endptr)
3444 const gchar *my_end;
3451 if (!g_variant_format_string_scan (string, limit, endptr))
3454 dest = new = g_malloc (*endptr - string + 1);
3455 while (string != *endptr)
3457 if (*string != '@' && *string != '&' && *string != '^')
3463 return (GVariantType *) G_VARIANT_TYPE (new);
3467 valid_format_string (const gchar *format_string,
3471 const gchar *endptr;
3474 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3476 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3479 g_critical ("`%s' is not a valid GVariant format string",
3482 g_critical ("`%s' does not have a valid GVariant format "
3483 "string as a prefix", format_string);
3486 g_variant_type_free (type);
3491 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3496 fragment = g_strndup (format_string, endptr - format_string);
3497 typestr = g_variant_type_dup_string (type);
3499 g_critical ("the GVariant format string `%s' has a type of "
3500 "`%s' but the given value has a type of `%s'",
3501 fragment, typestr, g_variant_get_type_string (value));
3503 g_variant_type_free (type);
3508 g_variant_type_free (type);
3513 /* Variable Arguments {{{1 */
3514 /* We consider 2 main classes of format strings:
3516 * - recursive format strings
3517 * these are ones that result in recursion and the collection of
3518 * possibly more than one argument. Maybe types, tuples,
3519 * dictionary entries.
3521 * - leaf format string
3522 * these result in the collection of a single argument.
3524 * Leaf format strings are further subdivided into two categories:
3526 * - single non-null pointer ("nnp")
3527 * these either collect or return a single non-null pointer.
3530 * these collect or return something else (bool, number, etc).
3532 * Based on the above, the varargs handling code is split into 4 main parts:
3534 * - nnp handling code
3535 * - leaf handling code (which may invoke nnp code)
3536 * - generic handling code (may be recursive, may invoke leaf code)
3537 * - user-facing API (which invokes the generic code)
3539 * Each section implements some of the following functions:
3542 * collect the arguments for the format string as if
3543 * g_variant_new() had been called, but do nothing with them. used
3544 * for skipping over arguments when constructing a Nothing maybe
3548 * create a GVariant *
3551 * unpack a GVariant *
3553 * - free (nnp only):
3554 * free a previously allocated item
3558 g_variant_format_string_is_leaf (const gchar *str)
3560 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
3564 g_variant_format_string_is_nnp (const gchar *str)
3566 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
3567 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
3568 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
3571 /* Single non-null pointer ("nnp") {{{2 */
3573 g_variant_valist_free_nnp (const gchar *str,
3579 g_variant_iter_free (ptr);
3583 if (str[2] != '&') /* '^as' */
3599 g_variant_unref (ptr);
3606 g_assert_not_reached ();
3611 g_variant_scan_convenience (const gchar **str,
3634 g_variant_valist_new_nnp (const gchar **str,
3644 const GVariantType *type;
3647 value = g_variant_builder_end (ptr);
3648 type = g_variant_get_type (value);
3650 if G_UNLIKELY (!g_variant_type_is_array (type))
3651 g_error ("g_variant_new: expected array GVariantBuilder but "
3652 "the built value has type `%s'",
3653 g_variant_get_type_string (value));
3655 type = g_variant_type_element (type);
3657 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
3658 g_error ("g_variant_new: expected GVariantBuilder array element "
3659 "type `%s' but the built value has element type `%s'",
3660 g_variant_type_dup_string ((GVariantType *) *str),
3661 g_variant_get_type_string (value) + 1);
3663 g_variant_type_string_scan (*str, NULL, str);
3669 return g_variant_new_string (ptr);
3672 return g_variant_new_object_path (ptr);
3675 return g_variant_new_signature (ptr);
3682 if (g_variant_scan_convenience (str, &constant, &arrays) == 's')
3683 return g_variant_new_strv (ptr, -1);
3686 return g_variant_new_bytestring_array (ptr, -1);
3688 return g_variant_new_bytestring (ptr);
3692 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
3693 g_error ("g_variant_new: expected GVariant of type `%s' but "
3694 "received value has type `%s'",
3695 g_variant_type_dup_string ((GVariantType *) *str),
3696 g_variant_get_type_string (ptr));
3698 g_variant_type_string_scan (*str, NULL, str);
3706 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
3707 g_error ("g_variant_new: format string `?' expects basic-typed "
3708 "GVariant, but received value has type `%s'",
3709 g_variant_get_type_string (ptr));
3714 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
3715 g_error ("g_variant_new: format string `r` expects tuple-typed "
3716 "GVariant, but received value has type `%s'",
3717 g_variant_get_type_string (ptr));
3722 return g_variant_new_variant (ptr);
3725 g_assert_not_reached ();
3730 g_variant_valist_get_nnp (const gchar **str,
3736 g_variant_type_string_scan (*str, NULL, str);
3737 return g_variant_iter_new (value);
3741 return (gchar *) g_variant_get_string (value, NULL);
3746 return g_variant_dup_string (value, NULL);
3753 if (g_variant_scan_convenience (str, &constant, &arrays) == 's')
3756 return g_variant_get_strv (value, NULL);
3758 return g_variant_dup_strv (value, NULL);
3761 else if (arrays > 1)
3764 return g_variant_get_bytestring_array (value, NULL);
3766 return g_variant_dup_bytestring_array (value, NULL);
3772 return (gchar *) g_variant_get_bytestring (value);
3774 return g_variant_dup_bytestring (value, NULL);
3779 g_variant_type_string_scan (*str, NULL, str);
3785 return g_variant_ref (value);
3788 return g_variant_get_variant (value);
3791 g_assert_not_reached ();
3797 g_variant_valist_skip_leaf (const gchar **str,
3800 if (g_variant_format_string_is_nnp (*str))
3802 g_variant_format_string_scan (*str, NULL, str);
3803 va_arg (*app, gpointer);
3821 va_arg (*app, guint64);
3825 va_arg (*app, gdouble);
3829 g_assert_not_reached ();
3834 g_variant_valist_new_leaf (const gchar **str,
3837 if (g_variant_format_string_is_nnp (*str))
3838 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
3843 return g_variant_new_boolean (va_arg (*app, gboolean));
3846 return g_variant_new_byte (va_arg (*app, guint));
3849 return g_variant_new_int16 (va_arg (*app, gint));
3852 return g_variant_new_uint16 (va_arg (*app, guint));
3855 return g_variant_new_int32 (va_arg (*app, gint));
3858 return g_variant_new_uint32 (va_arg (*app, guint));
3861 return g_variant_new_int64 (va_arg (*app, gint64));
3864 return g_variant_new_uint64 (va_arg (*app, guint64));
3867 return g_variant_new_handle (va_arg (*app, gint));
3870 return g_variant_new_double (va_arg (*app, gdouble));
3873 g_assert_not_reached ();
3877 /* The code below assumes this */
3878 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
3879 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
3882 g_variant_valist_get_leaf (const gchar **str,
3887 gpointer ptr = va_arg (*app, gpointer);
3891 g_variant_format_string_scan (*str, NULL, str);
3895 if (g_variant_format_string_is_nnp (*str))
3897 gpointer *nnp = (gpointer *) ptr;
3899 if (free && *nnp != NULL)
3900 g_variant_valist_free_nnp (*str, *nnp);
3905 *nnp = g_variant_valist_get_nnp (str, value);
3907 g_variant_format_string_scan (*str, NULL, str);
3917 *(gboolean *) ptr = g_variant_get_boolean (value);
3921 *(guchar *) ptr = g_variant_get_byte (value);
3925 *(gint16 *) ptr = g_variant_get_int16 (value);
3929 *(guint16 *) ptr = g_variant_get_uint16 (value);
3933 *(gint32 *) ptr = g_variant_get_int32 (value);
3937 *(guint32 *) ptr = g_variant_get_uint32 (value);
3941 *(gint64 *) ptr = g_variant_get_int64 (value);
3945 *(guint64 *) ptr = g_variant_get_uint64 (value);
3949 *(gint32 *) ptr = g_variant_get_handle (value);
3953 *(gdouble *) ptr = g_variant_get_double (value);
3962 *(guchar *) ptr = 0;
3967 *(guint16 *) ptr = 0;
3974 *(guint32 *) ptr = 0;
3980 *(guint64 *) ptr = 0;
3985 g_assert_not_reached ();
3988 /* Generic (recursive) {{{2 */
3990 g_variant_valist_skip (const gchar **str,
3993 if (g_variant_format_string_is_leaf (*str))
3994 g_variant_valist_skip_leaf (str, app);
3996 else if (**str == 'm') /* maybe */
4000 if (!g_variant_format_string_is_nnp (*str))
4001 va_arg (*app, gboolean);
4003 g_variant_valist_skip (str, app);
4005 else /* tuple, dictionary entry */
4007 g_assert (**str == '(' || **str == '{');
4009 while (**str != ')' && **str != '}')
4010 g_variant_valist_skip (str, app);
4016 g_variant_valist_new (const gchar **str,
4019 if (g_variant_format_string_is_leaf (*str))
4020 return g_variant_valist_new_leaf (str, app);
4022 if (**str == 'm') /* maybe */
4024 GVariantType *type = NULL;
4025 GVariant *value = NULL;
4029 if (g_variant_format_string_is_nnp (*str))
4031 gpointer nnp = va_arg (*app, gpointer);
4034 value = g_variant_valist_new_nnp (str, nnp);
4036 type = g_variant_format_string_scan_type (*str, NULL, str);
4040 gboolean just = va_arg (*app, gboolean);
4043 value = g_variant_valist_new (str, app);
4046 type = g_variant_format_string_scan_type (*str, NULL, NULL);
4047 g_variant_valist_skip (str, app);
4051 value = g_variant_new_maybe (type, value);
4054 g_variant_type_free (type);
4058 else /* tuple, dictionary entry */
4063 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
4066 g_assert (**str == '{');
4067 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
4071 while (**str != ')' && **str != '}')
4072 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
4075 return g_variant_builder_end (&b);
4080 g_variant_valist_get (const gchar **str,
4085 if (g_variant_format_string_is_leaf (*str))
4086 g_variant_valist_get_leaf (str, value, free, app);
4088 else if (**str == 'm')
4093 value = g_variant_get_maybe (value);
4095 if (!g_variant_format_string_is_nnp (*str))
4097 gboolean *ptr = va_arg (*app, gboolean *);
4100 *ptr = value != NULL;
4103 g_variant_valist_get (str, value, free, app);
4106 g_variant_unref (value);
4109 else /* tuple, dictionary entry */
4113 g_assert (**str == '(' || **str == '{');
4116 while (**str != ')' && **str != '}')
4120 GVariant *child = g_variant_get_child_value (value, index++);
4121 g_variant_valist_get (str, child, free, app);
4122 g_variant_unref (child);
4125 g_variant_valist_get (str, NULL, free, app);
4131 /* User-facing API {{{2 */
4134 * @format_string: a #GVariant format string
4135 * @...: arguments, as per @format_string
4136 * @returns: a new floating #GVariant instance
4138 * Creates a new #GVariant instance.
4140 * Think of this function as an analogue to g_strdup_printf().
4142 * The type of the created instance and the arguments that are
4143 * expected by this function are determined by @format_string. See the
4144 * section on <link linkend='gvariant-format-strings'>GVariant Format
4145 * Strings</link>. Please note that the syntax of the format string is
4146 * very likely to be extended in the future.
4148 * The first character of the format string must not be '*' '?' '@' or
4149 * 'r'; in essence, a new #GVariant must always be constructed by this
4150 * function (and not merely passed through it unmodified).
4155 g_variant_new (const gchar *format_string,
4161 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
4162 format_string[0] != '?' && format_string[0] != '@' &&
4163 format_string[0] != '*' && format_string[0] != 'r',
4166 va_start (ap, format_string);
4167 value = g_variant_new_va (format_string, NULL, &ap);
4175 * @format_string: a string that is prefixed with a format string
4176 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4178 * @app: a pointer to a #va_list
4179 * @returns: a new, usually floating, #GVariant
4181 * This function is intended to be used by libraries based on
4182 * #GVariant that want to provide g_variant_new()-like functionality
4185 * The API is more general than g_variant_new() to allow a wider range
4188 * @format_string must still point to a valid format string, but it only
4189 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
4190 * non-%NULL then it is updated to point to the first character past the
4191 * end of the format string.
4193 * @app is a pointer to a #va_list. The arguments, according to
4194 * @format_string, are collected from this #va_list and the list is left
4195 * pointing to the argument following the last.
4197 * These two generalisations allow mixing of multiple calls to
4198 * g_variant_new_va() and g_variant_get_va() within a single actual
4199 * varargs call by the user.
4201 * The return value will be floating if it was a newly created GVariant
4202 * instance (for example, if the format string was "(ii)"). In the case
4203 * that the format_string was '*', '?', 'r', or a format starting with
4204 * '@' then the collected #GVariant pointer will be returned unmodified,
4205 * without adding any additional references.
4207 * In order to behave correctly in all cases it is necessary for the
4208 * calling function to g_variant_ref_sink() the return result before
4209 * returning control to the user that originally provided the pointer.
4210 * At this point, the caller will have their own full reference to the
4211 * result. This can also be done by adding the result to a container,
4212 * or by passing it to another g_variant_new() call.
4217 g_variant_new_va (const gchar *format_string,
4218 const gchar **endptr,
4223 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
4225 g_return_val_if_fail (app != NULL, NULL);
4227 value = g_variant_valist_new (&format_string, app);
4230 *endptr = format_string;
4237 * @value: a #GVariant instance
4238 * @format_string: a #GVariant format string
4239 * @...: arguments, as per @format_string
4241 * Deconstructs a #GVariant instance.
4243 * Think of this function as an analogue to scanf().
4245 * The arguments that are expected by this function are entirely
4246 * determined by @format_string. @format_string also restricts the
4247 * permissible types of @value. It is an error to give a value with
4248 * an incompatible type. See the section on <link
4249 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
4250 * Please note that the syntax of the format string is very likely to be
4251 * extended in the future.
4256 g_variant_get (GVariant *value,
4257 const gchar *format_string,
4262 g_return_if_fail (valid_format_string (format_string, TRUE, value));
4264 /* if any direct-pointer-access formats are in use, flatten first */
4265 if (strchr (format_string, '&'))
4266 g_variant_get_data (value);
4268 va_start (ap, format_string);
4269 g_variant_get_va (value, format_string, NULL, &ap);
4275 * @value: a #GVariant
4276 * @format_string: a string that is prefixed with a format string
4277 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4279 * @app: a pointer to a #va_list
4281 * This function is intended to be used by libraries based on #GVariant
4282 * that want to provide g_variant_get()-like functionality to their
4285 * The API is more general than g_variant_get() to allow a wider range
4288 * @format_string must still point to a valid format string, but it only
4289 * need to be nul-terminated if @endptr is %NULL. If @endptr is
4290 * non-%NULL then it is updated to point to the first character past the
4291 * end of the format string.
4293 * @app is a pointer to a #va_list. The arguments, according to
4294 * @format_string, are collected from this #va_list and the list is left
4295 * pointing to the argument following the last.
4297 * These two generalisations allow mixing of multiple calls to
4298 * g_variant_new_va() and g_variant_get_va() within a single actual
4299 * varargs call by the user.
4304 g_variant_get_va (GVariant *value,
4305 const gchar *format_string,
4306 const gchar **endptr,
4309 g_return_if_fail (valid_format_string (format_string, !endptr, value));
4310 g_return_if_fail (value != NULL);
4311 g_return_if_fail (app != NULL);
4313 /* if any direct-pointer-access formats are in use, flatten first */
4314 if (strchr (format_string, '&'))
4315 g_variant_get_data (value);
4317 g_variant_valist_get (&format_string, value, FALSE, app);
4320 *endptr = format_string;
4323 /* Varargs-enabled Utility Functions {{{1 */
4326 * g_variant_builder_add:
4327 * @builder: a #GVariantBuilder
4328 * @format_string: a #GVariant varargs format string
4329 * @...: arguments, as per @format_string
4331 * Adds to a #GVariantBuilder.
4333 * This call is a convenience wrapper that is exactly equivalent to
4334 * calling g_variant_new() followed by g_variant_builder_add_value().
4336 * This function might be used as follows:
4340 * make_pointless_dictionary (void)
4342 * GVariantBuilder *builder;
4345 * builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
4346 * for (i = 0; i < 16; i++)
4350 * sprintf (buf, "%d", i);
4351 * g_variant_builder_add (builder, "{is}", i, buf);
4354 * return g_variant_builder_end (builder);
4361 g_variant_builder_add (GVariantBuilder *builder,
4362 const gchar *format_string,
4368 va_start (ap, format_string);
4369 variant = g_variant_new_va (format_string, NULL, &ap);
4372 g_variant_builder_add_value (builder, variant);
4376 * g_variant_get_child:
4377 * @value: a container #GVariant
4378 * @index_: the index of the child to deconstruct
4379 * @format_string: a #GVariant format string
4380 * @...: arguments, as per @format_string
4382 * Reads a child item out of a container #GVariant instance and
4383 * deconstructs it according to @format_string. This call is
4384 * essentially a combination of g_variant_get_child_value() and
4390 g_variant_get_child (GVariant *value,
4392 const gchar *format_string,
4398 child = g_variant_get_child_value (value, index_);
4399 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4401 va_start (ap, format_string);
4402 g_variant_get_va (child, format_string, NULL, &ap);
4405 g_variant_unref (child);
4409 * g_variant_iter_next:
4410 * @iter: a #GVariantIter
4411 * @format_string: a GVariant format string
4412 * @...: the arguments to unpack the value into
4413 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4416 * Gets the next item in the container and unpacks it into the variable
4417 * argument list according to @format_string, returning %TRUE.
4419 * If no more items remain then %FALSE is returned.
4421 * All of the pointers given on the variable arguments list of this
4422 * function are assumed to point at uninitialised memory. It is the
4423 * responsibility of the caller to free all of the values returned by
4424 * the unpacking process.
4426 * See the section on <link linkend='gvariant-format-strings'>GVariant
4427 * Format Strings</link>.
4430 * <title>Memory management with g_variant_iter_next()</title>
4432 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4434 * iterate_dictionary (GVariant *dictionary)
4436 * GVariantIter iter;
4440 * g_variant_iter_init (&iter, dictionary);
4441 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4443 * g_print ("Item '%s' has type '%s'\n", key,
4444 * g_variant_get_type_string (value));
4446 * /<!-- -->* must free data for ourselves *<!-- -->/
4447 * g_variant_unref (value);
4454 * For a solution that is likely to be more convenient to C programmers
4455 * when dealing with loops, see g_variant_iter_loop().
4460 g_variant_iter_next (GVariantIter *iter,
4461 const gchar *format_string,
4466 value = g_variant_iter_next_value (iter);
4468 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
4475 va_start (ap, format_string);
4476 g_variant_valist_get (&format_string, value, FALSE, &ap);
4479 g_variant_unref (value);
4482 return value != NULL;
4486 * g_variant_iter_loop:
4487 * @iter: a #GVariantIter
4488 * @format_string: a GVariant format string
4489 * @...: the arguments to unpack the value into
4490 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4493 * Gets the next item in the container and unpacks it into the variable
4494 * argument list according to @format_string, returning %TRUE.
4496 * If no more items remain then %FALSE is returned.
4498 * On the first call to this function, the pointers appearing on the
4499 * variable argument list are assumed to point at uninitialised memory.
4500 * On the second and later calls, it is assumed that the same pointers
4501 * will be given and that they will point to the memory as set by the
4502 * previous call to this function. This allows the previous values to
4503 * be freed, as appropriate.
4505 * This function is intended to be used with a while loop as
4506 * demonstrated in the following example. This function can only be
4507 * used when iterating over an array. It is only valid to call this
4508 * function with a string constant for the format string and the same
4509 * string constant must be used each time. Mixing calls to this
4510 * function and g_variant_iter_next() or g_variant_iter_next_value() on
4511 * the same iterator is not recommended.
4513 * See the section on <link linkend='gvariant-format-strings'>GVariant
4514 * Format Strings</link>.
4517 * <title>Memory management with g_variant_iter_loop()</title>
4519 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4521 * iterate_dictionary (GVariant *dictionary)
4523 * GVariantIter iter;
4527 * g_variant_iter_init (&iter, dictionary);
4528 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
4530 * g_print ("Item '%s' has type '%s'\n", key,
4531 * g_variant_get_type_string (value));
4533 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
4539 * If you want a slightly less magical alternative that requires more
4540 * typing, see g_variant_iter_next().
4545 g_variant_iter_loop (GVariantIter *iter,
4546 const gchar *format_string,
4549 gboolean first_time = GVSI(iter)->loop_format == NULL;
4553 g_return_val_if_fail (first_time ||
4554 format_string == GVSI(iter)->loop_format,
4559 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
4560 GVSI(iter)->loop_format = format_string;
4562 if (strchr (format_string, '&'))
4563 g_variant_get_data (GVSI(iter)->value);
4566 value = g_variant_iter_next_value (iter);
4568 g_return_val_if_fail (!first_time ||
4569 valid_format_string (format_string, TRUE, value),
4572 va_start (ap, format_string);
4573 g_variant_valist_get (&format_string, value, !first_time, &ap);
4577 g_variant_unref (value);
4579 return value != NULL;
4582 /* Serialised data {{{1 */
4584 g_variant_deep_copy (GVariant *value)
4586 switch (g_variant_classify (value))
4588 case G_VARIANT_CLASS_MAYBE:
4589 case G_VARIANT_CLASS_ARRAY:
4590 case G_VARIANT_CLASS_TUPLE:
4591 case G_VARIANT_CLASS_DICT_ENTRY:
4592 case G_VARIANT_CLASS_VARIANT:
4594 GVariantBuilder builder;
4598 g_variant_builder_init (&builder, g_variant_get_type (value));
4599 g_variant_iter_init (&iter, value);
4601 while ((child = g_variant_iter_next_value (&iter)))
4603 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
4604 g_variant_unref (child);
4607 return g_variant_builder_end (&builder);
4610 case G_VARIANT_CLASS_BOOLEAN:
4611 return g_variant_new_boolean (g_variant_get_boolean (value));
4613 case G_VARIANT_CLASS_BYTE:
4614 return g_variant_new_byte (g_variant_get_byte (value));
4616 case G_VARIANT_CLASS_INT16:
4617 return g_variant_new_int16 (g_variant_get_int16 (value));
4619 case G_VARIANT_CLASS_UINT16:
4620 return g_variant_new_uint16 (g_variant_get_uint16 (value));
4622 case G_VARIANT_CLASS_INT32:
4623 return g_variant_new_int32 (g_variant_get_int32 (value));
4625 case G_VARIANT_CLASS_UINT32:
4626 return g_variant_new_uint32 (g_variant_get_uint32 (value));
4628 case G_VARIANT_CLASS_INT64:
4629 return g_variant_new_int64 (g_variant_get_int64 (value));
4631 case G_VARIANT_CLASS_UINT64:
4632 return g_variant_new_uint64 (g_variant_get_uint64 (value));
4634 case G_VARIANT_CLASS_HANDLE:
4635 return g_variant_new_handle (g_variant_get_handle (value));
4637 case G_VARIANT_CLASS_DOUBLE:
4638 return g_variant_new_double (g_variant_get_double (value));
4640 case G_VARIANT_CLASS_STRING:
4641 return g_variant_new_string (g_variant_get_string (value, NULL));
4643 case G_VARIANT_CLASS_OBJECT_PATH:
4644 return g_variant_new_object_path (g_variant_get_string (value, NULL));
4646 case G_VARIANT_CLASS_SIGNATURE:
4647 return g_variant_new_signature (g_variant_get_string (value, NULL));
4650 g_assert_not_reached ();
4654 * g_variant_get_normal_form:
4655 * @value: a #GVariant
4656 * @returns: a trusted #GVariant
4658 * Gets a #GVariant instance that has the same value as @value and is
4659 * trusted to be in normal form.
4661 * If @value is already trusted to be in normal form then a new
4662 * reference to @value is returned.
4664 * If @value is not already trusted, then it is scanned to check if it
4665 * is in normal form. If it is found to be in normal form then it is
4666 * marked as trusted and a new reference to it is returned.
4668 * If @value is found not to be in normal form then a new trusted
4669 * #GVariant is created with the same value as @value.
4671 * It makes sense to call this function if you've received #GVariant
4672 * data from untrusted sources and you want to ensure your serialised
4673 * output is definitely in normal form.
4678 g_variant_get_normal_form (GVariant *value)
4682 if (g_variant_is_normal_form (value))
4683 return g_variant_ref (value);
4685 trusted = g_variant_deep_copy (value);
4686 g_assert (g_variant_is_trusted (trusted));
4688 return g_variant_ref_sink (trusted);
4692 * g_variant_byteswap:
4693 * @value: a #GVariant
4694 * @returns: the byteswapped form of @value
4696 * Performs a byteswapping operation on the contents of @value. The
4697 * result is that all multi-byte numeric data contained in @value is
4698 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
4699 * integers as well as file handles and double precision floating point
4702 * This function is an identity mapping on any value that does not
4703 * contain multi-byte numeric data. That include strings, booleans,
4704 * bytes and containers containing only these things (recursively).
4706 * The returned value is always in normal form and is marked as trusted.
4711 g_variant_byteswap (GVariant *value)
4713 GVariantTypeInfo *type_info;
4717 type_info = g_variant_get_type_info (value);
4719 g_variant_type_info_query (type_info, &alignment, NULL);
4722 /* (potentially) contains multi-byte numeric data */
4724 GVariantSerialised serialised;
4728 trusted = g_variant_get_normal_form (value);
4729 serialised.type_info = g_variant_get_type_info (trusted);
4730 serialised.size = g_variant_get_size (trusted);
4731 serialised.data = g_malloc (serialised.size);
4732 g_variant_store (trusted, serialised.data);
4733 g_variant_unref (trusted);
4735 g_variant_serialised_byteswap (serialised);
4737 buffer = g_buffer_new_take_data (serialised.data, serialised.size);
4738 new = g_variant_new_from_buffer (g_variant_get_type (value), buffer, TRUE);
4739 g_buffer_unref (buffer);
4742 /* contains no multi-byte data */
4745 return g_variant_ref_sink (new);
4749 * g_variant_new_from_data:
4750 * @type: a definite #GVariantType
4751 * @data: the serialised data
4752 * @size: the size of @data
4753 * @trusted: %TRUE if @data is definitely in normal form
4754 * @notify: function to call when @data is no longer needed
4755 * @user_data: data for @notify
4756 * @returns: a new floating #GVariant of type @type
4758 * Creates a new #GVariant instance from serialised data.
4760 * @type is the type of #GVariant instance that will be constructed.
4761 * The interpretation of @data depends on knowing the type.
4763 * @data is not modified by this function and must remain valid with an
4764 * unchanging value until such a time as @notify is called with
4765 * @user_data. If the contents of @data change before that time then
4766 * the result is undefined.
4768 * If @data is trusted to be serialised data in normal form then
4769 * @trusted should be %TRUE. This applies to serialised data created
4770 * within this process or read from a trusted location on the disk (such
4771 * as a file installed in /usr/lib alongside your application). You
4772 * should set trusted to %FALSE if @data is read from the network, a
4773 * file in the user's home directory, etc.
4775 * @notify will be called with @user_data when @data is no longer
4776 * needed. The exact time of this call is unspecified and might even be
4777 * before this function returns.
4782 g_variant_new_from_data (const GVariantType *type,
4786 GDestroyNotify notify,
4792 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
4793 g_return_val_if_fail (data != NULL || size == 0, NULL);
4796 buffer = g_buffer_new_from_pointer (data, size, notify, user_data);
4798 buffer = g_buffer_new_from_static_data (data, size);
4800 value = g_variant_new_from_buffer (type, buffer, trusted);
4801 g_buffer_unref (buffer);
4807 /* vim:set foldmethod=marker: */