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>
42 * @short_description: strongly typed value datatype
43 * @see_also: GVariantType
45 * #GVariant is a variant datatype; it stores a value along with
46 * information about the type of that value. The range of possible
47 * values is determined by the type. The type system used by #GVariant
50 * #GVariant instances always have a type and a value (which are given
51 * at construction time). The type and value of a #GVariant instance
52 * can never change other than by the #GVariant itself being
53 * destroyed. A #GVariant can not contain a pointer.
55 * #GVariant is reference counted using g_variant_ref() and
56 * g_variant_unref(). #GVariant also has floating reference counts --
57 * see g_variant_ref_sink().
59 * #GVariant is completely threadsafe. A #GVariant instance can be
60 * concurrently accessed in any way from any number of threads without
63 * #GVariant is heavily optimised for dealing with data in serialised
64 * form. It works particularly well with data located in memory-mapped
65 * files. It can perform nearly all deserialisation operations in a
66 * small constant time, usually touching only a single memory page.
67 * Serialised #GVariant data can also be sent over the network.
69 * #GVariant is largely compatible with DBus. Almost all types of
70 * #GVariant instances can be sent over DBus. See #GVariantType for
73 * For convenience to C programmers, #GVariant features powerful
74 * varargs-based value construction and destruction. This feature is
75 * designed to be embedded in other libraries.
77 * There is a Python-inspired text language for describing #GVariant
78 * values. #GVariant includes a printer for this language and a parser
79 * with type inferencing.
82 * <title>Memory Use</title>
84 * #GVariant tries to be quite efficient with respect to memory use.
85 * This section gives a rough idea of how much memory is used by the
86 * current implementation. The information here is subject to change
90 * The memory allocated by #GVariant can be grouped into 4 broad
91 * purposes: memory for serialised data, memory for the type
92 * information cache, buffer management memory and memory for the
93 * #GVariant structure itself.
96 * <title>Serialised Data Memory</title>
98 * This is the memory that is used for storing GVariant data in
99 * serialised form. This is what would be sent over the network or
100 * what would end up on disk.
103 * The amount of memory required to store a boolean is 1 byte. 16,
104 * 32 and 64 bit integers and double precision floating point numbers
105 * use their "natural" size. Strings (including object path and
106 * signature strings) are stored with a nul terminator, and as such
107 * use the length of the string plus 1 byte.
110 * Maybe types use no space at all to represent the null value and
111 * use the same amount of space (sometimes plus one byte) as the
112 * equivalent non-maybe-typed value to represent the non-null case.
115 * Arrays use the amount of space required to store each of their
116 * members, concatenated. Additionally, if the items stored in an
117 * array are not of a fixed-size (ie: strings, other arrays, etc)
118 * then an additional framing offset is stored for each item. The
119 * size of this offset is either 1, 2 or 4 bytes depending on the
120 * overall size of the container. Additionally, extra padding bytes
121 * are added as required for alignment of child values.
124 * Tuples (including dictionary entries) use the amount of space
125 * required to store each of their members, concatenated, plus one
126 * framing offset (as per arrays) for each non-fixed-sized item in
127 * the tuple, except for the last one. Additionally, extra padding
128 * bytes are added as required for alignment of child values.
131 * Variants use the same amount of space as the item inside of the
132 * variant, plus 1 byte, plus the length of the type string for the
133 * item inside the variant.
136 * As an example, consider a dictionary mapping strings to variants.
137 * In the case that the dictionary is empty, 0 bytes are required for
141 * If we add an item "width" that maps to the int32 value of 500 then
142 * we will use 4 byte to store the int32 (so 6 for the variant
143 * containing it) and 6 bytes for the string. The variant must be
144 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
145 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
146 * for the dictionary entry. An additional 1 byte is added to the
147 * array as a framing offset making a total of 15 bytes.
150 * If we add another entry, "title" that maps to a nullable string
151 * that happens to have a value of null, then we use 0 bytes for the
152 * null value (and 3 bytes for the variant to contain it along with
153 * its type string) plus 6 bytes for the string. Again, we need 2
154 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
157 * We now require extra padding between the two items in the array.
158 * After the 14 bytes of the first item, that's 2 bytes required. We
159 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
160 * + 2 = 29 bytes to encode the entire two-item dictionary.
164 * <title>Type Information Cache</title>
166 * For each GVariant type that currently exists in the program a type
167 * information structure is kept in the type information cache. The
168 * type information structure is required for rapid deserialisation.
171 * Continuing with the above example, if a #GVariant exists with the
172 * type "a{sv}" then a type information struct will exist for
173 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
174 * will share the same type information. Additionally, all
175 * single-digit types are stored in read-only static memory and do
176 * not contribute to the writable memory footprint of a program using
180 * Aside from the type information structures stored in read-only
181 * memory, there are two forms of type information. One is used for
182 * container types where there is a single element type: arrays and
183 * maybe types. The other is used for container types where there
184 * are multiple element types: tuples and dictionary entries.
187 * Array type info structures are 6 * sizeof (void *), plus the
188 * memory required to store the type string itself. This means that
189 * on 32bit systems, the cache entry for "a{sv}" would require 30
190 * bytes of memory (plus malloc overhead).
193 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
194 * sizeof (void *) for each item in the tuple, plus the memory
195 * required to store the type string itself. A 2-item tuple, for
196 * example, would have a type information structure that consumed
197 * writable memory in the size of 14 * sizeof (void *) (plus type
198 * string) This means that on 32bit systems, the cache entry for
199 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
202 * This means that in total, for our "a{sv}" example, 91 bytes of
203 * type information would be allocated.
206 * The type information cache, additionally, uses a #GHashTable to
207 * store and lookup the cached items and stores a pointer to this
208 * hash table in static storage. The hash table is freed when there
209 * are zero items in the type cache.
212 * Although these sizes may seem large it is important to remember
213 * that a program will probably only have a very small number of
214 * different types of values in it and that only one type information
215 * structure is required for many different values of the same type.
219 * <title>Buffer Management Memory</title>
221 * #GVariant uses an internal buffer management structure to deal
222 * with the various different possible sources of serialised data
223 * that it uses. The buffer is responsible for ensuring that the
224 * correct call is made when the data is no longer in use by
225 * #GVariant. This may involve a g_free() or a g_slice_free() or
226 * even g_mapped_file_unref().
229 * One buffer management structure is used for each chunk of
230 * serialised data. The size of the buffer management structure is 4
231 * * (void *). On 32bit systems, that's 16 bytes.
235 * <title>GVariant structure</title>
237 * The size of a #GVariant structure is 6 * (void *). On 32 bit
238 * systems, that's 24 bytes.
241 * #GVariant structures only exist if they are explicitly created
242 * with API calls. For example, if a #GVariant is constructed out of
243 * serialised data for the example given above (with the dictionary)
244 * then although there are 9 individual values that comprise the
245 * entire dictionary (two keys, two values, two variants containing
246 * the values, two dictionary entries, plus the dictionary itself),
247 * only 1 #GVariant instance exists -- the one refering to the
251 * If calls are made to start accessing the other values then
252 * #GVariant instances will exist for those values only for as long
253 * as they are in use (ie: until you call g_variant_unref()). The
254 * type information is shared. The serialised data and the buffer
255 * management structure for that serialised data is shared by the
260 * <title>Summary</title>
262 * To put the entire example together, for our dictionary mapping
263 * strings to variants (with two entries, as given above), we are
264 * using 91 bytes of memory for type information, 29 byes of memory
265 * for the serialised data, 16 bytes for buffer management and 24
266 * bytes for the #GVariant instance, or a total of 160 bytes, plus
267 * malloc overhead. If we were to use g_variant_get_child_value() to
268 * access the two dictionary entries, we would use an additional 48
269 * bytes. If we were to have other dictionaries of the same type, we
270 * would use more memory for the serialised data and buffer
271 * management for those dictionaries, but the type information would
278 /* definition of GVariant structure is in gvariant-core.c */
280 /* this is a g_return_val_if_fail() for making
281 * sure a (GVariant *) has the required type.
283 #define TYPE_CHECK(value, TYPE, val) \
284 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
285 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
286 "g_variant_is_of_type (" #value \
291 /* Numeric Type Constructor/Getters {{{1 */
293 * g_variant_new_from_trusted:
294 * @type: the #GVariantType
295 * @data: the data to use
296 * @size: the size of @data
297 * @returns: a new floating #GVariant
299 * Constructs a new trusted #GVariant instance from the provided data.
300 * This is used to implement g_variant_new_* for all the basic types.
303 g_variant_new_from_trusted (const GVariantType *type,
310 buffer = g_buffer_new_from_data (data, size);
311 value = g_variant_new_from_buffer (type, buffer, TRUE);
312 g_buffer_unref (buffer);
318 * g_variant_new_boolean:
319 * @boolean: a #gboolean value
320 * @returns: a new boolean #GVariant instance
322 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
327 g_variant_new_boolean (gboolean value)
331 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
335 * g_variant_get_boolean:
336 * @value: a boolean #GVariant instance
337 * @returns: %TRUE or %FALSE
339 * Returns the boolean value of @value.
341 * It is an error to call this function with a @value of any type
342 * other than %G_VARIANT_TYPE_BOOLEAN.
347 g_variant_get_boolean (GVariant *value)
351 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
353 data = g_variant_get_data (value);
355 return data != NULL ? *data != 0 : FALSE;
358 /* the constructors and accessors for byte, int{16,32,64}, handles and
359 * doubles all look pretty much exactly the same, so we reduce
362 #define NUMERIC_TYPE(TYPE, type, ctype) \
363 GVariant *g_variant_new_##type (ctype value) { \
364 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
365 &value, sizeof value); \
367 ctype g_variant_get_##type (GVariant *value) { \
369 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
370 data = g_variant_get_data (value); \
371 return data != NULL ? *data : 0; \
376 * g_variant_new_byte:
377 * @byte: a #guint8 value
378 * @returns: a new byte #GVariant instance
380 * Creates a new byte #GVariant instance.
385 * g_variant_get_byte:
386 * @value: a byte #GVariant instance
387 * @returns: a #guchar
389 * Returns the byte value of @value.
391 * It is an error to call this function with a @value of any type
392 * other than %G_VARIANT_TYPE_BYTE.
396 NUMERIC_TYPE (BYTE, byte, guchar)
399 * g_variant_new_int16:
400 * @int16: a #gint16 value
401 * @returns: a new int16 #GVariant instance
403 * Creates a new int16 #GVariant instance.
408 * g_variant_get_int16:
409 * @value: a int16 #GVariant instance
410 * @returns: a #gint16
412 * Returns the 16-bit signed integer value of @value.
414 * It is an error to call this function with a @value of any type
415 * other than %G_VARIANT_TYPE_INT16.
419 NUMERIC_TYPE (INT16, int16, gint16)
422 * g_variant_new_uint16:
423 * @uint16: a #guint16 value
424 * @returns: a new uint16 #GVariant instance
426 * Creates a new uint16 #GVariant instance.
431 * g_variant_get_uint16:
432 * @value: a uint16 #GVariant instance
433 * @returns: a #guint16
435 * Returns the 16-bit unsigned integer value of @value.
437 * It is an error to call this function with a @value of any type
438 * other than %G_VARIANT_TYPE_UINT16.
442 NUMERIC_TYPE (UINT16, uint16, guint16)
445 * g_variant_new_int32:
446 * @int32: a #gint32 value
447 * @returns: a new int32 #GVariant instance
449 * Creates a new int32 #GVariant instance.
454 * g_variant_get_int32:
455 * @value: a int32 #GVariant instance
456 * @returns: a #gint32
458 * Returns the 32-bit signed integer value of @value.
460 * It is an error to call this function with a @value of any type
461 * other than %G_VARIANT_TYPE_INT32.
465 NUMERIC_TYPE (INT32, int32, gint32)
468 * g_variant_new_uint32:
469 * @uint32: a #guint32 value
470 * @returns: a new uint32 #GVariant instance
472 * Creates a new uint32 #GVariant instance.
477 * g_variant_get_uint32:
478 * @value: a uint32 #GVariant instance
479 * @returns: a #guint32
481 * Returns the 32-bit unsigned integer value of @value.
483 * It is an error to call this function with a @value of any type
484 * other than %G_VARIANT_TYPE_UINT32.
488 NUMERIC_TYPE (UINT32, uint32, guint32)
491 * g_variant_new_int64:
492 * @int64: a #gint64 value
493 * @returns: a new int64 #GVariant instance
495 * Creates a new int64 #GVariant instance.
500 * g_variant_get_int64:
501 * @value: a int64 #GVariant instance
502 * @returns: a #gint64
504 * Returns the 64-bit signed integer value of @value.
506 * It is an error to call this function with a @value of any type
507 * other than %G_VARIANT_TYPE_INT64.
511 NUMERIC_TYPE (INT64, int64, gint64)
514 * g_variant_new_uint64:
515 * @uint64: a #guint64 value
516 * @returns: a new uint64 #GVariant instance
518 * Creates a new uint64 #GVariant instance.
523 * g_variant_get_uint64:
524 * @value: a uint64 #GVariant instance
525 * @returns: a #guint64
527 * Returns the 64-bit unsigned integer value of @value.
529 * It is an error to call this function with a @value of any type
530 * other than %G_VARIANT_TYPE_UINT64.
534 NUMERIC_TYPE (UINT64, uint64, guint64)
537 * g_variant_new_handle:
538 * @handle: a #gint32 value
539 * @returns: a new handle #GVariant instance
541 * Creates a new handle #GVariant instance.
543 * By convention, handles are indexes into an array of file descriptors
544 * that are sent alongside a DBus message. If you're not interacting
545 * with DBus, you probably don't need them.
550 * g_variant_get_handle:
551 * @value: a handle #GVariant instance
552 * @returns: a #gint32
554 * Returns the 32-bit signed integer value of @value.
556 * It is an error to call this function with a @value of any type other
557 * than %G_VARIANT_TYPE_HANDLE.
559 * By convention, handles are indexes into an array of file descriptors
560 * that are sent alongside a DBus message. If you're not interacting
561 * with DBus, you probably don't need them.
565 NUMERIC_TYPE (HANDLE, handle, gint32)
568 * g_variant_new_double:
569 * @floating: a #gdouble floating point value
570 * @returns: a new double #GVariant instance
572 * Creates a new double #GVariant instance.
577 * g_variant_get_double:
578 * @value: a double #GVariant instance
579 * @returns: a #gdouble
581 * Returns the double precision floating point value of @value.
583 * It is an error to call this function with a @value of any type
584 * other than %G_VARIANT_TYPE_DOUBLE.
588 NUMERIC_TYPE (DOUBLE, double, gdouble)
590 /* Container type Constructor / Deconstructors {{{1 */
592 * g_variant_new_maybe:
593 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
594 * @child: (allow-none): the child value, or %NULL
595 * @returns: a new #GVariant maybe instance
597 * Depending on if @child is %NULL, either wraps @child inside of a
598 * maybe container or creates a Nothing instance for the given @type.
600 * At least one of @child_type and @child must be non-%NULL.
601 * If @child_type is non-%NULL then it must be a definite type.
602 * If they are both non-%NULL then @child_type must be the type
608 g_variant_new_maybe (const GVariantType *child_type,
611 GVariantType *maybe_type;
614 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
616 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
617 g_return_val_if_fail (child_type == NULL || child == NULL ||
618 g_variant_is_of_type (child, child_type),
621 if (child_type == NULL)
622 child_type = g_variant_get_type (child);
624 maybe_type = g_variant_type_new_maybe (child_type);
631 children = g_new (GVariant *, 1);
632 children[0] = g_variant_ref_sink (child);
633 trusted = g_variant_is_trusted (children[0]);
635 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
638 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
640 g_variant_type_free (maybe_type);
646 * g_variant_get_maybe:
647 * @value: a maybe-typed value
648 * @returns: (allow-none): the contents of @value, or %NULL
650 * Given a maybe-typed #GVariant instance, extract its value. If the
651 * value is Nothing, then this function returns %NULL.
656 g_variant_get_maybe (GVariant *value)
658 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
660 if (g_variant_n_children (value))
661 return g_variant_get_child_value (value, 0);
667 * g_variant_new_variant:
668 * @value: a #GVariance instance
669 * @returns: a new variant #GVariant instance
671 * Boxes @value. The result is a #GVariant instance representing a
672 * variant containing the original value.
677 g_variant_new_variant (GVariant *value)
679 g_return_val_if_fail (value != NULL, NULL);
681 g_variant_ref_sink (value);
683 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
684 g_memdup (&value, sizeof value),
685 1, g_variant_is_trusted (value));
689 * g_variant_get_variant:
690 * @value: a variant #GVariance instance
691 * @returns: the item contained in the variant
693 * Unboxes @value. The result is the #GVariant instance that was
694 * contained in @value.
699 g_variant_get_variant (GVariant *value)
701 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
703 return g_variant_get_child_value (value, 0);
707 * g_variant_new_array:
708 * @child_type: (allow-none): the element type of the new array
709 * @children: (allow-none) (array length=n_children): an array of
710 * #GVariant pointers, the children
711 * @n_children: the length of @children
712 * @returns: a new #GVariant array
714 * Creates a new #GVariant array from @children.
716 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
717 * child type is determined by inspecting the first element of the
718 * @children array. If @child_type is non-%NULL then it must be a
721 * The items of the array are taken from the @children array. No entry
722 * in the @children array may be %NULL.
724 * All items in the array must have the same type, which must be the
725 * same as @child_type, if given.
730 g_variant_new_array (const GVariantType *child_type,
731 GVariant * const *children,
734 GVariantType *array_type;
735 GVariant **my_children;
740 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
741 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
742 g_return_val_if_fail (child_type == NULL ||
743 g_variant_type_is_definite (child_type), NULL);
745 my_children = g_new (GVariant *, n_children);
748 if (child_type == NULL)
749 child_type = g_variant_get_type (children[0]);
750 array_type = g_variant_type_new_array (child_type);
752 for (i = 0; i < n_children; i++)
754 TYPE_CHECK (children[i], child_type, NULL);
755 my_children[i] = g_variant_ref_sink (children[i]);
756 trusted &= g_variant_is_trusted (children[i]);
759 value = g_variant_new_from_children (array_type, my_children,
760 n_children, trusted);
761 g_variant_type_free (array_type);
767 * g_variant_make_tuple_type:
768 * @children: (array length=n_children): an array of GVariant *
769 * @n_children: the length of @children
771 * Return the type of a tuple containing @children as its items.
773 static GVariantType *
774 g_variant_make_tuple_type (GVariant * const *children,
777 const GVariantType **types;
781 types = g_new (const GVariantType *, n_children);
783 for (i = 0; i < n_children; i++)
784 types[i] = g_variant_get_type (children[i]);
786 type = g_variant_type_new_tuple (types, n_children);
793 * g_variant_new_tuple:
794 * @children: (array length=n_children): the items to make the tuple out of
795 * @n_children: the length of @children
796 * @returns: a new #GVariant tuple
798 * Creates a new tuple #GVariant out of the items in @children. The
799 * type is determined from the types of @children. No entry in the
800 * @children array may be %NULL.
802 * If @n_children is 0 then the unit tuple is constructed.
807 g_variant_new_tuple (GVariant * const *children,
810 GVariantType *tuple_type;
811 GVariant **my_children;
816 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
818 my_children = g_new (GVariant *, n_children);
821 for (i = 0; i < n_children; i++)
823 my_children[i] = g_variant_ref_sink (children[i]);
824 trusted &= g_variant_is_trusted (children[i]);
827 tuple_type = g_variant_make_tuple_type (children, n_children);
828 value = g_variant_new_from_children (tuple_type, my_children,
829 n_children, trusted);
830 g_variant_type_free (tuple_type);
836 * g_variant_make_dict_entry_type:
837 * @key: a #GVariant, the key
838 * @val: a #GVariant, the value
840 * Return the type of a dictionary entry containing @key and @val as its
843 static GVariantType *
844 g_variant_make_dict_entry_type (GVariant *key,
847 return g_variant_type_new_dict_entry (g_variant_get_type (key),
848 g_variant_get_type (val));
852 * g_variant_new_dict_entry:
853 * @key: a basic #GVariant, the key
854 * @value: a #GVariant, the value
855 * @returns: a new dictionary entry #GVariant
857 * Creates a new dictionary entry #GVariant. @key and @value must be
860 * @key must be a value of a basic type (ie: not a container).
865 g_variant_new_dict_entry (GVariant *key,
868 GVariantType *dict_type;
872 g_return_val_if_fail (key != NULL && value != NULL, NULL);
873 g_return_val_if_fail (!g_variant_is_container (key), NULL);
875 children = g_new (GVariant *, 2);
876 children[0] = g_variant_ref_sink (key);
877 children[1] = g_variant_ref_sink (value);
878 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
880 dict_type = g_variant_make_dict_entry_type (key, value);
881 value = g_variant_new_from_children (dict_type, children, 2, trusted);
882 g_variant_type_free (dict_type);
888 * g_variant_get_fixed_array:
889 * @value: a #GVariant array with fixed-sized elements
890 * @n_elements: a pointer to the location to store the number of items
891 * @element_size: the size of each element
892 * @returns: (array length=n_elements): a pointer to the fixed array
894 * Provides access to the serialised data for an array of fixed-sized
897 * @value must be an array with fixed-sized elements. Numeric types are
898 * fixed-size as are tuples containing only other fixed-sized types.
900 * @element_size must be the size of a single element in the array. For
901 * example, if calling this function for an array of 32 bit integers,
902 * you might say <code>sizeof (gint32)</code>. This value isn't used
903 * except for the purpose of a double-check that the form of the
904 * seralised data matches the caller's expectation.
906 * @n_elements, which must be non-%NULL is set equal to the number of
907 * items in the array.
912 g_variant_get_fixed_array (GVariant *value,
916 GVariantTypeInfo *array_info;
917 gsize array_element_size;
921 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
923 g_return_val_if_fail (n_elements != NULL, NULL);
924 g_return_val_if_fail (element_size > 0, NULL);
926 array_info = g_variant_get_type_info (value);
927 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
929 g_return_val_if_fail (array_element_size, NULL);
931 if G_UNLIKELY (array_element_size != element_size)
933 if (array_element_size)
934 g_critical ("g_variant_get_fixed_array: assertion "
935 "`g_variant_array_has_fixed_size (value, element_size)' "
936 "failed: array size %"G_GSIZE_FORMAT" does not match "
937 "given element_size %"G_GSIZE_FORMAT".",
938 array_element_size, element_size);
940 g_critical ("g_variant_get_fixed_array: assertion "
941 "`g_variant_array_has_fixed_size (value, element_size)' "
942 "failed: array does not have fixed size.");
945 data = g_variant_get_data (value);
946 size = g_variant_get_size (value);
948 if (size % element_size)
951 *n_elements = size / element_size;
959 /* String type constructor/getters/validation {{{1 */
961 * g_variant_new_string:
962 * @string: a normal utf8 nul-terminated string
963 * @returns: a new string #GVariant instance
965 * Creates a string #GVariant with the contents of @string.
967 * @string must be valid utf8.
972 g_variant_new_string (const gchar *string)
974 g_return_val_if_fail (string != NULL, NULL);
976 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
977 string, strlen (string) + 1);
981 * g_variant_new_object_path:
982 * @object_path: a normal C nul-terminated string
983 * @returns: a new object path #GVariant instance
985 * Creates a DBus object path #GVariant with the contents of @string.
986 * @string must be a valid DBus object path. Use
987 * g_variant_is_object_path() if you're not sure.
992 g_variant_new_object_path (const gchar *object_path)
994 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
996 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
997 object_path, strlen (object_path) + 1);
1001 * g_variant_is_object_path:
1002 * @string: a normal C nul-terminated string
1003 * @returns: %TRUE if @string is a DBus object path
1005 * Determines if a given string is a valid DBus object path. You
1006 * should ensure that a string is a valid DBus object path before
1007 * passing it to g_variant_new_object_path().
1009 * A valid object path starts with '/' followed by zero or more
1010 * sequences of characters separated by '/' characters. Each sequence
1011 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1012 * (including the one following the final '/' character) may be empty.
1017 g_variant_is_object_path (const gchar *string)
1019 g_return_val_if_fail (string != NULL, FALSE);
1021 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1025 * g_variant_new_signature:
1026 * @signature: a normal C nul-terminated string
1027 * @returns: a new signature #GVariant instance
1029 * Creates a DBus type signature #GVariant with the contents of
1030 * @string. @string must be a valid DBus type signature. Use
1031 * g_variant_is_signature() if you're not sure.
1036 g_variant_new_signature (const gchar *signature)
1038 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1040 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1041 signature, strlen (signature) + 1);
1045 * g_variant_is_signature:
1046 * @string: a normal C nul-terminated string
1047 * @returns: %TRUE if @string is a DBus type signature
1049 * Determines if a given string is a valid DBus type signature. You
1050 * should ensure that a string is a valid DBus type signature before
1051 * passing it to g_variant_new_signature().
1053 * DBus type signatures consist of zero or more definite #GVariantType
1054 * strings in sequence.
1059 g_variant_is_signature (const gchar *string)
1061 g_return_val_if_fail (string != NULL, FALSE);
1063 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1067 * g_variant_get_string:
1068 * @value: a string #GVariant instance
1069 * @length: (allow-none) (default NULL): a pointer to a #gsize,
1070 * to store the length
1071 * @returns: the constant string, utf8 encoded
1073 * Returns the string value of a #GVariant instance with a string
1074 * type. This includes the types %G_VARIANT_TYPE_STRING,
1075 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1077 * The string will always be utf8 encoded.
1079 * If @length is non-%NULL then the length of the string (in bytes) is
1080 * returned there. For trusted values, this information is already
1081 * known. For untrusted values, a strlen() will be performed.
1083 * It is an error to call this function with a @value of any type
1084 * other than those three.
1086 * The return value remains valid as long as @value exists.
1091 g_variant_get_string (GVariant *value,
1097 g_return_val_if_fail (value != NULL, NULL);
1098 g_return_val_if_fail (
1099 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1100 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1101 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1103 data = g_variant_get_data (value);
1104 size = g_variant_get_size (value);
1106 if (!g_variant_is_trusted (value))
1108 switch (g_variant_classify (value))
1110 case G_VARIANT_CLASS_STRING:
1111 if (g_variant_serialiser_is_string (data, size))
1118 case G_VARIANT_CLASS_OBJECT_PATH:
1119 if (g_variant_serialiser_is_object_path (data, size))
1126 case G_VARIANT_CLASS_SIGNATURE:
1127 if (g_variant_serialiser_is_signature (data, size))
1135 g_assert_not_reached ();
1146 * g_variant_dup_string:
1147 * @value: a string #GVariant instance
1148 * @length: a pointer to a #gsize, to store the length
1149 * @returns: a newly allocated string, utf8 encoded
1151 * Similar to g_variant_get_string() except that instead of returning
1152 * a constant string, the string is duplicated.
1154 * The string will always be utf8 encoded.
1156 * The return value must be freed using g_free().
1161 g_variant_dup_string (GVariant *value,
1164 return g_strdup (g_variant_get_string (value, length));
1168 * g_variant_new_byte_array:
1169 * @array: (array length=length): a pointer to an array of bytes
1170 * @length: the length of @array, or -1
1171 * @returns: a new floating #GVariant instance
1173 * Constructs an array of bytes #GVariant from the given array of bytes.
1175 * If @length is -1 then @array is taken to be a normal C string (in the
1176 * sense that it is terminated by a nul character). The nul character
1177 * is included in the array. If length is not -1 then it gives the
1178 * length of @array which may then contain nul chracters with no special
1184 g_variant_new_byte_array (gconstpointer array,
1189 const gchar *bytes = array;
1192 while (bytes[length++]);
1195 return g_variant_new_from_trusted (G_VARIANT_TYPE ("ay"),
1200 * g_variant_get_byte_array:
1201 * @value: an array of bytes #GVariant
1202 * @length: (allow-none): the length of the result, or %NULL
1203 * @returns: (array length=length): a pointer to the byte data, or %NULL
1205 * Gets the contents of an array of bytes #GVariant.
1207 * If @length is non-%NULL then it points to a location at which to
1208 * store the length of the array and nul bytes contained within the
1209 * array have no special meaning.
1211 * If @length is %NULL then the caller has no way to determine what the
1212 * length of the returned data might be. In this case, the function
1213 * ensures that the last byte of the array is a nul byte and, if it is
1214 * not, returns %NULL instead. In this way, the caller is assured that
1215 * any non-%NULL pointer that is returned will be nul-terminated.
1217 * The return value remains valid as long as @value exists.
1222 g_variant_get_byte_array (GVariant *value,
1228 TYPE_CHECK (value, G_VARIANT_TYPE ("ay"), NULL);
1230 data = g_variant_get_data (value);
1231 size = g_variant_get_size (value);
1235 const gchar *bytes = data;
1237 if (bytes[size - 1] != '\0')
1247 * g_variant_new_strv:
1248 * @strv: an array of strings
1249 * @length: the length of @strv, or -1
1250 * @returns: (array length=length): a new floating #GVariant instance
1252 * Constructs an array of strings #GVariant from the given array of
1255 * If @length is not -1 then it gives the maximum length of @strv. In
1256 * any case, a %NULL pointer in @strv is taken as a terminator.
1261 g_variant_new_strv (const gchar * const *strv,
1267 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1270 length = g_strv_length ((gchar **) strv);
1272 strings = g_new (GVariant *, length);
1273 for (i = 0; i < length; i++)
1274 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1276 return g_variant_new_from_children (G_VARIANT_TYPE ("as"),
1277 strings, length, TRUE);
1281 * g_variant_get_strv:
1282 * @value: an array of strings #GVariant
1283 * @length: (allow-none): the length of the result, or %NULL
1284 * @returns: (array length=length): an array of constant strings
1286 * Gets the contents of an array of strings #GVariant. This call
1287 * makes a shallow copy; the return result should be released with
1288 * g_free(), but the individual strings must not be modified.
1290 * If @length is non-%NULL then the number of elements in the result
1291 * is stored there. In any case, the resulting array will be
1294 * For an empty array, @length will be set to 0 and a pointer to a
1295 * %NULL pointer will be returned.
1300 g_variant_get_strv (GVariant *value,
1307 g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1308 g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1309 g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1312 g_variant_get_data (value);
1313 n = g_variant_n_children (value);
1314 strv = g_new (const gchar *, n + 1);
1316 for (i = 0; i < n; i++)
1320 string = g_variant_get_child_value (value, i);
1321 strv[i] = g_variant_get_string (string, NULL);
1322 g_variant_unref (string);
1333 * g_variant_dup_strv:
1334 * @value: an array of strings #GVariant
1335 * @length: (allow-none): the length of the result, or %NULL
1336 * @returns: (array length=length): an array of constant strings
1338 * Gets the contents of an array of strings #GVariant. This call
1339 * makes a deep copy; the return result should be released with
1342 * If @length is non-%NULL then the number of elements in the result
1343 * is stored there. In any case, the resulting array will be
1346 * For an empty array, @length will be set to 0 and a pointer to a
1347 * %NULL pointer will be returned.
1352 g_variant_dup_strv (GVariant *value,
1359 g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1360 g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1361 g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1364 n = g_variant_n_children (value);
1365 strv = g_new (gchar *, n + 1);
1367 for (i = 0; i < n; i++)
1371 string = g_variant_get_child_value (value, i);
1372 strv[i] = g_variant_dup_string (string, NULL);
1373 g_variant_unref (string);
1383 /* Type checking and querying {{{1 */
1385 * g_variant_get_type:
1386 * @value: a #GVariant
1387 * @returns: a #GVariantType
1389 * Determines the type of @value.
1391 * The return value is valid for the lifetime of @value and must not
1396 const GVariantType *
1397 g_variant_get_type (GVariant *value)
1399 GVariantTypeInfo *type_info;
1401 g_return_val_if_fail (value != NULL, NULL);
1403 type_info = g_variant_get_type_info (value);
1405 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1409 * g_variant_get_type_string:
1410 * @value: a #GVariant
1411 * @returns: the type string for the type of @value
1413 * Returns the type string of @value. Unlike the result of calling
1414 * g_variant_type_peek_string(), this string is nul-terminated. This
1415 * string belongs to #GVariant and must not be freed.
1420 g_variant_get_type_string (GVariant *value)
1422 GVariantTypeInfo *type_info;
1424 g_return_val_if_fail (value != NULL, NULL);
1426 type_info = g_variant_get_type_info (value);
1428 return g_variant_type_info_get_type_string (type_info);
1432 * g_variant_is_of_type:
1433 * @value: a #GVariant instance
1434 * @type: a #GVariantType
1435 * @returns: %TRUE if the type of @value matches @type
1437 * Checks if a value has a type matching the provided type.
1442 g_variant_is_of_type (GVariant *value,
1443 const GVariantType *type)
1445 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1449 * g_variant_is_container:
1450 * @value: a #GVariant instance
1451 * @returns: %TRUE if @value is a container
1453 * Checks if @value is a container.
1456 g_variant_is_container (GVariant *value)
1458 return g_variant_type_is_container (g_variant_get_type (value));
1463 * g_variant_classify:
1464 * @value: a #GVariant
1465 * @returns: the #GVariantClass of @value
1467 * Classifies @value according to its top-level type.
1473 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
1474 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
1475 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
1476 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
1477 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
1478 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
1479 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
1480 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
1481 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
1482 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
1484 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
1485 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a DBus object path
1487 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a DBus signature string.
1488 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
1489 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
1490 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
1491 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
1492 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
1494 * The range of possible top-level types of #GVariant instances.
1499 g_variant_classify (GVariant *value)
1501 g_return_val_if_fail (value != NULL, 0);
1503 return *g_variant_get_type_string (value);
1506 /* Pretty printer {{{1 */
1508 * g_variant_print_string:
1509 * @value: a #GVariant
1510 * @string: (allow-none) (default NULL): a #GString, or %NULL
1511 * @type_annotate: %TRUE if type information should be included in
1513 * @returns: a #GString containing the string
1515 * Behaves as g_variant_print(), but operates on a #GString.
1517 * If @string is non-%NULL then it is appended to and returned. Else,
1518 * a new empty #GString is allocated and it is returned.
1523 g_variant_print_string (GVariant *value,
1525 gboolean type_annotate)
1527 if G_UNLIKELY (string == NULL)
1528 string = g_string_new (NULL);
1530 switch (g_variant_classify (value))
1532 case G_VARIANT_CLASS_MAYBE:
1534 g_string_append_printf (string, "@%s ",
1535 g_variant_get_type_string (value));
1537 if (g_variant_n_children (value))
1539 gchar *printed_child;
1544 * Consider the case of the type "mmi". In this case we could
1545 * write "just just 4", but "4" alone is totally unambiguous,
1546 * so we try to drop "just" where possible.
1548 * We have to be careful not to always drop "just", though,
1549 * since "nothing" needs to be distinguishable from "just
1550 * nothing". The case where we need to ensure we keep the
1551 * "just" is actually exactly the case where we have a nested
1554 * Instead of searching for that nested Nothing, we just print
1555 * the contained value into a separate string and see if we
1556 * end up with "nothing" at the end of it. If so, we need to
1557 * add "just" at our level.
1559 element = g_variant_get_child_value (value, 0);
1560 printed_child = g_variant_print (element, FALSE);
1561 g_variant_unref (element);
1563 if (g_str_has_suffix (printed_child, "nothing"))
1564 g_string_append (string, "just ");
1565 g_string_append (string, printed_child);
1566 g_free (printed_child);
1569 g_string_append (string, "nothing");
1573 case G_VARIANT_CLASS_ARRAY:
1574 /* it's an array so the first character of the type string is 'a'
1576 * if the first two characters are 'a{' then it's an array of
1577 * dictionary entries (ie: a dictionary) so we print that
1580 if (g_variant_get_type_string (value)[1] == '{')
1583 const gchar *comma = "";
1586 if ((n = g_variant_n_children (value)) == 0)
1589 g_string_append_printf (string, "@%s ",
1590 g_variant_get_type_string (value));
1591 g_string_append (string, "{}");
1595 g_string_append_c (string, '{');
1596 for (i = 0; i < n; i++)
1598 GVariant *entry, *key, *val;
1600 g_string_append (string, comma);
1603 entry = g_variant_get_child_value (value, i);
1604 key = g_variant_get_child_value (entry, 0);
1605 val = g_variant_get_child_value (entry, 1);
1606 g_variant_unref (entry);
1608 g_variant_print_string (key, string, type_annotate);
1609 g_variant_unref (key);
1610 g_string_append (string, ": ");
1611 g_variant_print_string (val, string, type_annotate);
1612 g_variant_unref (val);
1613 type_annotate = FALSE;
1615 g_string_append_c (string, '}');
1618 /* normal (non-dictionary) array */
1620 const gchar *comma = "";
1623 if ((n = g_variant_n_children (value)) == 0)
1626 g_string_append_printf (string, "@%s ",
1627 g_variant_get_type_string (value));
1628 g_string_append (string, "[]");
1632 g_string_append_c (string, '[');
1633 for (i = 0; i < n; i++)
1637 g_string_append (string, comma);
1640 element = g_variant_get_child_value (value, i);
1642 g_variant_print_string (element, string, type_annotate);
1643 g_variant_unref (element);
1644 type_annotate = FALSE;
1646 g_string_append_c (string, ']');
1651 case G_VARIANT_CLASS_TUPLE:
1655 n = g_variant_n_children (value);
1657 g_string_append_c (string, '(');
1658 for (i = 0; i < n; i++)
1662 element = g_variant_get_child_value (value, i);
1663 g_variant_print_string (element, string, type_annotate);
1664 g_string_append (string, ", ");
1665 g_variant_unref (element);
1668 /* for >1 item: remove final ", "
1669 * for 1 item: remove final " ", but leave the ","
1670 * for 0 items: there is only "(", so remove nothing
1672 g_string_truncate (string, string->len - (n > 0) - (n > 1));
1673 g_string_append_c (string, ')');
1677 case G_VARIANT_CLASS_DICT_ENTRY:
1681 g_string_append_c (string, '{');
1683 element = g_variant_get_child_value (value, 0);
1684 g_variant_print_string (element, string, type_annotate);
1685 g_variant_unref (element);
1687 g_string_append (string, ", ");
1689 element = g_variant_get_child_value (value, 1);
1690 g_variant_print_string (element, string, type_annotate);
1691 g_variant_unref (element);
1693 g_string_append_c (string, '}');
1697 case G_VARIANT_CLASS_VARIANT:
1699 GVariant *child = g_variant_get_variant (value);
1701 /* Always annotate types in nested variants, because they are
1702 * (by nature) of variable type.
1704 g_string_append_c (string, '<');
1705 g_variant_print_string (child, string, TRUE);
1706 g_string_append_c (string, '>');
1708 g_variant_unref (child);
1712 case G_VARIANT_CLASS_BOOLEAN:
1713 if (g_variant_get_boolean (value))
1714 g_string_append (string, "true");
1716 g_string_append (string, "false");
1719 case G_VARIANT_CLASS_STRING:
1721 const gchar *str = g_variant_get_string (value, NULL);
1722 gunichar quote = strchr (str, '\'') ? '"' : '\'';
1724 g_string_append_c (string, quote);
1728 gunichar c = g_utf8_get_char (str);
1730 if (c == quote || c == '\\')
1731 g_string_append_c (string, '\\');
1733 if (g_unichar_isprint (c))
1734 g_string_append_unichar (string, c);
1738 g_string_append_c (string, '\\');
1743 g_string_append_c (string, 'a');
1747 g_string_append_c (string, 'b');
1751 g_string_append_c (string, 'f');
1755 g_string_append_c (string, 'n');
1759 g_string_append_c (string, 'r');
1763 g_string_append_c (string, 't');
1767 g_string_append_c (string, 'v');
1771 g_string_append_printf (string, "u%04x", c);
1775 g_string_append_printf (string, "U%08x", c);
1778 str = g_utf8_next_char (str);
1781 g_string_append_c (string, quote);
1785 case G_VARIANT_CLASS_BYTE:
1787 g_string_append (string, "byte ");
1788 g_string_append_printf (string, "0x%02x",
1789 g_variant_get_byte (value));
1792 case G_VARIANT_CLASS_INT16:
1794 g_string_append (string, "int16 ");
1795 g_string_append_printf (string, "%"G_GINT16_FORMAT,
1796 g_variant_get_int16 (value));
1799 case G_VARIANT_CLASS_UINT16:
1801 g_string_append (string, "uint16 ");
1802 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
1803 g_variant_get_uint16 (value));
1806 case G_VARIANT_CLASS_INT32:
1807 /* Never annotate this type because it is the default for numbers
1808 * (and this is a *pretty* printer)
1810 g_string_append_printf (string, "%"G_GINT32_FORMAT,
1811 g_variant_get_int32 (value));
1814 case G_VARIANT_CLASS_HANDLE:
1816 g_string_append (string, "handle ");
1817 g_string_append_printf (string, "%"G_GINT32_FORMAT,
1818 g_variant_get_handle (value));
1821 case G_VARIANT_CLASS_UINT32:
1823 g_string_append (string, "uint32 ");
1824 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
1825 g_variant_get_uint32 (value));
1828 case G_VARIANT_CLASS_INT64:
1830 g_string_append (string, "int64 ");
1831 g_string_append_printf (string, "%"G_GINT64_FORMAT,
1832 g_variant_get_int64 (value));
1835 case G_VARIANT_CLASS_UINT64:
1837 g_string_append (string, "uint64 ");
1838 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
1839 g_variant_get_uint64 (value));
1842 case G_VARIANT_CLASS_DOUBLE:
1847 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
1849 for (i = 0; buffer[i]; i++)
1850 if (buffer[i] == '.' || buffer[i] == 'e' ||
1851 buffer[i] == 'n' || buffer[i] == 'N')
1854 /* if there is no '.' or 'e' in the float then add one */
1855 if (buffer[i] == '\0')
1862 g_string_append (string, buffer);
1866 case G_VARIANT_CLASS_OBJECT_PATH:
1868 g_string_append (string, "objectpath ");
1869 g_string_append_printf (string, "\'%s\'",
1870 g_variant_get_string (value, NULL));
1873 case G_VARIANT_CLASS_SIGNATURE:
1875 g_string_append (string, "signature ");
1876 g_string_append_printf (string, "\'%s\'",
1877 g_variant_get_string (value, NULL));
1881 g_assert_not_reached ();
1889 * @value: a #GVariant
1890 * @type_annotate: %TRUE if type information should be included in
1892 * @returns: a newly-allocated string holding the result.
1894 * Pretty-prints @value in the format understood by g_variant_parse().
1896 * If @type_annotate is %TRUE, then type information is included in
1900 g_variant_print (GVariant *value,
1901 gboolean type_annotate)
1903 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
1907 /* Hash, Equal, Compare {{{1 */
1910 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
1911 * @returns: a hash value corresponding to @value
1913 * Generates a hash value for a #GVariant instance.
1915 * The output of this function is guaranteed to be the same for a given
1916 * value only per-process. It may change between different processor
1917 * architectures or even different versions of GLib. Do not use this
1918 * function as a basis for building protocols or file formats.
1920 * The type of @value is #gconstpointer only to allow use of this
1921 * function with #GHashTable. @value must be a #GVariant.
1926 g_variant_hash (gconstpointer value_)
1928 GVariant *value = (GVariant *) value_;
1930 switch (g_variant_classify (value))
1932 case G_VARIANT_CLASS_STRING:
1933 case G_VARIANT_CLASS_OBJECT_PATH:
1934 case G_VARIANT_CLASS_SIGNATURE:
1935 return g_str_hash (g_variant_get_string (value, NULL));
1937 case G_VARIANT_CLASS_BOOLEAN:
1938 /* this is a very odd thing to hash... */
1939 return g_variant_get_boolean (value);
1941 case G_VARIANT_CLASS_BYTE:
1942 return g_variant_get_byte (value);
1944 case G_VARIANT_CLASS_INT16:
1945 case G_VARIANT_CLASS_UINT16:
1949 ptr = g_variant_get_data (value);
1957 case G_VARIANT_CLASS_INT32:
1958 case G_VARIANT_CLASS_UINT32:
1959 case G_VARIANT_CLASS_HANDLE:
1963 ptr = g_variant_get_data (value);
1971 case G_VARIANT_CLASS_INT64:
1972 case G_VARIANT_CLASS_UINT64:
1973 case G_VARIANT_CLASS_DOUBLE:
1974 /* need a separate case for these guys because otherwise
1975 * performance could be quite bad on big endian systems
1980 ptr = g_variant_get_data (value);
1983 return ptr[0] + ptr[1];
1989 g_return_val_if_fail (!g_variant_is_container (value), 0);
1990 g_assert_not_reached ();
1996 * @one: (type GVariant): a #GVariant instance
1997 * @two: (type GVariant): a #GVariant instance
1998 * @returns: %TRUE if @one and @two are equal
2000 * Checks if @one and @two have the same type and value.
2002 * The types of @one and @two are #gconstpointer only to allow use of
2003 * this function with #GHashTable. They must each be a #GVariant.
2008 g_variant_equal (gconstpointer one,
2013 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2015 if (g_variant_get_type_info ((GVariant *) one) !=
2016 g_variant_get_type_info ((GVariant *) two))
2019 /* if both values are trusted to be in their canonical serialised form
2020 * then a simple memcmp() of their serialised data will answer the
2023 * if not, then this might generate a false negative (since it is
2024 * possible for two different byte sequences to represent the same
2025 * value). for now we solve this by pretty-printing both values and
2026 * comparing the result.
2028 if (g_variant_is_trusted ((GVariant *) one) &&
2029 g_variant_is_trusted ((GVariant *) two))
2031 gconstpointer data_one, data_two;
2032 gsize size_one, size_two;
2034 size_one = g_variant_get_size ((GVariant *) one);
2035 size_two = g_variant_get_size ((GVariant *) two);
2037 if (size_one != size_two)
2040 data_one = g_variant_get_data ((GVariant *) one);
2041 data_two = g_variant_get_data ((GVariant *) two);
2043 equal = memcmp (data_one, data_two, size_one) == 0;
2047 gchar *strone, *strtwo;
2049 strone = g_variant_print ((GVariant *) one, FALSE);
2050 strtwo = g_variant_print ((GVariant *) two, FALSE);
2051 equal = strcmp (strone, strtwo) == 0;
2060 * g_variant_compare:
2061 * @one: (type GVariant): a basic-typed #GVariant instance
2062 * @two: (type GVariant): a #GVariant instance of the same type
2063 * @returns: negative value if a < b;
2065 * positive value if a > b.
2067 * Compares @one and @two.
2069 * The types of @one and @two are #gconstpointer only to allow use of
2070 * this function with #GTree, #GPtrArray, etc. They must each be a
2073 * Comparison is only defined for basic types (ie: booleans, numbers,
2074 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2075 * ordered in the usual way. Strings are in ASCII lexographical order.
2077 * It is a programmer error to attempt to compare container values or
2078 * two values that have types that are not exactly equal. For example,
2079 * you can not compare a 32-bit signed integer with a 32-bit unsigned
2080 * integer. Also note that this function is not particularly
2081 * well-behaved when it comes to comparison of doubles; in particular,
2082 * the handling of incomparable values (ie: NaN) is undefined.
2084 * If you only require an equality comparison, g_variant_equal() is more
2090 g_variant_compare (gconstpointer one,
2093 GVariant *a = (GVariant *) one;
2094 GVariant *b = (GVariant *) two;
2096 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2098 switch (g_variant_classify (a))
2100 case G_VARIANT_CLASS_BYTE:
2101 return ((gint) g_variant_get_byte (a)) -
2102 ((gint) g_variant_get_byte (b));
2104 case G_VARIANT_CLASS_INT16:
2105 return ((gint) g_variant_get_int16 (a)) -
2106 ((gint) g_variant_get_int16 (b));
2108 case G_VARIANT_CLASS_UINT16:
2109 return ((gint) g_variant_get_uint16 (a)) -
2110 ((gint) g_variant_get_uint16 (b));
2112 case G_VARIANT_CLASS_INT32:
2114 gint32 a_val = g_variant_get_int32 (a);
2115 gint32 b_val = g_variant_get_int32 (b);
2117 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2120 case G_VARIANT_CLASS_UINT32:
2122 guint32 a_val = g_variant_get_uint32 (a);
2123 guint32 b_val = g_variant_get_uint32 (b);
2125 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2128 case G_VARIANT_CLASS_INT64:
2130 gint64 a_val = g_variant_get_int64 (a);
2131 gint64 b_val = g_variant_get_int64 (b);
2133 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2136 case G_VARIANT_CLASS_UINT64:
2138 guint64 a_val = g_variant_get_int32 (a);
2139 guint64 b_val = g_variant_get_int32 (b);
2141 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2144 case G_VARIANT_CLASS_DOUBLE:
2146 gdouble a_val = g_variant_get_double (a);
2147 gdouble b_val = g_variant_get_double (b);
2149 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2152 case G_VARIANT_CLASS_STRING:
2153 case G_VARIANT_CLASS_OBJECT_PATH:
2154 case G_VARIANT_CLASS_SIGNATURE:
2155 return strcmp (g_variant_get_string (a, NULL),
2156 g_variant_get_string (b, NULL));
2159 g_return_val_if_fail (!g_variant_is_container (a), 0);
2160 g_assert_not_reached ();
2164 /* GVariantIter {{{1 */
2168 * #GVariantIter is an opaque data structure and can only be accessed
2169 * using the following functions.
2176 const gchar *loop_format;
2182 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2186 struct stack_iter iter;
2188 GVariant *value_ref;
2192 #define GVSI(i) ((struct stack_iter *) (i))
2193 #define GVHI(i) ((struct heap_iter *) (i))
2194 #define GVSI_MAGIC ((gsize) 3579507750u)
2195 #define GVHI_MAGIC ((gsize) 1450270775u)
2196 #define is_valid_iter(i) (i != NULL && \
2197 GVSI(i)->magic == GVSI_MAGIC)
2198 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2202 * g_variant_iter_new:
2203 * @value: a container #GVariant
2204 * @returns: a new heap-allocated #GVariantIter
2206 * Creates a heap-allocated #GVariantIter for iterating over the items
2209 * Use g_variant_iter_free() to free the return value when you no longer
2212 * A reference is taken to @value and will be released only when
2213 * g_variant_iter_free() is called.
2218 g_variant_iter_new (GVariant *value)
2222 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2223 GVHI(iter)->value_ref = g_variant_ref (value);
2224 GVHI(iter)->magic = GVHI_MAGIC;
2226 g_variant_iter_init (iter, value);
2232 * g_variant_iter_init:
2233 * @iter: a pointer to a #GVariantIter
2234 * @value: a container #GVariant
2235 * @returns: the number of items in @value
2237 * Initialises (without allocating) a #GVariantIter. @iter may be
2238 * completely uninitialised prior to this call; its old value is
2241 * The iterator remains valid for as long as @value exists, and need not
2242 * be freed in any way.
2247 g_variant_iter_init (GVariantIter *iter,
2250 GVSI(iter)->magic = GVSI_MAGIC;
2251 GVSI(iter)->value = value;
2252 GVSI(iter)->n = g_variant_n_children (value);
2254 GVSI(iter)->loop_format = NULL;
2256 return GVSI(iter)->n;
2260 * g_variant_iter_copy:
2261 * @iter: a #GVariantIter
2262 * @returns: a new heap-allocated #GVariantIter
2264 * Creates a new heap-allocated #GVariantIter to iterate over the
2265 * container that was being iterated over by @iter. Iteration begins on
2266 * the new iterator from the current position of the old iterator but
2267 * the two copies are independent past that point.
2269 * Use g_variant_iter_free() to free the return value when you no longer
2272 * A reference is taken to the container that @iter is iterating over
2273 * and will be releated only when g_variant_iter_free() is called.
2278 g_variant_iter_copy (GVariantIter *iter)
2282 g_return_val_if_fail (is_valid_iter (iter), 0);
2284 copy = g_variant_iter_new (GVSI(iter)->value);
2285 GVSI(copy)->i = GVSI(iter)->i;
2291 * g_variant_iter_n_children:
2292 * @iter: a #GVariantIter
2293 * @returns: the number of children in the container
2295 * Queries the number of child items in the container that we are
2296 * iterating over. This is the total number of items -- not the number
2297 * of items remaining.
2299 * This function might be useful for preallocation of arrays.
2304 g_variant_iter_n_children (GVariantIter *iter)
2306 g_return_val_if_fail (is_valid_iter (iter), 0);
2308 return GVSI(iter)->n;
2312 * g_variant_iter_free:
2313 * @iter: a heap-allocated #GVariantIter
2315 * Frees a heap-allocated #GVariantIter. Only call this function on
2316 * iterators that were returned by g_variant_iter_new() or
2317 * g_variant_iter_copy().
2322 g_variant_iter_free (GVariantIter *iter)
2324 g_return_if_fail (is_valid_heap_iter (iter));
2326 g_variant_unref (GVHI(iter)->value_ref);
2327 GVHI(iter)->magic = 0;
2329 g_slice_free (struct heap_iter, GVHI(iter));
2333 * g_variant_iter_next_value:
2334 * @iter: a #GVariantIter
2335 * @returns: (allow-none): a #GVariant, or %NULL
2337 * Gets the next item in the container. If no more items remain then
2338 * %NULL is returned.
2340 * Use g_variant_unref() to drop your reference on the return value when
2341 * you no longer need it.
2344 * <title>Iterating with g_variant_iter_next_value()</title>
2346 * /<!-- -->* recursively iterate a container *<!-- -->/
2348 * iterate_container_recursive (GVariant *container)
2350 * GVariantIter iter;
2353 * g_variant_iter_init (&iter, dictionary);
2354 * while ((child = g_variant_iter_next_value (&iter)))
2356 * g_print ("type '%s'\n", g_variant_get_type_string (child));
2358 * if (g_variant_is_container (child))
2359 * iterate_container_recursive (child);
2361 * g_variant_unref (child);
2370 g_variant_iter_next_value (GVariantIter *iter)
2372 g_return_val_if_fail (is_valid_iter (iter), FALSE);
2374 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2376 g_critical ("g_variant_iter_next_value: must not be called again "
2377 "after NULL has already been returned.");
2383 if (GVSI(iter)->i < GVSI(iter)->n)
2384 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2389 /* GVariantBuilder {{{1 */
2393 * A utility type for constructing container-type #GVariant instances.
2395 * This is an opaque structure and may only be accessed using the
2396 * following functions.
2398 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
2399 * access it from more than one thread.
2402 struct stack_builder
2404 GVariantBuilder *parent;
2407 /* type constraint explicitly specified by 'type'.
2408 * for tuple types, this moves along as we add more items.
2410 const GVariantType *expected_type;
2412 /* type constraint implied by previous array item.
2414 const GVariantType *prev_item_type;
2416 /* constraints on the number of children. max = -1 for unlimited. */
2420 /* dynamically-growing pointer array */
2421 GVariant **children;
2422 gsize allocated_children;
2425 /* set to '1' if all items in the container will have the same type
2426 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
2428 guint uniform_item_types : 1;
2430 /* set to '1' initially and changed to '0' if an untrusted value is
2438 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
2442 GVariantBuilder builder;
2448 #define GVSB(b) ((struct stack_builder *) (b))
2449 #define GVHB(b) ((struct heap_builder *) (b))
2450 #define GVSB_MAGIC ((gsize) 1033660112u)
2451 #define GVHB_MAGIC ((gsize) 3087242682u)
2452 #define is_valid_builder(b) (b != NULL && \
2453 GVSB(b)->magic == GVSB_MAGIC)
2454 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
2457 * g_variant_builder_new:
2458 * @type: a container type
2459 * @returns: a #GVariantBuilder
2461 * Allocates and initialises a new #GVariantBuilder.
2463 * You should call g_variant_builder_unref() on the return value when it
2464 * is no longer needed. The memory will not be automatically freed by
2467 * In most cases it is easier to place a #GVariantBuilder directly on
2468 * the stack of the calling function and initialise it with
2469 * g_variant_builder_init().
2474 g_variant_builder_new (const GVariantType *type)
2476 GVariantBuilder *builder;
2478 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
2479 g_variant_builder_init (builder, type);
2480 GVHB(builder)->magic = GVHB_MAGIC;
2481 GVHB(builder)->ref_count = 1;
2487 * g_variant_builder_unref:
2488 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2490 * Decreases the reference count on @builder.
2492 * In the event that there are no more references, releases all memory
2493 * associated with the #GVariantBuilder.
2495 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2496 * things will happen.
2501 g_variant_builder_unref (GVariantBuilder *builder)
2503 g_return_if_fail (is_valid_heap_builder (builder));
2505 if (--GVHB(builder)->ref_count)
2508 g_variant_builder_clear (builder);
2509 GVHB(builder)->magic = 0;
2511 g_slice_free (struct heap_builder, GVHB(builder));
2515 * g_variant_builder_ref:
2516 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2517 * @returns: a new reference to @builder
2519 * Increases the reference count on @builder.
2521 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2522 * things will happen.
2527 g_variant_builder_ref (GVariantBuilder *builder)
2529 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
2531 GVHB(builder)->ref_count++;
2537 * g_variant_builder_clear:
2538 * @builder: a #GVariantBuilder
2540 * Releases all memory associated with a #GVariantBuilder without
2541 * freeing the #GVariantBuilder structure itself.
2543 * It typically only makes sense to do this on a stack-allocated
2544 * #GVariantBuilder if you want to abort building the value part-way
2545 * through. This function need not be called if you call
2546 * g_variant_builder_end() and it also doesn't need to be called on
2547 * builders allocated with g_variant_builder_new (see
2548 * g_variant_builder_free() for that).
2550 * This function leaves the #GVariantBuilder structure set to all-zeros.
2551 * It is valid to call this function on either an initialised
2552 * #GVariantBuilder or one that is set to all-zeros but it is not valid
2553 * to call this function on uninitialised memory.
2558 g_variant_builder_clear (GVariantBuilder *builder)
2562 if (GVSB(builder)->magic == 0)
2563 /* all-zeros case */
2566 g_return_if_fail (is_valid_builder (builder));
2568 g_variant_type_free (GVSB(builder)->type);
2570 for (i = 0; i < GVSB(builder)->offset; i++)
2571 g_variant_unref (GVSB(builder)->children[i]);
2573 g_free (GVSB(builder)->children);
2575 if (GVSB(builder)->parent)
2577 g_variant_builder_clear (GVSB(builder)->parent);
2578 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
2581 memset (builder, 0, sizeof (GVariantBuilder));
2585 * g_variant_builder_init:
2586 * @builder: a #GVariantBuilder
2587 * @type: a container type
2589 * Initialises a #GVariantBuilder structure.
2591 * @type must be non-%NULL. It specifies the type of container to
2592 * construct. It can be an indefinite type such as
2593 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
2594 * Maybe, array, tuple, dictionary entry and variant-typed values may be
2597 * After the builder is initialised, values are added using
2598 * g_variant_builder_add_value() or g_variant_builder_add().
2600 * After all the child values are added, g_variant_builder_end() frees
2601 * the memory associated with the builder and returns the #GVariant that
2604 * This function completely ignores the previous contents of @builder.
2605 * On one hand this means that it is valid to pass in completely
2606 * uninitialised memory. On the other hand, this means that if you are
2607 * initialising over top of an existing #GVariantBuilder you need to
2608 * first call g_variant_builder_clear() in order to avoid leaking
2611 * You must not call g_variant_builder_ref() or
2612 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
2613 * with this function. If you ever pass a reference to a
2614 * #GVariantBuilder outside of the control of your own code then you
2615 * should assume that the person receiving that reference may try to use
2616 * reference counting; you should use g_variant_builder_new() instead of
2622 g_variant_builder_init (GVariantBuilder *builder,
2623 const GVariantType *type)
2625 g_return_if_fail (type != NULL);
2626 g_return_if_fail (g_variant_type_is_container (type));
2628 memset (builder, 0, sizeof (GVariantBuilder));
2630 GVSB(builder)->type = g_variant_type_copy (type);
2631 GVSB(builder)->magic = GVSB_MAGIC;
2632 GVSB(builder)->trusted = TRUE;
2634 switch (*(const gchar *) type)
2636 case G_VARIANT_CLASS_VARIANT:
2637 GVSB(builder)->uniform_item_types = TRUE;
2638 GVSB(builder)->allocated_children = 1;
2639 GVSB(builder)->expected_type = NULL;
2640 GVSB(builder)->min_items = 1;
2641 GVSB(builder)->max_items = 1;
2644 case G_VARIANT_CLASS_ARRAY:
2645 GVSB(builder)->uniform_item_types = TRUE;
2646 GVSB(builder)->allocated_children = 8;
2647 GVSB(builder)->expected_type =
2648 g_variant_type_element (GVSB(builder)->type);
2649 GVSB(builder)->min_items = 0;
2650 GVSB(builder)->max_items = -1;
2653 case G_VARIANT_CLASS_MAYBE:
2654 GVSB(builder)->uniform_item_types = TRUE;
2655 GVSB(builder)->allocated_children = 1;
2656 GVSB(builder)->expected_type =
2657 g_variant_type_element (GVSB(builder)->type);
2658 GVSB(builder)->min_items = 0;
2659 GVSB(builder)->max_items = 1;
2662 case G_VARIANT_CLASS_DICT_ENTRY:
2663 GVSB(builder)->uniform_item_types = FALSE;
2664 GVSB(builder)->allocated_children = 2;
2665 GVSB(builder)->expected_type =
2666 g_variant_type_key (GVSB(builder)->type);
2667 GVSB(builder)->min_items = 2;
2668 GVSB(builder)->max_items = 2;
2671 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
2672 GVSB(builder)->uniform_item_types = FALSE;
2673 GVSB(builder)->allocated_children = 8;
2674 GVSB(builder)->expected_type = NULL;
2675 GVSB(builder)->min_items = 0;
2676 GVSB(builder)->max_items = -1;
2679 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
2680 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
2681 GVSB(builder)->expected_type =
2682 g_variant_type_first (GVSB(builder)->type);
2683 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
2684 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
2685 GVSB(builder)->uniform_item_types = FALSE;
2689 g_assert_not_reached ();
2692 GVSB(builder)->children = g_new (GVariant *,
2693 GVSB(builder)->allocated_children);
2697 g_variant_builder_make_room (struct stack_builder *builder)
2699 if (builder->offset == builder->allocated_children)
2701 builder->allocated_children *= 2;
2702 builder->children = g_renew (GVariant *, builder->children,
2703 builder->allocated_children);
2708 * g_variant_builder_add_value:
2709 * @builder: a #GVariantBuilder
2710 * @value: a #GVariant
2712 * Adds @value to @builder.
2714 * It is an error to call this function in any way that would create an
2715 * inconsistent value to be constructed. Some examples of this are
2716 * putting different types of items into an array, putting the wrong
2717 * types or number of items in a tuple, putting more than one value into
2723 g_variant_builder_add_value (GVariantBuilder *builder,
2726 g_return_if_fail (is_valid_builder (builder));
2727 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2728 g_return_if_fail (!GVSB(builder)->expected_type ||
2729 g_variant_is_of_type (value,
2730 GVSB(builder)->expected_type));
2731 g_return_if_fail (!GVSB(builder)->prev_item_type ||
2732 g_variant_is_of_type (value,
2733 GVSB(builder)->prev_item_type));
2735 GVSB(builder)->trusted &= g_variant_is_trusted (value);
2737 if (!GVSB(builder)->uniform_item_types)
2739 /* advance our expected type pointers */
2740 if (GVSB(builder)->expected_type)
2741 GVSB(builder)->expected_type =
2742 g_variant_type_next (GVSB(builder)->expected_type);
2744 if (GVSB(builder)->prev_item_type)
2745 GVSB(builder)->prev_item_type =
2746 g_variant_type_next (GVSB(builder)->prev_item_type);
2749 GVSB(builder)->prev_item_type = g_variant_get_type (value);
2751 g_variant_builder_make_room (GVSB(builder));
2753 GVSB(builder)->children[GVSB(builder)->offset++] =
2754 g_variant_ref_sink (value);
2758 * g_variant_builder_open:
2759 * @builder: a #GVariantBuilder
2760 * @type: a #GVariantType
2762 * Opens a subcontainer inside the given @builder. When done adding
2763 * items to the subcontainer, g_variant_builder_close() must be called.
2765 * It is an error to call this function in any way that would cause an
2766 * inconsistent value to be constructed (ie: adding too many values or
2767 * a value of an incorrect type).
2772 g_variant_builder_open (GVariantBuilder *builder,
2773 const GVariantType *type)
2775 GVariantBuilder *parent;
2777 g_return_if_fail (is_valid_builder (builder));
2778 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2779 g_return_if_fail (!GVSB(builder)->expected_type ||
2780 g_variant_type_is_subtype_of (type,
2781 GVSB(builder)->expected_type));
2782 g_return_if_fail (!GVSB(builder)->prev_item_type ||
2783 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
2786 parent = g_slice_dup (GVariantBuilder, builder);
2787 g_variant_builder_init (builder, type);
2788 GVSB(builder)->parent = parent;
2790 /* push the prev_item_type down into the subcontainer */
2791 if (GVSB(parent)->prev_item_type)
2793 if (!GVSB(builder)->uniform_item_types)
2794 /* tuples and dict entries */
2795 GVSB(builder)->prev_item_type =
2796 g_variant_type_first (GVSB(parent)->prev_item_type);
2798 else if (!g_variant_type_is_variant (GVSB(builder)->type))
2799 /* maybes and arrays */
2800 GVSB(builder)->prev_item_type =
2801 g_variant_type_element (GVSB(parent)->prev_item_type);
2806 * g_variant_builder_close:
2807 * @builder: a #GVariantBuilder
2809 * Closes the subcontainer inside the given @builder that was opened by
2810 * the most recent call to g_variant_builder_open().
2812 * It is an error to call this function in any way that would create an
2813 * inconsistent value to be constructed (ie: too few values added to the
2819 g_variant_builder_close (GVariantBuilder *builder)
2821 GVariantBuilder *parent;
2823 g_return_if_fail (is_valid_builder (builder));
2824 g_return_if_fail (GVSB(builder)->parent != NULL);
2826 parent = GVSB(builder)->parent;
2827 GVSB(builder)->parent = NULL;
2829 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
2832 g_slice_free (GVariantBuilder, parent);
2836 * g_variant_make_maybe_type:
2837 * @element: a #GVariant
2839 * Return the type of a maybe containing @element.
2841 static GVariantType *
2842 g_variant_make_maybe_type (GVariant *element)
2844 return g_variant_type_new_maybe (g_variant_get_type (element));
2848 * g_variant_make_array_type:
2849 * @element: a #GVariant
2851 * Return the type of an array containing @element.
2853 static GVariantType *
2854 g_variant_make_array_type (GVariant *element)
2856 return g_variant_type_new_array (g_variant_get_type (element));
2860 * g_variant_builder_end:
2861 * @builder: a #GVariantBuilder
2862 * @returns: a new, floating, #GVariant
2864 * Ends the builder process and returns the constructed value.
2866 * It is not permissible to use @builder in any way after this call
2867 * except for reference counting operations (in the case of a
2868 * heap-allocated #GVariantBuilder) or by reinitialising it with
2869 * g_variant_builder_init() (in the case of stack-allocated).
2871 * It is an error to call this function in any way that would create an
2872 * inconsistent value to be constructed (ie: insufficient number of
2873 * items added to a container with a specific number of children
2874 * required). It is also an error to call this function if the builder
2875 * was created with an indefinite array or maybe type and no children
2876 * have been added; in this case it is impossible to infer the type of
2882 g_variant_builder_end (GVariantBuilder *builder)
2884 GVariantType *my_type;
2887 g_return_val_if_fail (is_valid_builder (builder), NULL);
2888 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
2890 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
2891 GVSB(builder)->prev_item_type != NULL ||
2892 g_variant_type_is_definite (GVSB(builder)->type),
2895 if (g_variant_type_is_definite (GVSB(builder)->type))
2896 my_type = g_variant_type_copy (GVSB(builder)->type);
2898 else if (g_variant_type_is_maybe (GVSB(builder)->type))
2899 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
2901 else if (g_variant_type_is_array (GVSB(builder)->type))
2902 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
2904 else if (g_variant_type_is_tuple (GVSB(builder)->type))
2905 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
2906 GVSB(builder)->offset);
2908 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
2909 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
2910 GVSB(builder)->children[1]);
2912 g_assert_not_reached ();
2914 value = g_variant_new_from_children (my_type,
2915 g_renew (GVariant *,
2916 GVSB(builder)->children,
2917 GVSB(builder)->offset),
2918 GVSB(builder)->offset,
2919 GVSB(builder)->trusted);
2920 GVSB(builder)->children = NULL;
2921 GVSB(builder)->offset = 0;
2923 g_variant_builder_clear (builder);
2924 g_variant_type_free (my_type);
2929 /* Format strings {{{1 */
2931 * g_variant_format_string_scan:
2932 * @string: a string that may be prefixed with a format string
2933 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
2935 * @endptr: (allow-none) (default NULL): location to store the end pointer,
2937 * @returns: %TRUE if there was a valid format string
2939 * Checks the string pointed to by @string for starting with a properly
2940 * formed #GVariant varargs format string. If no valid format string is
2941 * found then %FALSE is returned.
2943 * If @string does start with a valid format string then %TRUE is
2944 * returned. If @endptr is non-%NULL then it is updated to point to the
2945 * first character after the format string.
2947 * If @limit is non-%NULL then @limit (and any charater after it) will
2948 * not be accessed and the effect is otherwise equivalent to if the
2949 * character at @limit were nul.
2951 * See the section on <link linkend='gvariant-format-strings'>GVariant
2952 * Format Strings</link>.
2957 g_variant_format_string_scan (const gchar *string,
2959 const gchar **endptr)
2961 #define next_char() (string == limit ? '\0' : *string++)
2962 #define peek_char() (string == limit ? '\0' : *string)
2965 switch (next_char())
2967 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
2968 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
2969 case 'g': case 'v': case '*': case '?': case 'r':
2973 return g_variant_format_string_scan (string, limit, endptr);
2977 return g_variant_type_string_scan (string, limit, endptr);
2980 while (peek_char() != ')')
2981 if (!g_variant_format_string_scan (string, limit, &string))
2984 next_char(); /* consume ')' */
2994 if (c != 's' && c != 'o' && c != 'g')
3002 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3003 * The terminating null character is considered to be
3004 * part of the string.
3006 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3010 if (!g_variant_format_string_scan (string, limit, &string))
3013 if (next_char() != '}')
3018 case '^': /* '^as' or '^a&s' only */
3019 if (next_char() != 'a')
3022 if (peek_char() == '&')
3027 if (c != 's' && c != 'o' && c != 'g')
3035 if (c != 's' && c != 'o' && c != 'g')
3054 * g_variant_format_string_scan_type:
3055 * @string: a string that may be prefixed with a format string
3056 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3058 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3060 * @returns: (allow-none): a #GVariantType if there was a valid format string
3062 * If @string starts with a valid format string then this function will
3063 * return the type that the format string corresponds to. Otherwise
3064 * this function returns %NULL.
3066 * Use g_variant_type_free() to free the return value when you no longer
3069 * This function is otherwise exactly like
3070 * g_variant_format_string_scan().
3075 g_variant_format_string_scan_type (const gchar *string,
3077 const gchar **endptr)
3079 const gchar *my_end;
3086 if (!g_variant_format_string_scan (string, limit, endptr))
3089 dest = new = g_malloc (*endptr - string + 1);
3090 while (string != *endptr)
3092 if (*string != '@' && *string != '&' && *string != '^')
3098 return (GVariantType *) G_VARIANT_TYPE (new);
3102 valid_format_string (const gchar *format_string,
3106 const gchar *endptr;
3109 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3111 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3114 g_critical ("`%s' is not a valid GVariant format string",
3117 g_critical ("`%s' does not have a valid GVariant format "
3118 "string as a prefix", format_string);
3121 g_variant_type_free (type);
3126 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3131 fragment = g_strndup (format_string, endptr - format_string);
3132 typestr = g_variant_type_dup_string (type);
3134 g_critical ("the GVariant format string `%s' has a type of "
3135 "`%s' but the given value has a type of `%s'",
3136 fragment, typestr, g_variant_get_type_string (value));
3138 g_variant_type_free (type);
3143 g_variant_type_free (type);
3148 /* Variable Arguments {{{1 */
3149 /* We consider 2 main classes of format strings:
3151 * - recursive format strings
3152 * these are ones that result in recursion and the collection of
3153 * possibly more than one argument. Maybe types, tuples,
3154 * dictionary entries.
3156 * - leaf format string
3157 * these result in the collection of a single argument.
3159 * Leaf format strings are further subdivided into two categories:
3161 * - single non-null pointer ("nnp")
3162 * these either collect or return a single non-null pointer.
3165 * these collect or return something else (bool, number, etc).
3167 * Based on the above, the varargs handling code is split into 4 main parts:
3169 * - nnp handling code
3170 * - leaf handling code (which may invoke nnp code)
3171 * - generic handling code (may be recursive, may invoke leaf code)
3172 * - user-facing API (which invokes the generic code)
3174 * Each section implements some of the following functions:
3177 * collect the arguments for the format string as if
3178 * g_variant_new() had been called, but do nothing with them. used
3179 * for skipping over arguments when constructing a Nothing maybe
3183 * create a GVariant *
3186 * unpack a GVariant *
3188 * - free (nnp only):
3189 * free a previously allocated item
3193 g_variant_format_string_is_leaf (const gchar *str)
3195 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
3199 g_variant_format_string_is_nnp (const gchar *str)
3201 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
3202 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
3203 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
3206 /* Single non-null pointer ("nnp") {{{2 */
3208 g_variant_valist_free_nnp (const gchar *str,
3214 g_variant_iter_free (ptr);
3218 if (str[2] != '&') /* '^as' */
3234 g_variant_unref (ptr);
3241 g_assert_not_reached ();
3246 g_variant_valist_new_nnp (const gchar **str,
3256 const GVariantType *type;
3259 value = g_variant_builder_end (ptr);
3260 type = g_variant_get_type (value);
3262 if G_UNLIKELY (!g_variant_type_is_array (type))
3263 g_error ("g_variant_new: expected array GVariantBuilder but "
3264 "the built value has type `%s'",
3265 g_variant_get_type_string (value));
3267 type = g_variant_type_element (type);
3269 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
3270 g_error ("g_variant_new: expected GVariantBuilder array element "
3271 "type `%s' but the built value has element type `%s'",
3272 g_variant_type_dup_string ((GVariantType *) *str),
3273 g_variant_get_type_string (value) + 1);
3275 g_variant_type_string_scan (*str, NULL, str);
3281 return g_variant_new_string (ptr);
3284 return g_variant_new_object_path (ptr);
3287 return g_variant_new_signature (ptr);
3291 const GVariantType *type;
3292 GVariantType *array_type;
3293 GVariant **children;
3298 if ((*str)[1] == '&') /* '^a&s' */
3303 type = (GVariantType *) (*str)++;
3304 array_type = g_variant_type_new_array (type);
3305 length = g_strv_length (strv);
3306 children = g_new (GVariant *, length);
3307 for (i = 0; i < length; i++)
3308 children[i] = g_variant_ref_sink (
3309 g_variant_new_from_trusted (type, strv[i], strlen (strv[i]) + 1));
3311 value = g_variant_new_from_children (array_type, children,
3313 g_variant_type_free (array_type);
3319 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
3320 g_error ("g_variant_new: expected GVariant of type `%s' but "
3321 "received value has type `%s'",
3322 g_variant_type_dup_string ((GVariantType *) *str),
3323 g_variant_get_type_string (ptr));
3325 g_variant_type_string_scan (*str, NULL, str);
3333 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
3334 g_error ("g_variant_new: format string `?' expects basic-typed "
3335 "GVariant, but received value has type `%s'",
3336 g_variant_get_type_string (ptr));
3341 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
3342 g_error ("g_variant_new: format string `r` expects tuple-typed "
3343 "GVariant, but received value has type `%s'",
3344 g_variant_get_type_string (ptr));
3349 return g_variant_new_variant (ptr);
3352 g_assert_not_reached ();
3357 g_variant_valist_get_nnp (const gchar **str,
3363 g_variant_type_string_scan (*str, NULL, str);
3364 return g_variant_iter_new (value);
3368 return (gchar *) g_variant_get_string (value, NULL);
3373 return g_variant_dup_string (value, NULL);
3376 if ((*str)[1] == '&') /* '^a&s' */
3379 return g_variant_get_strv (value, NULL);
3384 return g_variant_dup_strv (value, NULL);
3388 g_variant_type_string_scan (*str, NULL, str);
3394 return g_variant_ref (value);
3397 return g_variant_get_variant (value);
3400 g_assert_not_reached ();
3406 g_variant_valist_skip_leaf (const gchar **str,
3409 if (g_variant_format_string_is_nnp (*str))
3411 g_variant_format_string_scan (*str, NULL, str);
3412 va_arg (*app, gpointer);
3430 va_arg (*app, guint64);
3434 va_arg (*app, gdouble);
3438 g_assert_not_reached ();
3443 g_variant_valist_new_leaf (const gchar **str,
3446 if (g_variant_format_string_is_nnp (*str))
3447 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
3452 return g_variant_new_boolean (va_arg (*app, gboolean));
3455 return g_variant_new_byte (va_arg (*app, guint));
3458 return g_variant_new_int16 (va_arg (*app, gint));
3461 return g_variant_new_uint16 (va_arg (*app, guint));
3464 return g_variant_new_int32 (va_arg (*app, gint));
3467 return g_variant_new_uint32 (va_arg (*app, guint));
3470 return g_variant_new_int64 (va_arg (*app, gint64));
3473 return g_variant_new_uint64 (va_arg (*app, guint64));
3476 return g_variant_new_handle (va_arg (*app, gint));
3479 return g_variant_new_double (va_arg (*app, gdouble));
3482 g_assert_not_reached ();
3486 /* The code below assumes this */
3487 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
3488 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
3491 g_variant_valist_get_leaf (const gchar **str,
3496 gpointer ptr = va_arg (*app, gpointer);
3500 g_variant_format_string_scan (*str, NULL, str);
3504 if (g_variant_format_string_is_nnp (*str))
3506 gpointer *nnp = (gpointer *) ptr;
3508 if (free && *nnp != NULL)
3509 g_variant_valist_free_nnp (*str, *nnp);
3514 *nnp = g_variant_valist_get_nnp (str, value);
3516 g_variant_format_string_scan (*str, NULL, str);
3526 *(gboolean *) ptr = g_variant_get_boolean (value);
3530 *(guchar *) ptr = g_variant_get_byte (value);
3534 *(gint16 *) ptr = g_variant_get_int16 (value);
3538 *(guint16 *) ptr = g_variant_get_uint16 (value);
3542 *(gint32 *) ptr = g_variant_get_int32 (value);
3546 *(guint32 *) ptr = g_variant_get_uint32 (value);
3550 *(gint64 *) ptr = g_variant_get_int64 (value);
3554 *(guint64 *) ptr = g_variant_get_uint64 (value);
3558 *(gint32 *) ptr = g_variant_get_handle (value);
3562 *(gdouble *) ptr = g_variant_get_double (value);
3571 *(guchar *) ptr = 0;
3576 *(guint16 *) ptr = 0;
3583 *(guint32 *) ptr = 0;
3589 *(guint64 *) ptr = 0;
3594 g_assert_not_reached ();
3597 /* Generic (recursive) {{{2 */
3599 g_variant_valist_skip (const gchar **str,
3602 if (g_variant_format_string_is_leaf (*str))
3603 g_variant_valist_skip_leaf (str, app);
3605 else if (**str == 'm') /* maybe */
3609 if (!g_variant_format_string_is_nnp (*str))
3610 va_arg (*app, gboolean);
3612 g_variant_valist_skip (str, app);
3614 else /* tuple, dictionary entry */
3616 g_assert (**str == '(' || **str == '{');
3618 while (**str != ')' && **str != '}')
3619 g_variant_valist_skip (str, app);
3625 g_variant_valist_new (const gchar **str,
3628 if (g_variant_format_string_is_leaf (*str))
3629 return g_variant_valist_new_leaf (str, app);
3631 if (**str == 'm') /* maybe */
3633 GVariantType *type = NULL;
3634 GVariant *value = NULL;
3638 if (g_variant_format_string_is_nnp (*str))
3640 gpointer nnp = va_arg (*app, gpointer);
3643 value = g_variant_valist_new_nnp (str, nnp);
3645 type = g_variant_format_string_scan_type (*str, NULL, str);
3649 gboolean just = va_arg (*app, gboolean);
3652 value = g_variant_valist_new (str, app);
3655 type = g_variant_format_string_scan_type (*str, NULL, NULL);
3656 g_variant_valist_skip (str, app);
3660 value = g_variant_new_maybe (type, value);
3663 g_variant_type_free (type);
3667 else /* tuple, dictionary entry */
3672 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
3675 g_assert (**str == '{');
3676 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
3680 while (**str != ')' && **str != '}')
3681 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
3684 return g_variant_builder_end (&b);
3689 g_variant_valist_get (const gchar **str,
3694 if (g_variant_format_string_is_leaf (*str))
3695 g_variant_valist_get_leaf (str, value, free, app);
3697 else if (**str == 'm')
3702 value = g_variant_get_maybe (value);
3704 if (!g_variant_format_string_is_nnp (*str))
3706 gboolean *ptr = va_arg (*app, gboolean *);
3709 *ptr = value != NULL;
3712 g_variant_valist_get (str, value, free, app);
3715 g_variant_unref (value);
3718 else /* tuple, dictionary entry */
3722 g_assert (**str == '(' || **str == '{');
3725 while (**str != ')' && **str != '}')
3729 GVariant *child = g_variant_get_child_value (value, index++);
3730 g_variant_valist_get (str, child, free, app);
3731 g_variant_unref (child);
3734 g_variant_valist_get (str, NULL, free, app);
3740 /* User-facing API {{{2 */
3743 * @format_string: a #GVariant format string
3744 * @...: arguments, as per @format_string
3745 * @returns: a new floating #GVariant instance
3747 * Creates a new #GVariant instance.
3749 * Think of this function as an analogue to g_strdup_printf().
3751 * The type of the created instance and the arguments that are
3752 * expected by this function are determined by @format_string. See the
3753 * section on <link linkend='gvariant-format-strings'>GVariant Format
3754 * Strings</link>. Please note that the syntax of the format string is
3755 * very likely to be extended in the future.
3757 * The first character of the format string must not be '*' '?' '@' or
3758 * 'r'; in essence, a new #GVariant must always be constructed by this
3759 * function (and not merely passed through it unmodified).
3764 g_variant_new (const gchar *format_string,
3770 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
3771 format_string[0] != '?' && format_string[0] != '@' &&
3772 format_string[0] != '*' && format_string[0] != 'r',
3775 va_start (ap, format_string);
3776 value = g_variant_new_va (format_string, NULL, &ap);
3784 * @format_string: a string that is prefixed with a format string
3785 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3787 * @app: a pointer to a #va_list
3788 * @returns: a new, usually floating, #GVariant
3790 * This function is intended to be used by libraries based on
3791 * #GVariant that want to provide g_variant_new()-like functionality
3794 * The API is more general than g_variant_new() to allow a wider range
3797 * @format_string must still point to a valid format string, but it only
3798 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
3799 * non-%NULL then it is updated to point to the first character past the
3800 * end of the format string.
3802 * @app is a pointer to a #va_list. The arguments, according to
3803 * @format_string, are collected from this #va_list and the list is left
3804 * pointing to the argument following the last.
3806 * These two generalisations allow mixing of multiple calls to
3807 * g_variant_new_va() and g_variant_get_va() within a single actual
3808 * varargs call by the user.
3810 * The return value will be floating if it was a newly created GVariant
3811 * instance (for example, if the format string was "(ii)"). In the case
3812 * that the format_string was '*', '?', 'r', or a format starting with
3813 * '@' then the collected #GVariant pointer will be returned unmodified,
3814 * without adding any additional references.
3816 * In order to behave correctly in all cases it is necessary for the
3817 * calling function to g_variant_ref_sink() the return result before
3818 * returning control to the user that originally provided the pointer.
3819 * At this point, the caller will have their own full reference to the
3820 * result. This can also be done by adding the result to a container,
3821 * or by passing it to another g_variant_new() call.
3826 g_variant_new_va (const gchar *format_string,
3827 const gchar **endptr,
3832 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
3834 g_return_val_if_fail (app != NULL, NULL);
3836 value = g_variant_valist_new (&format_string, app);
3839 *endptr = format_string;
3846 * @value: a #GVariant instance
3847 * @format_string: a #GVariant format string
3848 * @...: arguments, as per @format_string
3850 * Deconstructs a #GVariant instance.
3852 * Think of this function as an analogue to scanf().
3854 * The arguments that are expected by this function are entirely
3855 * determined by @format_string. @format_string also restricts the
3856 * permissible types of @value. It is an error to give a value with
3857 * an incompatible type. See the section on <link
3858 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
3859 * Please note that the syntax of the format string is very likely to be
3860 * extended in the future.
3865 g_variant_get (GVariant *value,
3866 const gchar *format_string,
3871 g_return_if_fail (valid_format_string (format_string, TRUE, value));
3873 /* if any direct-pointer-access formats are in use, flatten first */
3874 if (strchr (format_string, '&'))
3875 g_variant_get_data (value);
3877 va_start (ap, format_string);
3878 g_variant_get_va (value, format_string, NULL, &ap);
3884 * @value: a #GVariant
3885 * @format_string: a string that is prefixed with a format string
3886 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3888 * @app: a pointer to a #va_list
3890 * This function is intended to be used by libraries based on #GVariant
3891 * that want to provide g_variant_get()-like functionality to their
3894 * The API is more general than g_variant_get() to allow a wider range
3897 * @format_string must still point to a valid format string, but it only
3898 * need to be nul-terminated if @endptr is %NULL. If @endptr is
3899 * non-%NULL then it is updated to point to the first character past the
3900 * end of the format string.
3902 * @app is a pointer to a #va_list. The arguments, according to
3903 * @format_string, are collected from this #va_list and the list is left
3904 * pointing to the argument following the last.
3906 * These two generalisations allow mixing of multiple calls to
3907 * g_variant_new_va() and g_variant_get_va() within a single actual
3908 * varargs call by the user.
3913 g_variant_get_va (GVariant *value,
3914 const gchar *format_string,
3915 const gchar **endptr,
3918 g_return_if_fail (valid_format_string (format_string, !endptr, value));
3919 g_return_if_fail (value != NULL);
3920 g_return_if_fail (app != NULL);
3922 /* if any direct-pointer-access formats are in use, flatten first */
3923 if (strchr (format_string, '&'))
3924 g_variant_get_data (value);
3926 g_variant_valist_get (&format_string, value, FALSE, app);
3929 *endptr = format_string;
3932 /* Varargs-enabled Utility Functions {{{1 */
3935 * g_variant_builder_add:
3936 * @builder: a #GVariantBuilder
3937 * @format_string: a #GVariant varargs format string
3938 * @...: arguments, as per @format_string
3940 * Adds to a #GVariantBuilder.
3942 * This call is a convenience wrapper that is exactly equivalent to
3943 * calling g_variant_new() followed by g_variant_builder_add_value().
3945 * This function might be used as follows:
3949 * make_pointless_dictionary (void)
3951 * GVariantBuilder *builder;
3954 * builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3955 * for (i = 0; i < 16; i++)
3959 * sprintf (buf, "%d", i);
3960 * g_variant_builder_add (builder, "{is}", i, buf);
3963 * return g_variant_builder_end (builder);
3970 g_variant_builder_add (GVariantBuilder *builder,
3971 const gchar *format_string,
3977 va_start (ap, format_string);
3978 variant = g_variant_new_va (format_string, NULL, &ap);
3981 g_variant_builder_add_value (builder, variant);
3985 * g_variant_get_child:
3986 * @value: a container #GVariant
3987 * @index_: the index of the child to deconstruct
3988 * @format_string: a #GVariant format string
3989 * @...: arguments, as per @format_string
3991 * Reads a child item out of a container #GVariant instance and
3992 * deconstructs it according to @format_string. This call is
3993 * essentially a combination of g_variant_get_child_value() and
3999 g_variant_get_child (GVariant *value,
4001 const gchar *format_string,
4007 child = g_variant_get_child_value (value, index_);
4008 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4010 va_start (ap, format_string);
4011 g_variant_get_va (child, format_string, NULL, &ap);
4014 g_variant_unref (child);
4018 * g_variant_iter_next:
4019 * @iter: a #GVariantIter
4020 * @format_string: a GVariant format string
4021 * @...: the arguments to unpack the value into
4022 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4025 * Gets the next item in the container and unpacks it into the variable
4026 * argument list according to @format_string, returning %TRUE.
4028 * If no more items remain then %FALSE is returned.
4030 * All of the pointers given on the variable arguments list of this
4031 * function are assumed to point at uninitialised memory. It is the
4032 * responsibility of the caller to free all of the values returned by
4033 * the unpacking process.
4035 * See the section on <link linkend='gvariant-format-strings'>GVariant
4036 * Format Strings</link>.
4039 * <title>Memory management with g_variant_iter_next()</title>
4041 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4043 * iterate_dictionary (GVariant *dictionary)
4045 * GVariantIter iter;
4049 * g_variant_iter_init (&iter, dictionary);
4050 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4052 * g_print ("Item '%s' has type '%s'\n", key,
4053 * g_variant_get_type_string (value));
4055 * /<!-- -->* must free data for ourselves *<!-- -->/
4056 * g_variant_unref (value);
4063 * For a solution that is likely to be more convenient to C programmers
4064 * when dealing with loops, see g_variant_iter_loop().
4069 g_variant_iter_next (GVariantIter *iter,
4070 const gchar *format_string,
4075 value = g_variant_iter_next_value (iter);
4077 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
4084 va_start (ap, format_string);
4085 g_variant_valist_get (&format_string, value, FALSE, &ap);
4088 g_variant_unref (value);
4091 return value != NULL;
4095 * g_variant_iter_loop:
4096 * @iter: a #GVariantIter
4097 * @format_string: a GVariant format string
4098 * @...: the arguments to unpack the value into
4099 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4102 * Gets the next item in the container and unpacks it into the variable
4103 * argument list according to @format_string, returning %TRUE.
4105 * If no more items remain then %FALSE is returned.
4107 * On the first call to this function, the pointers appearing on the
4108 * variable argument list are assumed to point at uninitialised memory.
4109 * On the second and later calls, it is assumed that the same pointers
4110 * will be given and that they will point to the memory as set by the
4111 * previous call to this function. This allows the previous values to
4112 * be freed, as appropriate.
4114 * This function is intended to be used with a while loop as
4115 * demonstrated in the following example. This function can only be
4116 * used when iterating over an array. It is only valid to call this
4117 * function with a string constant for the format string and the same
4118 * string constant must be used each time. Mixing calls to this
4119 * function and g_variant_iter_next() or g_variant_iter_next_value() on
4120 * the same iterator is not recommended.
4122 * See the section on <link linkend='gvariant-format-strings'>GVariant
4123 * Format Strings</link>.
4126 * <title>Memory management with g_variant_iter_loop()</title>
4128 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4130 * iterate_dictionary (GVariant *dictionary)
4132 * GVariantIter iter;
4136 * g_variant_iter_init (&iter, dictionary);
4137 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
4139 * g_print ("Item '%s' has type '%s'\n", key,
4140 * g_variant_get_type_string (value));
4142 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
4148 * If you want a slightly less magical alternative that requires more
4149 * typing, see g_variant_iter_next().
4154 g_variant_iter_loop (GVariantIter *iter,
4155 const gchar *format_string,
4158 gboolean first_time = GVSI(iter)->loop_format == NULL;
4162 g_return_val_if_fail (first_time ||
4163 format_string == GVSI(iter)->loop_format,
4168 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
4169 GVSI(iter)->loop_format = format_string;
4171 if (strchr (format_string, '&'))
4172 g_variant_get_data (GVSI(iter)->value);
4175 value = g_variant_iter_next_value (iter);
4177 g_return_val_if_fail (!first_time ||
4178 valid_format_string (format_string, TRUE, value),
4181 va_start (ap, format_string);
4182 g_variant_valist_get (&format_string, value, !first_time, &ap);
4186 g_variant_unref (value);
4188 return value != NULL;
4191 /* Serialised data {{{1 */
4193 g_variant_deep_copy (GVariant *value)
4195 switch (g_variant_classify (value))
4197 case G_VARIANT_CLASS_MAYBE:
4198 case G_VARIANT_CLASS_ARRAY:
4199 case G_VARIANT_CLASS_TUPLE:
4200 case G_VARIANT_CLASS_DICT_ENTRY:
4201 case G_VARIANT_CLASS_VARIANT:
4203 GVariantBuilder builder;
4207 g_variant_builder_init (&builder, g_variant_get_type (value));
4208 g_variant_iter_init (&iter, value);
4210 while ((child = g_variant_iter_next_value (&iter)))
4212 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
4213 g_variant_unref (child);
4216 return g_variant_builder_end (&builder);
4219 case G_VARIANT_CLASS_BOOLEAN:
4220 return g_variant_new_boolean (g_variant_get_boolean (value));
4222 case G_VARIANT_CLASS_BYTE:
4223 return g_variant_new_byte (g_variant_get_byte (value));
4225 case G_VARIANT_CLASS_INT16:
4226 return g_variant_new_int16 (g_variant_get_int16 (value));
4228 case G_VARIANT_CLASS_UINT16:
4229 return g_variant_new_uint16 (g_variant_get_uint16 (value));
4231 case G_VARIANT_CLASS_INT32:
4232 return g_variant_new_int32 (g_variant_get_int32 (value));
4234 case G_VARIANT_CLASS_UINT32:
4235 return g_variant_new_uint32 (g_variant_get_uint32 (value));
4237 case G_VARIANT_CLASS_INT64:
4238 return g_variant_new_int64 (g_variant_get_int64 (value));
4240 case G_VARIANT_CLASS_UINT64:
4241 return g_variant_new_uint64 (g_variant_get_uint64 (value));
4243 case G_VARIANT_CLASS_HANDLE:
4244 return g_variant_new_handle (g_variant_get_handle (value));
4246 case G_VARIANT_CLASS_DOUBLE:
4247 return g_variant_new_double (g_variant_get_double (value));
4249 case G_VARIANT_CLASS_STRING:
4250 return g_variant_new_string (g_variant_get_string (value, NULL));
4252 case G_VARIANT_CLASS_OBJECT_PATH:
4253 return g_variant_new_object_path (g_variant_get_string (value, NULL));
4255 case G_VARIANT_CLASS_SIGNATURE:
4256 return g_variant_new_signature (g_variant_get_string (value, NULL));
4259 g_assert_not_reached ();
4263 * g_variant_get_normal_form:
4264 * @value: a #GVariant
4265 * @returns: a trusted #GVariant
4267 * Gets a #GVariant instance that has the same value as @value and is
4268 * trusted to be in normal form.
4270 * If @value is already trusted to be in normal form then a new
4271 * reference to @value is returned.
4273 * If @value is not already trusted, then it is scanned to check if it
4274 * is in normal form. If it is found to be in normal form then it is
4275 * marked as trusted and a new reference to it is returned.
4277 * If @value is found not to be in normal form then a new trusted
4278 * #GVariant is created with the same value as @value.
4280 * It makes sense to call this function if you've received #GVariant
4281 * data from untrusted sources and you want to ensure your serialised
4282 * output is definitely in normal form.
4287 g_variant_get_normal_form (GVariant *value)
4291 if (g_variant_is_normal_form (value))
4292 return g_variant_ref (value);
4294 trusted = g_variant_deep_copy (value);
4295 g_assert (g_variant_is_trusted (trusted));
4297 return g_variant_ref_sink (trusted);
4301 * g_variant_byteswap:
4302 * @value: a #GVariant
4303 * @returns: the byteswapped form of @value
4305 * Performs a byteswapping operation on the contents of @value. The
4306 * result is that all multi-byte numeric data contained in @value is
4307 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
4308 * integers as well as file handles and double precision floating point
4311 * This function is an identity mapping on any value that does not
4312 * contain multi-byte numeric data. That include strings, booleans,
4313 * bytes and containers containing only these things (recursively).
4315 * The returned value is always in normal form and is marked as trusted.
4320 g_variant_byteswap (GVariant *value)
4322 GVariantSerialised serialised;
4327 trusted = g_variant_get_normal_form (value);
4328 serialised.type_info = g_variant_get_type_info (trusted);
4329 serialised.size = g_variant_get_size (trusted);
4330 serialised.data = g_malloc (serialised.size);
4331 g_variant_store (trusted, serialised.data);
4332 g_variant_unref (trusted);
4334 g_variant_serialised_byteswap (serialised);
4336 buffer = g_buffer_new_take_data (serialised.data, serialised.size);
4337 new = g_variant_new_from_buffer (g_variant_get_type (value), buffer, TRUE);
4338 g_buffer_unref (buffer);
4340 return g_variant_ref_sink (new);
4344 * g_variant_new_from_data:
4345 * @type: a definite #GVariantType
4346 * @data: the serialised data
4347 * @size: the size of @data
4348 * @trusted: %TRUE if @data is definitely in normal form
4349 * @notify: function to call when @data is no longer needed
4350 * @user_data: data for @notify
4351 * @returns: a new floating #GVariant of type @type
4353 * Creates a new #GVariant instance from serialised data.
4355 * @type is the type of #GVariant instance that will be constructed.
4356 * The interpretation of @data depends on knowing the type.
4358 * @data is not modified by this function and must remain valid with an
4359 * unchanging value until such a time as @notify is called with
4360 * @user_data. If the contents of @data change before that time then
4361 * the result is undefined.
4363 * If @data is trusted to be serialised data in normal form then
4364 * @trusted should be %TRUE. This applies to serialised data created
4365 * within this process or read from a trusted location on the disk (such
4366 * as a file installed in /usr/lib alongside your application). You
4367 * should set trusted to %FALSE if @data is read from the network, a
4368 * file in the user's home directory, etc.
4370 * @notify will be called with @user_data when @data is no longer
4371 * needed. The exact time of this call is unspecified and might even be
4372 * before this function returns.
4377 g_variant_new_from_data (const GVariantType *type,
4381 GDestroyNotify notify,
4387 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
4388 g_return_val_if_fail (data != NULL || size == 0, NULL);
4391 buffer = g_buffer_new_from_pointer (data, size, notify, user_data);
4393 buffer = g_buffer_new_from_static_data (data, size);
4395 value = g_variant_new_from_buffer (type, buffer, trusted);
4396 g_buffer_unref (buffer);
4402 #define __G_VARIANT_C__
4403 #include "galiasdef.c"
4405 /* vim:set foldmethod=marker: */