2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the licence, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: Ryan Lortie <desrt@desrt.ca>
27 #include <glib/gvariant-serialiser.h>
28 #include "gvariant-internal.h"
29 #include <glib/gvariant-core.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gstrfuncs.h>
32 #include <glib/gslice.h>
33 #include <glib/ghash.h>
34 #include <glib/gmem.h>
42 * @short_description: strongly typed value datatype
43 * @see_also: GVariantType
45 * #GVariant is a variant datatype; it stores a value along with
46 * information about the type of that value. The range of possible
47 * values is determined by the type. The type system used by #GVariant
50 * #GVariant instances always have a type and a value (which are given
51 * at construction time). The type and value of a #GVariant instance
52 * can never change other than by the #GVariant itself being
53 * destroyed. A #GVariant cannot contain a pointer.
55 * #GVariant is reference counted using g_variant_ref() and
56 * g_variant_unref(). #GVariant also has floating reference counts --
57 * see g_variant_ref_sink().
59 * #GVariant is completely threadsafe. A #GVariant instance can be
60 * concurrently accessed in any way from any number of threads without
63 * #GVariant is heavily optimised for dealing with data in serialised
64 * form. It works particularly well with data located in memory-mapped
65 * files. It can perform nearly all deserialisation operations in a
66 * small constant time, usually touching only a single memory page.
67 * Serialised #GVariant data can also be sent over the network.
69 * #GVariant is largely compatible with D-Bus. Almost all types of
70 * #GVariant instances can be sent over D-Bus. See #GVariantType for
71 * exceptions. (However, #GVariant's serialisation format is not the same
72 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
73 * in the gio library, for those.)
75 * For space-efficiency, the #GVariant serialisation format does not
76 * automatically include the variant's type or endianness, which must
77 * either be implied from context (such as knowledge that a particular
78 * file format always contains a little-endian %G_VARIANT_TYPE_VARIANT)
79 * or supplied out-of-band (for instance, a type and/or endianness
80 * indicator could be placed at the beginning of a file, network message
83 * For convenience to C programmers, #GVariant features powerful
84 * varargs-based value construction and destruction. This feature is
85 * designed to be embedded in other libraries.
87 * There is a Python-inspired text language for describing #GVariant
88 * values. #GVariant includes a printer for this language and a parser
89 * with type inferencing.
92 * <title>Memory Use</title>
94 * #GVariant tries to be quite efficient with respect to memory use.
95 * This section gives a rough idea of how much memory is used by the
96 * current implementation. The information here is subject to change
100 * The memory allocated by #GVariant can be grouped into 4 broad
101 * purposes: memory for serialised data, memory for the type
102 * information cache, buffer management memory and memory for the
103 * #GVariant structure itself.
105 * <refsect3 id="gvariant-serialised-data-memory">
106 * <title>Serialised Data Memory</title>
108 * This is the memory that is used for storing GVariant data in
109 * serialised form. This is what would be sent over the network or
110 * what would end up on disk.
113 * The amount of memory required to store a boolean is 1 byte. 16,
114 * 32 and 64 bit integers and double precision floating point numbers
115 * use their "natural" size. Strings (including object path and
116 * signature strings) are stored with a nul terminator, and as such
117 * use the length of the string plus 1 byte.
120 * Maybe types use no space at all to represent the null value and
121 * use the same amount of space (sometimes plus one byte) as the
122 * equivalent non-maybe-typed value to represent the non-null case.
125 * Arrays use the amount of space required to store each of their
126 * members, concatenated. Additionally, if the items stored in an
127 * array are not of a fixed-size (ie: strings, other arrays, etc)
128 * then an additional framing offset is stored for each item. The
129 * size of this offset is either 1, 2 or 4 bytes depending on the
130 * overall size of the container. Additionally, extra padding bytes
131 * are added as required for alignment of child values.
134 * Tuples (including dictionary entries) use the amount of space
135 * required to store each of their members, concatenated, plus one
136 * framing offset (as per arrays) for each non-fixed-sized item in
137 * the tuple, except for the last one. Additionally, extra padding
138 * bytes are added as required for alignment of child values.
141 * Variants use the same amount of space as the item inside of the
142 * variant, plus 1 byte, plus the length of the type string for the
143 * item inside the variant.
146 * As an example, consider a dictionary mapping strings to variants.
147 * In the case that the dictionary is empty, 0 bytes are required for
151 * If we add an item "width" that maps to the int32 value of 500 then
152 * we will use 4 byte to store the int32 (so 6 for the variant
153 * containing it) and 6 bytes for the string. The variant must be
154 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
155 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
156 * for the dictionary entry. An additional 1 byte is added to the
157 * array as a framing offset making a total of 15 bytes.
160 * If we add another entry, "title" that maps to a nullable string
161 * that happens to have a value of null, then we use 0 bytes for the
162 * null value (and 3 bytes for the variant to contain it along with
163 * its type string) plus 6 bytes for the string. Again, we need 2
164 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
167 * We now require extra padding between the two items in the array.
168 * After the 14 bytes of the first item, that's 2 bytes required. We
169 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
170 * + 2 = 29 bytes to encode the entire two-item dictionary.
174 * <title>Type Information Cache</title>
176 * For each GVariant type that currently exists in the program a type
177 * information structure is kept in the type information cache. The
178 * type information structure is required for rapid deserialisation.
181 * Continuing with the above example, if a #GVariant exists with the
182 * type "a{sv}" then a type information struct will exist for
183 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
184 * will share the same type information. Additionally, all
185 * single-digit types are stored in read-only static memory and do
186 * not contribute to the writable memory footprint of a program using
190 * Aside from the type information structures stored in read-only
191 * memory, there are two forms of type information. One is used for
192 * container types where there is a single element type: arrays and
193 * maybe types. The other is used for container types where there
194 * are multiple element types: tuples and dictionary entries.
197 * Array type info structures are 6 * sizeof (void *), plus the
198 * memory required to store the type string itself. This means that
199 * on 32bit systems, the cache entry for "a{sv}" would require 30
200 * bytes of memory (plus malloc overhead).
203 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
204 * sizeof (void *) for each item in the tuple, plus the memory
205 * required to store the type string itself. A 2-item tuple, for
206 * example, would have a type information structure that consumed
207 * writable memory in the size of 14 * sizeof (void *) (plus type
208 * string) This means that on 32bit systems, the cache entry for
209 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
212 * This means that in total, for our "a{sv}" example, 91 bytes of
213 * type information would be allocated.
216 * The type information cache, additionally, uses a #GHashTable to
217 * store and lookup the cached items and stores a pointer to this
218 * hash table in static storage. The hash table is freed when there
219 * are zero items in the type cache.
222 * Although these sizes may seem large it is important to remember
223 * that a program will probably only have a very small number of
224 * different types of values in it and that only one type information
225 * structure is required for many different values of the same type.
229 * <title>Buffer Management Memory</title>
231 * #GVariant uses an internal buffer management structure to deal
232 * with the various different possible sources of serialised data
233 * that it uses. The buffer is responsible for ensuring that the
234 * correct call is made when the data is no longer in use by
235 * #GVariant. This may involve a g_free() or a g_slice_free() or
236 * even g_mapped_file_unref().
239 * One buffer management structure is used for each chunk of
240 * serialised data. The size of the buffer management structure is 4
241 * * (void *). On 32bit systems, that's 16 bytes.
245 * <title>GVariant structure</title>
247 * The size of a #GVariant structure is 6 * (void *). On 32 bit
248 * systems, that's 24 bytes.
251 * #GVariant structures only exist if they are explicitly created
252 * with API calls. For example, if a #GVariant is constructed out of
253 * serialised data for the example given above (with the dictionary)
254 * then although there are 9 individual values that comprise the
255 * entire dictionary (two keys, two values, two variants containing
256 * the values, two dictionary entries, plus the dictionary itself),
257 * only 1 #GVariant instance exists -- the one referring to the
261 * If calls are made to start accessing the other values then
262 * #GVariant instances will exist for those values only for as long
263 * as they are in use (ie: until you call g_variant_unref()). The
264 * type information is shared. The serialised data and the buffer
265 * management structure for that serialised data is shared by the
270 * <title>Summary</title>
272 * To put the entire example together, for our dictionary mapping
273 * strings to variants (with two entries, as given above), we are
274 * using 91 bytes of memory for type information, 29 byes of memory
275 * for the serialised data, 16 bytes for buffer management and 24
276 * bytes for the #GVariant instance, or a total of 160 bytes, plus
277 * malloc overhead. If we were to use g_variant_get_child_value() to
278 * access the two dictionary entries, we would use an additional 48
279 * bytes. If we were to have other dictionaries of the same type, we
280 * would use more memory for the serialised data and buffer
281 * management for those dictionaries, but the type information would
288 /* definition of GVariant structure is in gvariant-core.c */
290 /* this is a g_return_val_if_fail() for making
291 * sure a (GVariant *) has the required type.
293 #define TYPE_CHECK(value, TYPE, val) \
294 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
295 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
296 "g_variant_is_of_type (" #value \
301 /* Numeric Type Constructor/Getters {{{1 */
303 * g_variant_new_from_trusted:
304 * @type: the #GVariantType
305 * @data: the data to use
306 * @size: the size of @data
307 * @returns: a new floating #GVariant
309 * Constructs a new trusted #GVariant instance from the provided data.
310 * This is used to implement g_variant_new_* for all the basic types.
313 g_variant_new_from_trusted (const GVariantType *type,
320 buffer = g_buffer_new_from_data (data, size);
321 value = g_variant_new_from_buffer (type, buffer, TRUE);
322 g_buffer_unref (buffer);
328 * g_variant_new_boolean:
329 * @value: a #gboolean value
330 * @returns: (transfer none): a floating reference to a new boolean #GVariant instance
332 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
337 g_variant_new_boolean (gboolean value)
341 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
345 * g_variant_get_boolean:
346 * @value: a boolean #GVariant instance
347 * @returns: %TRUE or %FALSE
349 * Returns the boolean value of @value.
351 * It is an error to call this function with a @value of any type
352 * other than %G_VARIANT_TYPE_BOOLEAN.
357 g_variant_get_boolean (GVariant *value)
361 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
363 data = g_variant_get_data (value);
365 return data != NULL ? *data != 0 : FALSE;
368 /* the constructors and accessors for byte, int{16,32,64}, handles and
369 * doubles all look pretty much exactly the same, so we reduce
372 #define NUMERIC_TYPE(TYPE, type, ctype) \
373 GVariant *g_variant_new_##type (ctype value) { \
374 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
375 &value, sizeof value); \
377 ctype g_variant_get_##type (GVariant *value) { \
379 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
380 data = g_variant_get_data (value); \
381 return data != NULL ? *data : 0; \
386 * g_variant_new_byte:
387 * @value: a #guint8 value
388 * @returns: (transfer none): a floating reference to a new byte #GVariant instance
390 * Creates a new byte #GVariant instance.
395 * g_variant_get_byte:
396 * @value: a byte #GVariant instance
397 * @returns: a #guchar
399 * Returns the byte value of @value.
401 * It is an error to call this function with a @value of any type
402 * other than %G_VARIANT_TYPE_BYTE.
406 NUMERIC_TYPE (BYTE, byte, guchar)
409 * g_variant_new_int16:
410 * @value: a #gint16 value
411 * @returns: (transfer none): a floating reference to a new int16 #GVariant instance
413 * Creates a new int16 #GVariant instance.
418 * g_variant_get_int16:
419 * @value: a int16 #GVariant instance
420 * @returns: a #gint16
422 * Returns the 16-bit signed integer value of @value.
424 * It is an error to call this function with a @value of any type
425 * other than %G_VARIANT_TYPE_INT16.
429 NUMERIC_TYPE (INT16, int16, gint16)
432 * g_variant_new_uint16:
433 * @value: a #guint16 value
434 * @returns: (transfer none): a floating reference to a new uint16 #GVariant instance
436 * Creates a new uint16 #GVariant instance.
441 * g_variant_get_uint16:
442 * @value: a uint16 #GVariant instance
443 * @returns: a #guint16
445 * Returns the 16-bit unsigned integer value of @value.
447 * It is an error to call this function with a @value of any type
448 * other than %G_VARIANT_TYPE_UINT16.
452 NUMERIC_TYPE (UINT16, uint16, guint16)
455 * g_variant_new_int32:
456 * @value: a #gint32 value
457 * @returns: (transfer none): a floating reference to a new int32 #GVariant instance
459 * Creates a new int32 #GVariant instance.
464 * g_variant_get_int32:
465 * @value: a int32 #GVariant instance
466 * @returns: a #gint32
468 * Returns the 32-bit signed integer value of @value.
470 * It is an error to call this function with a @value of any type
471 * other than %G_VARIANT_TYPE_INT32.
475 NUMERIC_TYPE (INT32, int32, gint32)
478 * g_variant_new_uint32:
479 * @value: a #guint32 value
480 * @returns: (transfer none): a floating reference to a new uint32 #GVariant instance
482 * Creates a new uint32 #GVariant instance.
487 * g_variant_get_uint32:
488 * @value: a uint32 #GVariant instance
489 * @returns: a #guint32
491 * Returns the 32-bit unsigned integer value of @value.
493 * It is an error to call this function with a @value of any type
494 * other than %G_VARIANT_TYPE_UINT32.
498 NUMERIC_TYPE (UINT32, uint32, guint32)
501 * g_variant_new_int64:
502 * @value: a #gint64 value
503 * @returns: (transfer none): a floating reference to a new int64 #GVariant instance
505 * Creates a new int64 #GVariant instance.
510 * g_variant_get_int64:
511 * @value: a int64 #GVariant instance
512 * @returns: a #gint64
514 * Returns the 64-bit signed integer value of @value.
516 * It is an error to call this function with a @value of any type
517 * other than %G_VARIANT_TYPE_INT64.
521 NUMERIC_TYPE (INT64, int64, gint64)
524 * g_variant_new_uint64:
525 * @value: a #guint64 value
526 * @returns: (transfer none): a floating reference to a new uint64 #GVariant instance
528 * Creates a new uint64 #GVariant instance.
533 * g_variant_get_uint64:
534 * @value: a uint64 #GVariant instance
535 * @returns: a #guint64
537 * Returns the 64-bit unsigned integer value of @value.
539 * It is an error to call this function with a @value of any type
540 * other than %G_VARIANT_TYPE_UINT64.
544 NUMERIC_TYPE (UINT64, uint64, guint64)
547 * g_variant_new_handle:
548 * @value: a #gint32 value
549 * @returns: (transfer none): a floating reference to a new handle #GVariant instance
551 * Creates a new handle #GVariant instance.
553 * By convention, handles are indexes into an array of file descriptors
554 * that are sent alongside a D-Bus message. If you're not interacting
555 * with D-Bus, you probably don't need them.
560 * g_variant_get_handle:
561 * @value: a handle #GVariant instance
562 * @returns: a #gint32
564 * Returns the 32-bit signed integer value of @value.
566 * It is an error to call this function with a @value of any type other
567 * than %G_VARIANT_TYPE_HANDLE.
569 * By convention, handles are indexes into an array of file descriptors
570 * that are sent alongside a D-Bus message. If you're not interacting
571 * with D-Bus, you probably don't need them.
575 NUMERIC_TYPE (HANDLE, handle, gint32)
578 * g_variant_new_double:
579 * @value: a #gdouble floating point value
580 * @returns: (transfer none): a floating reference to a new double #GVariant instance
582 * Creates a new double #GVariant instance.
587 * g_variant_get_double:
588 * @value: a double #GVariant instance
589 * @returns: a #gdouble
591 * Returns the double precision floating point value of @value.
593 * It is an error to call this function with a @value of any type
594 * other than %G_VARIANT_TYPE_DOUBLE.
598 NUMERIC_TYPE (DOUBLE, double, gdouble)
600 /* Container type Constructor / Deconstructors {{{1 */
602 * g_variant_new_maybe:
603 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
604 * @child: (allow-none): the child value, or %NULL
605 * @returns: (transfer none): a floating reference to a new #GVariant maybe instance
607 * Depending on if @child is %NULL, either wraps @child inside of a
608 * maybe container or creates a Nothing instance for the given @type.
610 * At least one of @child_type and @child must be non-%NULL.
611 * If @child_type is non-%NULL then it must be a definite type.
612 * If they are both non-%NULL then @child_type must be the type
615 * If @child is a floating reference (see g_variant_ref_sink()), the new
616 * instance takes ownership of @child.
621 g_variant_new_maybe (const GVariantType *child_type,
624 GVariantType *maybe_type;
627 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
629 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
630 g_return_val_if_fail (child_type == NULL || child == NULL ||
631 g_variant_is_of_type (child, child_type),
634 if (child_type == NULL)
635 child_type = g_variant_get_type (child);
637 maybe_type = g_variant_type_new_maybe (child_type);
644 children = g_new (GVariant *, 1);
645 children[0] = g_variant_ref_sink (child);
646 trusted = g_variant_is_trusted (children[0]);
648 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
651 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
653 g_variant_type_free (maybe_type);
659 * g_variant_get_maybe:
660 * @value: a maybe-typed value
661 * @returns: (allow-none) (transfer full): the contents of @value, or %NULL
663 * Given a maybe-typed #GVariant instance, extract its value. If the
664 * value is Nothing, then this function returns %NULL.
669 g_variant_get_maybe (GVariant *value)
671 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
673 if (g_variant_n_children (value))
674 return g_variant_get_child_value (value, 0);
680 * g_variant_new_variant: (constructor)
681 * @value: a #GVariant instance
682 * @returns: (transfer none): a floating reference to a new variant #GVariant instance
684 * Boxes @value. The result is a #GVariant instance representing a
685 * variant containing the original value.
687 * If @child is a floating reference (see g_variant_ref_sink()), the new
688 * instance takes ownership of @child.
693 g_variant_new_variant (GVariant *value)
695 g_return_val_if_fail (value != NULL, NULL);
697 g_variant_ref_sink (value);
699 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
700 g_memdup (&value, sizeof value),
701 1, g_variant_is_trusted (value));
705 * g_variant_get_variant:
706 * @value: a variant #GVariant instance
707 * @returns: (transfer full): the item contained in the variant
709 * Unboxes @value. The result is the #GVariant instance that was
710 * contained in @value.
715 g_variant_get_variant (GVariant *value)
717 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
719 return g_variant_get_child_value (value, 0);
723 * g_variant_new_array:
724 * @child_type: (allow-none): the element type of the new array
725 * @children: (allow-none) (array length=n_children): an array of
726 * #GVariant pointers, the children
727 * @n_children: the length of @children
728 * @returns: (transfer none): a floating reference to a new #GVariant array
730 * Creates a new #GVariant array from @children.
732 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
733 * child type is determined by inspecting the first element of the
734 * @children array. If @child_type is non-%NULL then it must be a
737 * The items of the array are taken from the @children array. No entry
738 * in the @children array may be %NULL.
740 * All items in the array must have the same type, which must be the
741 * same as @child_type, if given.
743 * If the @children are floating references (see g_variant_ref_sink()), the
744 * new instance takes ownership of them as if via g_variant_ref_sink().
749 g_variant_new_array (const GVariantType *child_type,
750 GVariant * const *children,
753 GVariantType *array_type;
754 GVariant **my_children;
759 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
760 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
761 g_return_val_if_fail (child_type == NULL ||
762 g_variant_type_is_definite (child_type), NULL);
764 my_children = g_new (GVariant *, n_children);
767 if (child_type == NULL)
768 child_type = g_variant_get_type (children[0]);
769 array_type = g_variant_type_new_array (child_type);
771 for (i = 0; i < n_children; i++)
773 TYPE_CHECK (children[i], child_type, NULL);
774 my_children[i] = g_variant_ref_sink (children[i]);
775 trusted &= g_variant_is_trusted (children[i]);
778 value = g_variant_new_from_children (array_type, my_children,
779 n_children, trusted);
780 g_variant_type_free (array_type);
786 * g_variant_make_tuple_type:
787 * @children: (array length=n_children): an array of GVariant *
788 * @n_children: the length of @children
790 * Return the type of a tuple containing @children as its items.
792 static GVariantType *
793 g_variant_make_tuple_type (GVariant * const *children,
796 const GVariantType **types;
800 types = g_new (const GVariantType *, n_children);
802 for (i = 0; i < n_children; i++)
803 types[i] = g_variant_get_type (children[i]);
805 type = g_variant_type_new_tuple (types, n_children);
812 * g_variant_new_tuple:
813 * @children: (array length=n_children): the items to make the tuple out of
814 * @n_children: the length of @children
815 * @returns: (transfer none): a floating reference to a new #GVariant tuple
817 * Creates a new tuple #GVariant out of the items in @children. The
818 * type is determined from the types of @children. No entry in the
819 * @children array may be %NULL.
821 * If @n_children is 0 then the unit tuple is constructed.
823 * If the @children are floating references (see g_variant_ref_sink()), the
824 * new instance takes ownership of them as if via g_variant_ref_sink().
829 g_variant_new_tuple (GVariant * const *children,
832 GVariantType *tuple_type;
833 GVariant **my_children;
838 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
840 my_children = g_new (GVariant *, n_children);
843 for (i = 0; i < n_children; i++)
845 my_children[i] = g_variant_ref_sink (children[i]);
846 trusted &= g_variant_is_trusted (children[i]);
849 tuple_type = g_variant_make_tuple_type (children, n_children);
850 value = g_variant_new_from_children (tuple_type, my_children,
851 n_children, trusted);
852 g_variant_type_free (tuple_type);
858 * g_variant_make_dict_entry_type:
859 * @key: a #GVariant, the key
860 * @val: a #GVariant, the value
862 * Return the type of a dictionary entry containing @key and @val as its
865 static GVariantType *
866 g_variant_make_dict_entry_type (GVariant *key,
869 return g_variant_type_new_dict_entry (g_variant_get_type (key),
870 g_variant_get_type (val));
874 * g_variant_new_dict_entry: (constructor)
875 * @key: a basic #GVariant, the key
876 * @value: a #GVariant, the value
877 * @returns: (transfer none): a floating reference to a new dictionary entry #GVariant
879 * Creates a new dictionary entry #GVariant. @key and @value must be
880 * non-%NULL. @key must be a value of a basic type (ie: not a container).
882 * If the @key or @value are floating references (see g_variant_ref_sink()),
883 * the new instance takes ownership of them as if via g_variant_ref_sink().
888 g_variant_new_dict_entry (GVariant *key,
891 GVariantType *dict_type;
895 g_return_val_if_fail (key != NULL && value != NULL, NULL);
896 g_return_val_if_fail (!g_variant_is_container (key), NULL);
898 children = g_new (GVariant *, 2);
899 children[0] = g_variant_ref_sink (key);
900 children[1] = g_variant_ref_sink (value);
901 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
903 dict_type = g_variant_make_dict_entry_type (key, value);
904 value = g_variant_new_from_children (dict_type, children, 2, trusted);
905 g_variant_type_free (dict_type);
911 * g_variant_lookup: (skip)
912 * @dictionary: a dictionary #GVariant
913 * @key: the key to lookup in the dictionary
914 * @format_string: a GVariant format string
915 * @...: the arguments to unpack the value into
917 * Looks up a value in a dictionary #GVariant.
919 * This function is a wrapper around g_variant_lookup_value() and
920 * g_variant_get(). In the case that %NULL would have been returned,
921 * this function returns %FALSE. Otherwise, it unpacks the returned
922 * value and returns %TRUE.
924 * See g_variant_get() for information about @format_string.
926 * Returns: %TRUE if a value was unpacked
931 g_variant_lookup (GVariant *dictionary,
933 const gchar *format_string,
940 g_variant_get_data (dictionary);
942 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
943 value = g_variant_lookup_value (dictionary, key, type);
944 g_variant_type_free (type);
950 va_start (ap, format_string);
951 g_variant_get_va (value, format_string, NULL, &ap);
952 g_variant_unref (value);
963 * g_variant_lookup_value:
964 * @dictionary: a dictionary #GVariant
965 * @key: the key to lookup in the dictionary
966 * @expected_type: (allow-none): a #GVariantType, or %NULL
968 * Looks up a value in a dictionary #GVariant.
970 * This function works with dictionaries of the type
971 * <literal>a{s*}</literal> (and equally well with type
972 * <literal>a{o*}</literal>, but we only further discuss the string case
973 * for sake of clarity).
975 * In the event that @dictionary has the type <literal>a{sv}</literal>,
976 * the @expected_type string specifies what type of value is expected to
977 * be inside of the variant. If the value inside the variant has a
978 * different type then %NULL is returned. In the event that @dictionary
979 * has a value type other than <literal>v</literal> then @expected_type
980 * must directly match the key type and it is used to unpack the value
981 * directly or an error occurs.
983 * In either case, if @key is not found in @dictionary, %NULL is
986 * If the key is found and the value has the correct type, it is
987 * returned. If @expected_type was specified then any non-%NULL return
988 * value will have this type.
990 * Returns: (transfer full): the value of the dictionary key, or %NULL
995 g_variant_lookup_value (GVariant *dictionary,
997 const GVariantType *expected_type)
1003 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1004 G_VARIANT_TYPE ("a{s*}")) ||
1005 g_variant_is_of_type (dictionary,
1006 G_VARIANT_TYPE ("a{o*}")),
1009 g_variant_iter_init (&iter, dictionary);
1011 while ((entry = g_variant_iter_next_value (&iter)))
1013 GVariant *entry_key;
1016 entry_key = g_variant_get_child_value (entry, 0);
1017 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1018 g_variant_unref (entry_key);
1023 g_variant_unref (entry);
1029 value = g_variant_get_child_value (entry, 1);
1030 g_variant_unref (entry);
1032 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1036 tmp = g_variant_get_variant (value);
1037 g_variant_unref (value);
1039 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1041 g_variant_unref (tmp);
1048 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1049 g_variant_is_of_type (value, expected_type), NULL);
1055 * g_variant_get_fixed_array:
1056 * @value: a #GVariant array with fixed-sized elements
1057 * @n_elements: (out): a pointer to the location to store the number of items
1058 * @element_size: the size of each element
1059 * @returns: (array length=n_elements) (transfer none): a pointer to
1062 * Provides access to the serialised data for an array of fixed-sized
1065 * @value must be an array with fixed-sized elements. Numeric types are
1066 * fixed-size, as are tuples containing only other fixed-sized types.
1068 * @element_size must be the size of a single element in the array,
1069 * as given by the section on
1070 * <link linkend='gvariant-serialised-data-memory'>Serialised Data
1073 * In particular, arrays of these fixed-sized types can be interpreted
1074 * as an array of the given C type, with @element_size set to
1075 * <code>sizeof</code> the appropriate type:
1079 * <thead><row><entry>element type</entry> <entry>C type</entry></row></thead>
1081 * <row><entry>%G_VARIANT_TYPE_INT16 (etc.)</entry>
1082 * <entry>#gint16 (etc.)</entry></row>
1083 * <row><entry>%G_VARIANT_TYPE_BOOLEAN</entry>
1084 * <entry>#guchar (not #gboolean!)</entry></row>
1085 * <row><entry>%G_VARIANT_TYPE_BYTE</entry> <entry>#guchar</entry></row>
1086 * <row><entry>%G_VARIANT_TYPE_HANDLE</entry> <entry>#guint32</entry></row>
1087 * <row><entry>%G_VARIANT_TYPE_DOUBLE</entry> <entry>#gdouble</entry></row>
1092 * For example, if calling this function for an array of 32 bit integers,
1093 * you might say <code>sizeof (gint32)</code>. This value isn't used
1094 * except for the purpose of a double-check that the form of the
1095 * serialised data matches the caller's expectation.
1097 * @n_elements, which must be non-%NULL is set equal to the number of
1098 * items in the array.
1103 g_variant_get_fixed_array (GVariant *value,
1107 GVariantTypeInfo *array_info;
1108 gsize array_element_size;
1112 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1114 g_return_val_if_fail (n_elements != NULL, NULL);
1115 g_return_val_if_fail (element_size > 0, NULL);
1117 array_info = g_variant_get_type_info (value);
1118 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1120 g_return_val_if_fail (array_element_size, NULL);
1122 if G_UNLIKELY (array_element_size != element_size)
1124 if (array_element_size)
1125 g_critical ("g_variant_get_fixed_array: assertion "
1126 "`g_variant_array_has_fixed_size (value, element_size)' "
1127 "failed: array size %"G_GSIZE_FORMAT" does not match "
1128 "given element_size %"G_GSIZE_FORMAT".",
1129 array_element_size, element_size);
1131 g_critical ("g_variant_get_fixed_array: assertion "
1132 "`g_variant_array_has_fixed_size (value, element_size)' "
1133 "failed: array does not have fixed size.");
1136 data = g_variant_get_data (value);
1137 size = g_variant_get_size (value);
1139 if (size % element_size)
1142 *n_elements = size / element_size;
1151 * g_variant_new_fixed_array:
1152 * @element_type: the #GVariantType of each element
1153 * @elements: a pointer to the fixed array of contiguous elements
1154 * @n_elements: the number of elements
1155 * @element_size: the size of each element
1156 * @returns: (transfer none): a floating reference to a new array #GVariant instance
1158 * Provides access to the serialised data for an array of fixed-sized
1161 * @value must be an array with fixed-sized elements. Numeric types are
1162 * fixed-size as are tuples containing only other fixed-sized types.
1164 * @element_size must be the size of a single element in the array. For
1165 * example, if calling this function for an array of 32 bit integers,
1166 * you might say <code>sizeof (gint32)</code>. This value isn't used
1167 * except for the purpose of a double-check that the form of the
1168 * serialised data matches the caller's expectation.
1170 * @n_elements, which must be non-%NULL is set equal to the number of
1171 * items in the array.
1176 g_variant_new_fixed_array (const GVariantType *element_type,
1177 gconstpointer elements,
1181 GVariantType *array_type;
1182 gsize array_element_size;
1183 GVariantTypeInfo *array_info;
1187 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1188 g_return_val_if_fail (element_size > 0, NULL);
1190 array_type = g_variant_type_new_array (element_type);
1191 array_info = g_variant_type_info_get (array_type);
1192 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1193 if G_UNLIKELY (array_element_size != element_size)
1195 if (array_element_size)
1196 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1197 " does not match given element_size %" G_GSIZE_FORMAT ".",
1198 array_element_size, element_size);
1200 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1204 data = g_memdup (elements, n_elements * element_size);
1205 value = g_variant_new_from_data (array_type, data,
1206 n_elements * element_size,
1207 FALSE, g_free, data);
1209 g_variant_type_free (array_type);
1210 g_variant_type_info_unref (array_info);
1215 /* String type constructor/getters/validation {{{1 */
1217 * g_variant_new_string:
1218 * @string: a normal utf8 nul-terminated string
1219 * @returns: (transfer none): a floating reference to a new string #GVariant instance
1221 * Creates a string #GVariant with the contents of @string.
1223 * @string must be valid utf8.
1228 g_variant_new_string (const gchar *string)
1230 g_return_val_if_fail (string != NULL, NULL);
1231 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1233 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1234 string, strlen (string) + 1);
1238 * g_variant_new_object_path:
1239 * @object_path: a normal C nul-terminated string
1240 * @returns: (transfer none): a floating reference to a new object path #GVariant instance
1242 * Creates a D-Bus object path #GVariant with the contents of @string.
1243 * @string must be a valid D-Bus object path. Use
1244 * g_variant_is_object_path() if you're not sure.
1249 g_variant_new_object_path (const gchar *object_path)
1251 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1253 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1254 object_path, strlen (object_path) + 1);
1258 * g_variant_is_object_path:
1259 * @string: a normal C nul-terminated string
1260 * @returns: %TRUE if @string is a D-Bus object path
1262 * Determines if a given string is a valid D-Bus object path. You
1263 * should ensure that a string is a valid D-Bus object path before
1264 * passing it to g_variant_new_object_path().
1266 * A valid object path starts with '/' followed by zero or more
1267 * sequences of characters separated by '/' characters. Each sequence
1268 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1269 * (including the one following the final '/' character) may be empty.
1274 g_variant_is_object_path (const gchar *string)
1276 g_return_val_if_fail (string != NULL, FALSE);
1278 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1282 * g_variant_new_signature:
1283 * @signature: a normal C nul-terminated string
1284 * @returns: (transfer none): a floating reference to a new signature #GVariant instance
1286 * Creates a D-Bus type signature #GVariant with the contents of
1287 * @string. @string must be a valid D-Bus type signature. Use
1288 * g_variant_is_signature() if you're not sure.
1293 g_variant_new_signature (const gchar *signature)
1295 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1297 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1298 signature, strlen (signature) + 1);
1302 * g_variant_is_signature:
1303 * @string: a normal C nul-terminated string
1304 * @returns: %TRUE if @string is a D-Bus type signature
1306 * Determines if a given string is a valid D-Bus type signature. You
1307 * should ensure that a string is a valid D-Bus type signature before
1308 * passing it to g_variant_new_signature().
1310 * D-Bus type signatures consist of zero or more definite #GVariantType
1311 * strings in sequence.
1316 g_variant_is_signature (const gchar *string)
1318 g_return_val_if_fail (string != NULL, FALSE);
1320 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1324 * g_variant_get_string:
1325 * @value: a string #GVariant instance
1326 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1327 * to store the length
1328 * @returns: (transfer none): the constant string, utf8 encoded
1330 * Returns the string value of a #GVariant instance with a string
1331 * type. This includes the types %G_VARIANT_TYPE_STRING,
1332 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1334 * The string will always be utf8 encoded.
1336 * If @length is non-%NULL then the length of the string (in bytes) is
1337 * returned there. For trusted values, this information is already
1338 * known. For untrusted values, a strlen() will be performed.
1340 * It is an error to call this function with a @value of any type
1341 * other than those three.
1343 * The return value remains valid as long as @value exists.
1348 g_variant_get_string (GVariant *value,
1354 g_return_val_if_fail (value != NULL, NULL);
1355 g_return_val_if_fail (
1356 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1357 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1358 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1360 data = g_variant_get_data (value);
1361 size = g_variant_get_size (value);
1363 if (!g_variant_is_trusted (value))
1365 switch (g_variant_classify (value))
1367 case G_VARIANT_CLASS_STRING:
1368 if (g_variant_serialiser_is_string (data, size))
1375 case G_VARIANT_CLASS_OBJECT_PATH:
1376 if (g_variant_serialiser_is_object_path (data, size))
1383 case G_VARIANT_CLASS_SIGNATURE:
1384 if (g_variant_serialiser_is_signature (data, size))
1392 g_assert_not_reached ();
1403 * g_variant_dup_string:
1404 * @value: a string #GVariant instance
1405 * @length: (out): a pointer to a #gsize, to store the length
1406 * @returns: (transfer full): a newly allocated string, utf8 encoded
1408 * Similar to g_variant_get_string() except that instead of returning
1409 * a constant string, the string is duplicated.
1411 * The string will always be utf8 encoded.
1413 * The return value must be freed using g_free().
1418 g_variant_dup_string (GVariant *value,
1421 return g_strdup (g_variant_get_string (value, length));
1425 * g_variant_new_strv:
1426 * @strv: (array length=length) (element-type utf8): an array of strings
1427 * @length: the length of @strv, or -1
1428 * @returns: (transfer none): a new floating #GVariant instance
1430 * Constructs an array of strings #GVariant from the given array of
1433 * If @length is -1 then @strv is %NULL-terminated.
1438 g_variant_new_strv (const gchar * const *strv,
1444 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1447 length = g_strv_length ((gchar **) strv);
1449 strings = g_new (GVariant *, length);
1450 for (i = 0; i < length; i++)
1451 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1453 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1454 strings, length, TRUE);
1458 * g_variant_get_strv:
1459 * @value: an array of strings #GVariant
1460 * @length: (out) (allow-none): the length of the result, or %NULL
1461 * @returns: (array length=length zero-terminated=1) (transfer container): an array of constant
1464 * Gets the contents of an array of strings #GVariant. This call
1465 * makes a shallow copy; the return result should be released with
1466 * g_free(), but the individual strings must not be modified.
1468 * If @length is non-%NULL then the number of elements in the result
1469 * is stored there. In any case, the resulting array will be
1472 * For an empty array, @length will be set to 0 and a pointer to a
1473 * %NULL pointer will be returned.
1478 g_variant_get_strv (GVariant *value,
1485 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1487 g_variant_get_data (value);
1488 n = g_variant_n_children (value);
1489 strv = g_new (const gchar *, n + 1);
1491 for (i = 0; i < n; i++)
1495 string = g_variant_get_child_value (value, i);
1496 strv[i] = g_variant_get_string (string, NULL);
1497 g_variant_unref (string);
1508 * g_variant_dup_strv:
1509 * @value: an array of strings #GVariant
1510 * @length: (out) (allow-none): the length of the result, or %NULL
1511 * @returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1513 * Gets the contents of an array of strings #GVariant. This call
1514 * makes a deep copy; the return result should be released with
1517 * If @length is non-%NULL then the number of elements in the result
1518 * is stored there. In any case, the resulting array will be
1521 * For an empty array, @length will be set to 0 and a pointer to a
1522 * %NULL pointer will be returned.
1527 g_variant_dup_strv (GVariant *value,
1534 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1536 n = g_variant_n_children (value);
1537 strv = g_new (gchar *, n + 1);
1539 for (i = 0; i < n; i++)
1543 string = g_variant_get_child_value (value, i);
1544 strv[i] = g_variant_dup_string (string, NULL);
1545 g_variant_unref (string);
1556 * g_variant_new_objv:
1557 * @strv: (array length=length) (element-type utf8): an array of strings
1558 * @length: the length of @strv, or -1
1559 * @returns: (transfer none): a new floating #GVariant instance
1561 * Constructs an array of object paths #GVariant from the given array of
1564 * Each string must be a valid #GVariant object path; see
1565 * g_variant_is_object_path().
1567 * If @length is -1 then @strv is %NULL-terminated.
1572 g_variant_new_objv (const gchar * const *strv,
1578 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1581 length = g_strv_length ((gchar **) strv);
1583 strings = g_new (GVariant *, length);
1584 for (i = 0; i < length; i++)
1585 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1587 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1588 strings, length, TRUE);
1592 * g_variant_get_objv:
1593 * @value: an array of object paths #GVariant
1594 * @length: (out) (allow-none): the length of the result, or %NULL
1595 * @returns: (array length=length zero-terminated=1) (transfer container): an array of constant
1598 * Gets the contents of an array of object paths #GVariant. This call
1599 * makes a shallow copy; the return result should be released with
1600 * g_free(), but the individual strings must not be modified.
1602 * If @length is non-%NULL then the number of elements in the result
1603 * is stored there. In any case, the resulting array will be
1606 * For an empty array, @length will be set to 0 and a pointer to a
1607 * %NULL pointer will be returned.
1612 g_variant_get_objv (GVariant *value,
1619 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1621 g_variant_get_data (value);
1622 n = g_variant_n_children (value);
1623 strv = g_new (const gchar *, n + 1);
1625 for (i = 0; i < n; i++)
1629 string = g_variant_get_child_value (value, i);
1630 strv[i] = g_variant_get_string (string, NULL);
1631 g_variant_unref (string);
1642 * g_variant_dup_objv:
1643 * @value: an array of object paths #GVariant
1644 * @length: (out) (allow-none): the length of the result, or %NULL
1645 * @returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1647 * Gets the contents of an array of object paths #GVariant. This call
1648 * makes a deep copy; the return result should be released with
1651 * If @length is non-%NULL then the number of elements in the result
1652 * is stored there. In any case, the resulting array will be
1655 * For an empty array, @length will be set to 0 and a pointer to a
1656 * %NULL pointer will be returned.
1661 g_variant_dup_objv (GVariant *value,
1668 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1670 n = g_variant_n_children (value);
1671 strv = g_new (gchar *, n + 1);
1673 for (i = 0; i < n; i++)
1677 string = g_variant_get_child_value (value, i);
1678 strv[i] = g_variant_dup_string (string, NULL);
1679 g_variant_unref (string);
1691 * g_variant_new_bytestring:
1692 * @string: (array zero-terminated=1) (element-type guint8): a normal
1693 * nul-terminated string in no particular encoding
1694 * @returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1696 * Creates an array-of-bytes #GVariant with the contents of @string.
1697 * This function is just like g_variant_new_string() except that the
1698 * string need not be valid utf8.
1700 * The nul terminator character at the end of the string is stored in
1706 g_variant_new_bytestring (const gchar *string)
1708 g_return_val_if_fail (string != NULL, NULL);
1710 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1711 string, strlen (string) + 1);
1715 * g_variant_get_bytestring:
1716 * @value: an array-of-bytes #GVariant instance
1717 * @returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1718 * the constant string
1720 * Returns the string value of a #GVariant instance with an
1721 * array-of-bytes type. The string has no particular encoding.
1723 * If the array does not end with a nul terminator character, the empty
1724 * string is returned. For this reason, you can always trust that a
1725 * non-%NULL nul-terminated string will be returned by this function.
1727 * If the array contains a nul terminator character somewhere other than
1728 * the last byte then the returned string is the string, up to the first
1729 * such nul character.
1731 * It is an error to call this function with a @value that is not an
1734 * The return value remains valid as long as @value exists.
1739 g_variant_get_bytestring (GVariant *value)
1741 const gchar *string;
1744 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1746 /* Won't be NULL since this is an array type */
1747 string = g_variant_get_data (value);
1748 size = g_variant_get_size (value);
1750 if (size && string[size - 1] == '\0')
1757 * g_variant_dup_bytestring:
1758 * @value: an array-of-bytes #GVariant instance
1759 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1760 * the length (not including the nul terminator)
1761 * @returns: (transfer full) (array zero-terminated=1 length=length)
1762 * (element-type guint8): a newly allocated string
1764 * Similar to g_variant_get_bytestring() except that instead of
1765 * returning a constant string, the string is duplicated.
1767 * The return value must be freed using g_free().
1772 g_variant_dup_bytestring (GVariant *value,
1775 const gchar *original = g_variant_get_bytestring (value);
1778 /* don't crash in case get_bytestring() had an assert failure */
1779 if (original == NULL)
1782 size = strlen (original);
1787 return g_memdup (original, size + 1);
1791 * g_variant_new_bytestring_array:
1792 * @strv: (array length=length): an array of strings
1793 * @length: the length of @strv, or -1
1794 * @returns: (transfer none): a new floating #GVariant instance
1796 * Constructs an array of bytestring #GVariant from the given array of
1799 * If @length is -1 then @strv is %NULL-terminated.
1804 g_variant_new_bytestring_array (const gchar * const *strv,
1810 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1813 length = g_strv_length ((gchar **) strv);
1815 strings = g_new (GVariant *, length);
1816 for (i = 0; i < length; i++)
1817 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1819 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1820 strings, length, TRUE);
1824 * g_variant_get_bytestring_array:
1825 * @value: an array of array of bytes #GVariant ('aay')
1826 * @length: (out) (allow-none): the length of the result, or %NULL
1827 * @returns: (array length=length) (transfer container): an array of constant strings
1829 * Gets the contents of an array of array of bytes #GVariant. This call
1830 * makes a shallow copy; the return result should be released with
1831 * g_free(), but the individual strings must not be modified.
1833 * If @length is non-%NULL then the number of elements in the result is
1834 * stored there. In any case, the resulting array will be
1837 * For an empty array, @length will be set to 0 and a pointer to a
1838 * %NULL pointer will be returned.
1843 g_variant_get_bytestring_array (GVariant *value,
1850 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1852 g_variant_get_data (value);
1853 n = g_variant_n_children (value);
1854 strv = g_new (const gchar *, n + 1);
1856 for (i = 0; i < n; i++)
1860 string = g_variant_get_child_value (value, i);
1861 strv[i] = g_variant_get_bytestring (string);
1862 g_variant_unref (string);
1873 * g_variant_dup_bytestring_array:
1874 * @value: an array of array of bytes #GVariant ('aay')
1875 * @length: (out) (allow-none): the length of the result, or %NULL
1876 * @returns: (array length=length) (transfer full): an array of strings
1878 * Gets the contents of an array of array of bytes #GVariant. This call
1879 * makes a deep copy; the return result should be released with
1882 * If @length is non-%NULL then the number of elements in the result is
1883 * stored there. In any case, the resulting array will be
1886 * For an empty array, @length will be set to 0 and a pointer to a
1887 * %NULL pointer will be returned.
1892 g_variant_dup_bytestring_array (GVariant *value,
1899 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1901 g_variant_get_data (value);
1902 n = g_variant_n_children (value);
1903 strv = g_new (gchar *, n + 1);
1905 for (i = 0; i < n; i++)
1909 string = g_variant_get_child_value (value, i);
1910 strv[i] = g_variant_dup_bytestring (string, NULL);
1911 g_variant_unref (string);
1921 /* Type checking and querying {{{1 */
1923 * g_variant_get_type:
1924 * @value: a #GVariant
1925 * @returns: a #GVariantType
1927 * Determines the type of @value.
1929 * The return value is valid for the lifetime of @value and must not
1934 const GVariantType *
1935 g_variant_get_type (GVariant *value)
1937 GVariantTypeInfo *type_info;
1939 g_return_val_if_fail (value != NULL, NULL);
1941 type_info = g_variant_get_type_info (value);
1943 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1947 * g_variant_get_type_string:
1948 * @value: a #GVariant
1949 * @returns: the type string for the type of @value
1951 * Returns the type string of @value. Unlike the result of calling
1952 * g_variant_type_peek_string(), this string is nul-terminated. This
1953 * string belongs to #GVariant and must not be freed.
1958 g_variant_get_type_string (GVariant *value)
1960 GVariantTypeInfo *type_info;
1962 g_return_val_if_fail (value != NULL, NULL);
1964 type_info = g_variant_get_type_info (value);
1966 return g_variant_type_info_get_type_string (type_info);
1970 * g_variant_is_of_type:
1971 * @value: a #GVariant instance
1972 * @type: a #GVariantType
1973 * @returns: %TRUE if the type of @value matches @type
1975 * Checks if a value has a type matching the provided type.
1980 g_variant_is_of_type (GVariant *value,
1981 const GVariantType *type)
1983 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1987 * g_variant_is_container:
1988 * @value: a #GVariant instance
1989 * @returns: %TRUE if @value is a container
1991 * Checks if @value is a container.
1994 g_variant_is_container (GVariant *value)
1996 return g_variant_type_is_container (g_variant_get_type (value));
2001 * g_variant_classify:
2002 * @value: a #GVariant
2003 * @returns: the #GVariantClass of @value
2005 * Classifies @value according to its top-level type.
2011 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2012 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2013 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2014 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2015 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2016 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2017 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2018 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2019 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2020 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2022 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2023 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2025 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2026 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2027 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2028 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2029 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2030 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2032 * The range of possible top-level types of #GVariant instances.
2037 g_variant_classify (GVariant *value)
2039 g_return_val_if_fail (value != NULL, 0);
2041 return *g_variant_get_type_string (value);
2044 /* Pretty printer {{{1 */
2045 /* This function is not introspectable because if @string is NULL,
2046 @returns is (transfer full), otherwise it is (transfer none), which
2047 is not supported by GObjectIntrospection */
2049 * g_variant_print_string: (skip)
2050 * @value: a #GVariant
2051 * @string: (allow-none) (default NULL): a #GString, or %NULL
2052 * @type_annotate: %TRUE if type information should be included in
2054 * @returns: a #GString containing the string
2056 * Behaves as g_variant_print(), but operates on a #GString.
2058 * If @string is non-%NULL then it is appended to and returned. Else,
2059 * a new empty #GString is allocated and it is returned.
2064 g_variant_print_string (GVariant *value,
2066 gboolean type_annotate)
2068 if G_UNLIKELY (string == NULL)
2069 string = g_string_new (NULL);
2071 switch (g_variant_classify (value))
2073 case G_VARIANT_CLASS_MAYBE:
2075 g_string_append_printf (string, "@%s ",
2076 g_variant_get_type_string (value));
2078 if (g_variant_n_children (value))
2080 gchar *printed_child;
2085 * Consider the case of the type "mmi". In this case we could
2086 * write "just just 4", but "4" alone is totally unambiguous,
2087 * so we try to drop "just" where possible.
2089 * We have to be careful not to always drop "just", though,
2090 * since "nothing" needs to be distinguishable from "just
2091 * nothing". The case where we need to ensure we keep the
2092 * "just" is actually exactly the case where we have a nested
2095 * Instead of searching for that nested Nothing, we just print
2096 * the contained value into a separate string and see if we
2097 * end up with "nothing" at the end of it. If so, we need to
2098 * add "just" at our level.
2100 element = g_variant_get_child_value (value, 0);
2101 printed_child = g_variant_print (element, FALSE);
2102 g_variant_unref (element);
2104 if (g_str_has_suffix (printed_child, "nothing"))
2105 g_string_append (string, "just ");
2106 g_string_append (string, printed_child);
2107 g_free (printed_child);
2110 g_string_append (string, "nothing");
2114 case G_VARIANT_CLASS_ARRAY:
2115 /* it's an array so the first character of the type string is 'a'
2117 * if the first two characters are 'ay' then it's a bytestring.
2118 * under certain conditions we print those as strings.
2120 if (g_variant_get_type_string (value)[1] == 'y')
2126 /* first determine if it is a byte string.
2127 * that's when there's a single nul character: at the end.
2129 str = g_variant_get_data (value);
2130 size = g_variant_get_size (value);
2132 for (i = 0; i < size; i++)
2136 /* first nul byte is the last byte -> it's a byte string. */
2139 gchar *escaped = g_strescape (str, NULL);
2141 /* use double quotes only if a ' is in the string */
2142 if (strchr (str, '\''))
2143 g_string_append_printf (string, "b\"%s\"", escaped);
2145 g_string_append_printf (string, "b'%s'", escaped);
2152 /* fall through and handle normally... */;
2156 * if the first two characters are 'a{' then it's an array of
2157 * dictionary entries (ie: a dictionary) so we print that
2160 if (g_variant_get_type_string (value)[1] == '{')
2163 const gchar *comma = "";
2166 if ((n = g_variant_n_children (value)) == 0)
2169 g_string_append_printf (string, "@%s ",
2170 g_variant_get_type_string (value));
2171 g_string_append (string, "{}");
2175 g_string_append_c (string, '{');
2176 for (i = 0; i < n; i++)
2178 GVariant *entry, *key, *val;
2180 g_string_append (string, comma);
2183 entry = g_variant_get_child_value (value, i);
2184 key = g_variant_get_child_value (entry, 0);
2185 val = g_variant_get_child_value (entry, 1);
2186 g_variant_unref (entry);
2188 g_variant_print_string (key, string, type_annotate);
2189 g_variant_unref (key);
2190 g_string_append (string, ": ");
2191 g_variant_print_string (val, string, type_annotate);
2192 g_variant_unref (val);
2193 type_annotate = FALSE;
2195 g_string_append_c (string, '}');
2198 /* normal (non-dictionary) array */
2200 const gchar *comma = "";
2203 if ((n = g_variant_n_children (value)) == 0)
2206 g_string_append_printf (string, "@%s ",
2207 g_variant_get_type_string (value));
2208 g_string_append (string, "[]");
2212 g_string_append_c (string, '[');
2213 for (i = 0; i < n; i++)
2217 g_string_append (string, comma);
2220 element = g_variant_get_child_value (value, i);
2222 g_variant_print_string (element, string, type_annotate);
2223 g_variant_unref (element);
2224 type_annotate = FALSE;
2226 g_string_append_c (string, ']');
2231 case G_VARIANT_CLASS_TUPLE:
2235 n = g_variant_n_children (value);
2237 g_string_append_c (string, '(');
2238 for (i = 0; i < n; i++)
2242 element = g_variant_get_child_value (value, i);
2243 g_variant_print_string (element, string, type_annotate);
2244 g_string_append (string, ", ");
2245 g_variant_unref (element);
2248 /* for >1 item: remove final ", "
2249 * for 1 item: remove final " ", but leave the ","
2250 * for 0 items: there is only "(", so remove nothing
2252 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2253 g_string_append_c (string, ')');
2257 case G_VARIANT_CLASS_DICT_ENTRY:
2261 g_string_append_c (string, '{');
2263 element = g_variant_get_child_value (value, 0);
2264 g_variant_print_string (element, string, type_annotate);
2265 g_variant_unref (element);
2267 g_string_append (string, ", ");
2269 element = g_variant_get_child_value (value, 1);
2270 g_variant_print_string (element, string, type_annotate);
2271 g_variant_unref (element);
2273 g_string_append_c (string, '}');
2277 case G_VARIANT_CLASS_VARIANT:
2279 GVariant *child = g_variant_get_variant (value);
2281 /* Always annotate types in nested variants, because they are
2282 * (by nature) of variable type.
2284 g_string_append_c (string, '<');
2285 g_variant_print_string (child, string, TRUE);
2286 g_string_append_c (string, '>');
2288 g_variant_unref (child);
2292 case G_VARIANT_CLASS_BOOLEAN:
2293 if (g_variant_get_boolean (value))
2294 g_string_append (string, "true");
2296 g_string_append (string, "false");
2299 case G_VARIANT_CLASS_STRING:
2301 const gchar *str = g_variant_get_string (value, NULL);
2302 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2304 g_string_append_c (string, quote);
2308 gunichar c = g_utf8_get_char (str);
2310 if (c == quote || c == '\\')
2311 g_string_append_c (string, '\\');
2313 if (g_unichar_isprint (c))
2314 g_string_append_unichar (string, c);
2318 g_string_append_c (string, '\\');
2323 g_string_append_c (string, 'a');
2327 g_string_append_c (string, 'b');
2331 g_string_append_c (string, 'f');
2335 g_string_append_c (string, 'n');
2339 g_string_append_c (string, 'r');
2343 g_string_append_c (string, 't');
2347 g_string_append_c (string, 'v');
2351 g_string_append_printf (string, "u%04x", c);
2355 g_string_append_printf (string, "U%08x", c);
2358 str = g_utf8_next_char (str);
2361 g_string_append_c (string, quote);
2365 case G_VARIANT_CLASS_BYTE:
2367 g_string_append (string, "byte ");
2368 g_string_append_printf (string, "0x%02x",
2369 g_variant_get_byte (value));
2372 case G_VARIANT_CLASS_INT16:
2374 g_string_append (string, "int16 ");
2375 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2376 g_variant_get_int16 (value));
2379 case G_VARIANT_CLASS_UINT16:
2381 g_string_append (string, "uint16 ");
2382 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2383 g_variant_get_uint16 (value));
2386 case G_VARIANT_CLASS_INT32:
2387 /* Never annotate this type because it is the default for numbers
2388 * (and this is a *pretty* printer)
2390 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2391 g_variant_get_int32 (value));
2394 case G_VARIANT_CLASS_HANDLE:
2396 g_string_append (string, "handle ");
2397 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2398 g_variant_get_handle (value));
2401 case G_VARIANT_CLASS_UINT32:
2403 g_string_append (string, "uint32 ");
2404 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2405 g_variant_get_uint32 (value));
2408 case G_VARIANT_CLASS_INT64:
2410 g_string_append (string, "int64 ");
2411 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2412 g_variant_get_int64 (value));
2415 case G_VARIANT_CLASS_UINT64:
2417 g_string_append (string, "uint64 ");
2418 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2419 g_variant_get_uint64 (value));
2422 case G_VARIANT_CLASS_DOUBLE:
2427 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2429 for (i = 0; buffer[i]; i++)
2430 if (buffer[i] == '.' || buffer[i] == 'e' ||
2431 buffer[i] == 'n' || buffer[i] == 'N')
2434 /* if there is no '.' or 'e' in the float then add one */
2435 if (buffer[i] == '\0')
2442 g_string_append (string, buffer);
2446 case G_VARIANT_CLASS_OBJECT_PATH:
2448 g_string_append (string, "objectpath ");
2449 g_string_append_printf (string, "\'%s\'",
2450 g_variant_get_string (value, NULL));
2453 case G_VARIANT_CLASS_SIGNATURE:
2455 g_string_append (string, "signature ");
2456 g_string_append_printf (string, "\'%s\'",
2457 g_variant_get_string (value, NULL));
2461 g_assert_not_reached ();
2469 * @value: a #GVariant
2470 * @type_annotate: %TRUE if type information should be included in
2472 * @returns: (transfer full): a newly-allocated string holding the result.
2474 * Pretty-prints @value in the format understood by g_variant_parse().
2476 * The format is described <link linkend='gvariant-text'>here</link>.
2478 * If @type_annotate is %TRUE, then type information is included in
2482 g_variant_print (GVariant *value,
2483 gboolean type_annotate)
2485 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2489 /* Hash, Equal, Compare {{{1 */
2492 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2493 * @returns: a hash value corresponding to @value
2495 * Generates a hash value for a #GVariant instance.
2497 * The output of this function is guaranteed to be the same for a given
2498 * value only per-process. It may change between different processor
2499 * architectures or even different versions of GLib. Do not use this
2500 * function as a basis for building protocols or file formats.
2502 * The type of @value is #gconstpointer only to allow use of this
2503 * function with #GHashTable. @value must be a #GVariant.
2508 g_variant_hash (gconstpointer value_)
2510 GVariant *value = (GVariant *) value_;
2512 switch (g_variant_classify (value))
2514 case G_VARIANT_CLASS_STRING:
2515 case G_VARIANT_CLASS_OBJECT_PATH:
2516 case G_VARIANT_CLASS_SIGNATURE:
2517 return g_str_hash (g_variant_get_string (value, NULL));
2519 case G_VARIANT_CLASS_BOOLEAN:
2520 /* this is a very odd thing to hash... */
2521 return g_variant_get_boolean (value);
2523 case G_VARIANT_CLASS_BYTE:
2524 return g_variant_get_byte (value);
2526 case G_VARIANT_CLASS_INT16:
2527 case G_VARIANT_CLASS_UINT16:
2531 ptr = g_variant_get_data (value);
2539 case G_VARIANT_CLASS_INT32:
2540 case G_VARIANT_CLASS_UINT32:
2541 case G_VARIANT_CLASS_HANDLE:
2545 ptr = g_variant_get_data (value);
2553 case G_VARIANT_CLASS_INT64:
2554 case G_VARIANT_CLASS_UINT64:
2555 case G_VARIANT_CLASS_DOUBLE:
2556 /* need a separate case for these guys because otherwise
2557 * performance could be quite bad on big endian systems
2562 ptr = g_variant_get_data (value);
2565 return ptr[0] + ptr[1];
2571 g_return_val_if_fail (!g_variant_is_container (value), 0);
2572 g_assert_not_reached ();
2578 * @one: (type GVariant): a #GVariant instance
2579 * @two: (type GVariant): a #GVariant instance
2580 * @returns: %TRUE if @one and @two are equal
2582 * Checks if @one and @two have the same type and value.
2584 * The types of @one and @two are #gconstpointer only to allow use of
2585 * this function with #GHashTable. They must each be a #GVariant.
2590 g_variant_equal (gconstpointer one,
2595 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2597 if (g_variant_get_type_info ((GVariant *) one) !=
2598 g_variant_get_type_info ((GVariant *) two))
2601 /* if both values are trusted to be in their canonical serialised form
2602 * then a simple memcmp() of their serialised data will answer the
2605 * if not, then this might generate a false negative (since it is
2606 * possible for two different byte sequences to represent the same
2607 * value). for now we solve this by pretty-printing both values and
2608 * comparing the result.
2610 if (g_variant_is_trusted ((GVariant *) one) &&
2611 g_variant_is_trusted ((GVariant *) two))
2613 gconstpointer data_one, data_two;
2614 gsize size_one, size_two;
2616 size_one = g_variant_get_size ((GVariant *) one);
2617 size_two = g_variant_get_size ((GVariant *) two);
2619 if (size_one != size_two)
2622 data_one = g_variant_get_data ((GVariant *) one);
2623 data_two = g_variant_get_data ((GVariant *) two);
2625 equal = memcmp (data_one, data_two, size_one) == 0;
2629 gchar *strone, *strtwo;
2631 strone = g_variant_print ((GVariant *) one, FALSE);
2632 strtwo = g_variant_print ((GVariant *) two, FALSE);
2633 equal = strcmp (strone, strtwo) == 0;
2642 * g_variant_compare:
2643 * @one: (type GVariant): a basic-typed #GVariant instance
2644 * @two: (type GVariant): a #GVariant instance of the same type
2645 * @returns: negative value if a < b;
2647 * positive value if a > b.
2649 * Compares @one and @two.
2651 * The types of @one and @two are #gconstpointer only to allow use of
2652 * this function with #GTree, #GPtrArray, etc. They must each be a
2655 * Comparison is only defined for basic types (ie: booleans, numbers,
2656 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2657 * ordered in the usual way. Strings are in ASCII lexographical order.
2659 * It is a programmer error to attempt to compare container values or
2660 * two values that have types that are not exactly equal. For example,
2661 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2662 * integer. Also note that this function is not particularly
2663 * well-behaved when it comes to comparison of doubles; in particular,
2664 * the handling of incomparable values (ie: NaN) is undefined.
2666 * If you only require an equality comparison, g_variant_equal() is more
2672 g_variant_compare (gconstpointer one,
2675 GVariant *a = (GVariant *) one;
2676 GVariant *b = (GVariant *) two;
2678 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2680 switch (g_variant_classify (a))
2682 case G_VARIANT_CLASS_BYTE:
2683 return ((gint) g_variant_get_byte (a)) -
2684 ((gint) g_variant_get_byte (b));
2686 case G_VARIANT_CLASS_INT16:
2687 return ((gint) g_variant_get_int16 (a)) -
2688 ((gint) g_variant_get_int16 (b));
2690 case G_VARIANT_CLASS_UINT16:
2691 return ((gint) g_variant_get_uint16 (a)) -
2692 ((gint) g_variant_get_uint16 (b));
2694 case G_VARIANT_CLASS_INT32:
2696 gint32 a_val = g_variant_get_int32 (a);
2697 gint32 b_val = g_variant_get_int32 (b);
2699 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2702 case G_VARIANT_CLASS_UINT32:
2704 guint32 a_val = g_variant_get_uint32 (a);
2705 guint32 b_val = g_variant_get_uint32 (b);
2707 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2710 case G_VARIANT_CLASS_INT64:
2712 gint64 a_val = g_variant_get_int64 (a);
2713 gint64 b_val = g_variant_get_int64 (b);
2715 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2718 case G_VARIANT_CLASS_UINT64:
2720 guint64 a_val = g_variant_get_uint64 (a);
2721 guint64 b_val = g_variant_get_uint64 (b);
2723 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2726 case G_VARIANT_CLASS_DOUBLE:
2728 gdouble a_val = g_variant_get_double (a);
2729 gdouble b_val = g_variant_get_double (b);
2731 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2734 case G_VARIANT_CLASS_STRING:
2735 case G_VARIANT_CLASS_OBJECT_PATH:
2736 case G_VARIANT_CLASS_SIGNATURE:
2737 return strcmp (g_variant_get_string (a, NULL),
2738 g_variant_get_string (b, NULL));
2741 g_return_val_if_fail (!g_variant_is_container (a), 0);
2742 g_assert_not_reached ();
2746 /* GVariantIter {{{1 */
2748 * GVariantIter: (skip)
2750 * #GVariantIter is an opaque data structure and can only be accessed
2751 * using the following functions.
2758 const gchar *loop_format;
2764 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2768 struct stack_iter iter;
2770 GVariant *value_ref;
2774 #define GVSI(i) ((struct stack_iter *) (i))
2775 #define GVHI(i) ((struct heap_iter *) (i))
2776 #define GVSI_MAGIC ((gsize) 3579507750u)
2777 #define GVHI_MAGIC ((gsize) 1450270775u)
2778 #define is_valid_iter(i) (i != NULL && \
2779 GVSI(i)->magic == GVSI_MAGIC)
2780 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2784 * g_variant_iter_new:
2785 * @value: a container #GVariant
2786 * @returns: (transfer full): a new heap-allocated #GVariantIter
2788 * Creates a heap-allocated #GVariantIter for iterating over the items
2791 * Use g_variant_iter_free() to free the return value when you no longer
2794 * A reference is taken to @value and will be released only when
2795 * g_variant_iter_free() is called.
2800 g_variant_iter_new (GVariant *value)
2804 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2805 GVHI(iter)->value_ref = g_variant_ref (value);
2806 GVHI(iter)->magic = GVHI_MAGIC;
2808 g_variant_iter_init (iter, value);
2814 * g_variant_iter_init: (skip)
2815 * @iter: a pointer to a #GVariantIter
2816 * @value: a container #GVariant
2817 * @returns: the number of items in @value
2819 * Initialises (without allocating) a #GVariantIter. @iter may be
2820 * completely uninitialised prior to this call; its old value is
2823 * The iterator remains valid for as long as @value exists, and need not
2824 * be freed in any way.
2829 g_variant_iter_init (GVariantIter *iter,
2832 GVSI(iter)->magic = GVSI_MAGIC;
2833 GVSI(iter)->value = value;
2834 GVSI(iter)->n = g_variant_n_children (value);
2836 GVSI(iter)->loop_format = NULL;
2838 return GVSI(iter)->n;
2842 * g_variant_iter_copy:
2843 * @iter: a #GVariantIter
2844 * @returns: (transfer full): a new heap-allocated #GVariantIter
2846 * Creates a new heap-allocated #GVariantIter to iterate over the
2847 * container that was being iterated over by @iter. Iteration begins on
2848 * the new iterator from the current position of the old iterator but
2849 * the two copies are independent past that point.
2851 * Use g_variant_iter_free() to free the return value when you no longer
2854 * A reference is taken to the container that @iter is iterating over
2855 * and will be releated only when g_variant_iter_free() is called.
2860 g_variant_iter_copy (GVariantIter *iter)
2864 g_return_val_if_fail (is_valid_iter (iter), 0);
2866 copy = g_variant_iter_new (GVSI(iter)->value);
2867 GVSI(copy)->i = GVSI(iter)->i;
2873 * g_variant_iter_n_children:
2874 * @iter: a #GVariantIter
2875 * @returns: the number of children in the container
2877 * Queries the number of child items in the container that we are
2878 * iterating over. This is the total number of items -- not the number
2879 * of items remaining.
2881 * This function might be useful for preallocation of arrays.
2886 g_variant_iter_n_children (GVariantIter *iter)
2888 g_return_val_if_fail (is_valid_iter (iter), 0);
2890 return GVSI(iter)->n;
2894 * g_variant_iter_free:
2895 * @iter: (transfer full): a heap-allocated #GVariantIter
2897 * Frees a heap-allocated #GVariantIter. Only call this function on
2898 * iterators that were returned by g_variant_iter_new() or
2899 * g_variant_iter_copy().
2904 g_variant_iter_free (GVariantIter *iter)
2906 g_return_if_fail (is_valid_heap_iter (iter));
2908 g_variant_unref (GVHI(iter)->value_ref);
2909 GVHI(iter)->magic = 0;
2911 g_slice_free (struct heap_iter, GVHI(iter));
2915 * g_variant_iter_next_value:
2916 * @iter: a #GVariantIter
2917 * @returns: (allow-none) (transfer full): a #GVariant, or %NULL
2919 * Gets the next item in the container. If no more items remain then
2920 * %NULL is returned.
2922 * Use g_variant_unref() to drop your reference on the return value when
2923 * you no longer need it.
2926 * <title>Iterating with g_variant_iter_next_value()</title>
2928 * /<!-- -->* recursively iterate a container *<!-- -->/
2930 * iterate_container_recursive (GVariant *container)
2932 * GVariantIter iter;
2935 * g_variant_iter_init (&iter, container);
2936 * while ((child = g_variant_iter_next_value (&iter)))
2938 * g_print ("type '%s'\n", g_variant_get_type_string (child));
2940 * if (g_variant_is_container (child))
2941 * iterate_container_recursive (child);
2943 * g_variant_unref (child);
2952 g_variant_iter_next_value (GVariantIter *iter)
2954 g_return_val_if_fail (is_valid_iter (iter), FALSE);
2956 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2958 g_critical ("g_variant_iter_next_value: must not be called again "
2959 "after NULL has already been returned.");
2965 if (GVSI(iter)->i < GVSI(iter)->n)
2966 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2971 /* GVariantBuilder {{{1 */
2975 * A utility type for constructing container-type #GVariant instances.
2977 * This is an opaque structure and may only be accessed using the
2978 * following functions.
2980 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
2981 * access it from more than one thread.
2984 struct stack_builder
2986 GVariantBuilder *parent;
2989 /* type constraint explicitly specified by 'type'.
2990 * for tuple types, this moves along as we add more items.
2992 const GVariantType *expected_type;
2994 /* type constraint implied by previous array item.
2996 const GVariantType *prev_item_type;
2998 /* constraints on the number of children. max = -1 for unlimited. */
3002 /* dynamically-growing pointer array */
3003 GVariant **children;
3004 gsize allocated_children;
3007 /* set to '1' if all items in the container will have the same type
3008 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3010 guint uniform_item_types : 1;
3012 /* set to '1' initially and changed to '0' if an untrusted value is
3020 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3024 GVariantBuilder builder;
3030 #define GVSB(b) ((struct stack_builder *) (b))
3031 #define GVHB(b) ((struct heap_builder *) (b))
3032 #define GVSB_MAGIC ((gsize) 1033660112u)
3033 #define GVHB_MAGIC ((gsize) 3087242682u)
3034 #define is_valid_builder(b) (b != NULL && \
3035 GVSB(b)->magic == GVSB_MAGIC)
3036 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3039 * g_variant_builder_new:
3040 * @type: a container type
3041 * @returns: (transfer full): a #GVariantBuilder
3043 * Allocates and initialises a new #GVariantBuilder.
3045 * You should call g_variant_builder_unref() on the return value when it
3046 * is no longer needed. The memory will not be automatically freed by
3049 * In most cases it is easier to place a #GVariantBuilder directly on
3050 * the stack of the calling function and initialise it with
3051 * g_variant_builder_init().
3056 g_variant_builder_new (const GVariantType *type)
3058 GVariantBuilder *builder;
3060 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3061 g_variant_builder_init (builder, type);
3062 GVHB(builder)->magic = GVHB_MAGIC;
3063 GVHB(builder)->ref_count = 1;
3069 * g_variant_builder_unref:
3070 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3072 * Decreases the reference count on @builder.
3074 * In the event that there are no more references, releases all memory
3075 * associated with the #GVariantBuilder.
3077 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3078 * things will happen.
3083 g_variant_builder_unref (GVariantBuilder *builder)
3085 g_return_if_fail (is_valid_heap_builder (builder));
3087 if (--GVHB(builder)->ref_count)
3090 g_variant_builder_clear (builder);
3091 GVHB(builder)->magic = 0;
3093 g_slice_free (struct heap_builder, GVHB(builder));
3097 * g_variant_builder_ref:
3098 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3099 * @returns: (transfer full): a new reference to @builder
3101 * Increases the reference count on @builder.
3103 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3104 * things will happen.
3109 g_variant_builder_ref (GVariantBuilder *builder)
3111 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3113 GVHB(builder)->ref_count++;
3119 * g_variant_builder_clear: (skip)
3120 * @builder: a #GVariantBuilder
3122 * Releases all memory associated with a #GVariantBuilder without
3123 * freeing the #GVariantBuilder structure itself.
3125 * It typically only makes sense to do this on a stack-allocated
3126 * #GVariantBuilder if you want to abort building the value part-way
3127 * through. This function need not be called if you call
3128 * g_variant_builder_end() and it also doesn't need to be called on
3129 * builders allocated with g_variant_builder_new (see
3130 * g_variant_builder_unref() for that).
3132 * This function leaves the #GVariantBuilder structure set to all-zeros.
3133 * It is valid to call this function on either an initialised
3134 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3135 * to call this function on uninitialised memory.
3140 g_variant_builder_clear (GVariantBuilder *builder)
3144 if (GVSB(builder)->magic == 0)
3145 /* all-zeros case */
3148 g_return_if_fail (is_valid_builder (builder));
3150 g_variant_type_free (GVSB(builder)->type);
3152 for (i = 0; i < GVSB(builder)->offset; i++)
3153 g_variant_unref (GVSB(builder)->children[i]);
3155 g_free (GVSB(builder)->children);
3157 if (GVSB(builder)->parent)
3159 g_variant_builder_clear (GVSB(builder)->parent);
3160 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3163 memset (builder, 0, sizeof (GVariantBuilder));
3167 * g_variant_builder_init: (skip)
3168 * @builder: a #GVariantBuilder
3169 * @type: a container type
3171 * Initialises a #GVariantBuilder structure.
3173 * @type must be non-%NULL. It specifies the type of container to
3174 * construct. It can be an indefinite type such as
3175 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3176 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3179 * After the builder is initialised, values are added using
3180 * g_variant_builder_add_value() or g_variant_builder_add().
3182 * After all the child values are added, g_variant_builder_end() frees
3183 * the memory associated with the builder and returns the #GVariant that
3186 * This function completely ignores the previous contents of @builder.
3187 * On one hand this means that it is valid to pass in completely
3188 * uninitialised memory. On the other hand, this means that if you are
3189 * initialising over top of an existing #GVariantBuilder you need to
3190 * first call g_variant_builder_clear() in order to avoid leaking
3193 * You must not call g_variant_builder_ref() or
3194 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3195 * with this function. If you ever pass a reference to a
3196 * #GVariantBuilder outside of the control of your own code then you
3197 * should assume that the person receiving that reference may try to use
3198 * reference counting; you should use g_variant_builder_new() instead of
3204 g_variant_builder_init (GVariantBuilder *builder,
3205 const GVariantType *type)
3207 g_return_if_fail (type != NULL);
3208 g_return_if_fail (g_variant_type_is_container (type));
3210 memset (builder, 0, sizeof (GVariantBuilder));
3212 GVSB(builder)->type = g_variant_type_copy (type);
3213 GVSB(builder)->magic = GVSB_MAGIC;
3214 GVSB(builder)->trusted = TRUE;
3216 switch (*(const gchar *) type)
3218 case G_VARIANT_CLASS_VARIANT:
3219 GVSB(builder)->uniform_item_types = TRUE;
3220 GVSB(builder)->allocated_children = 1;
3221 GVSB(builder)->expected_type = NULL;
3222 GVSB(builder)->min_items = 1;
3223 GVSB(builder)->max_items = 1;
3226 case G_VARIANT_CLASS_ARRAY:
3227 GVSB(builder)->uniform_item_types = TRUE;
3228 GVSB(builder)->allocated_children = 8;
3229 GVSB(builder)->expected_type =
3230 g_variant_type_element (GVSB(builder)->type);
3231 GVSB(builder)->min_items = 0;
3232 GVSB(builder)->max_items = -1;
3235 case G_VARIANT_CLASS_MAYBE:
3236 GVSB(builder)->uniform_item_types = TRUE;
3237 GVSB(builder)->allocated_children = 1;
3238 GVSB(builder)->expected_type =
3239 g_variant_type_element (GVSB(builder)->type);
3240 GVSB(builder)->min_items = 0;
3241 GVSB(builder)->max_items = 1;
3244 case G_VARIANT_CLASS_DICT_ENTRY:
3245 GVSB(builder)->uniform_item_types = FALSE;
3246 GVSB(builder)->allocated_children = 2;
3247 GVSB(builder)->expected_type =
3248 g_variant_type_key (GVSB(builder)->type);
3249 GVSB(builder)->min_items = 2;
3250 GVSB(builder)->max_items = 2;
3253 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3254 GVSB(builder)->uniform_item_types = FALSE;
3255 GVSB(builder)->allocated_children = 8;
3256 GVSB(builder)->expected_type = NULL;
3257 GVSB(builder)->min_items = 0;
3258 GVSB(builder)->max_items = -1;
3261 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3262 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3263 GVSB(builder)->expected_type =
3264 g_variant_type_first (GVSB(builder)->type);
3265 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3266 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3267 GVSB(builder)->uniform_item_types = FALSE;
3271 g_assert_not_reached ();
3274 GVSB(builder)->children = g_new (GVariant *,
3275 GVSB(builder)->allocated_children);
3279 g_variant_builder_make_room (struct stack_builder *builder)
3281 if (builder->offset == builder->allocated_children)
3283 builder->allocated_children *= 2;
3284 builder->children = g_renew (GVariant *, builder->children,
3285 builder->allocated_children);
3290 * g_variant_builder_add_value:
3291 * @builder: a #GVariantBuilder
3292 * @value: a #GVariant
3294 * Adds @value to @builder.
3296 * It is an error to call this function in any way that would create an
3297 * inconsistent value to be constructed. Some examples of this are
3298 * putting different types of items into an array, putting the wrong
3299 * types or number of items in a tuple, putting more than one value into
3302 * If @value is a floating reference (see g_variant_ref_sink()),
3303 * the @builder instance takes ownership of @value.
3308 g_variant_builder_add_value (GVariantBuilder *builder,
3311 g_return_if_fail (is_valid_builder (builder));
3312 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3313 g_return_if_fail (!GVSB(builder)->expected_type ||
3314 g_variant_is_of_type (value,
3315 GVSB(builder)->expected_type));
3316 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3317 g_variant_is_of_type (value,
3318 GVSB(builder)->prev_item_type));
3320 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3322 if (!GVSB(builder)->uniform_item_types)
3324 /* advance our expected type pointers */
3325 if (GVSB(builder)->expected_type)
3326 GVSB(builder)->expected_type =
3327 g_variant_type_next (GVSB(builder)->expected_type);
3329 if (GVSB(builder)->prev_item_type)
3330 GVSB(builder)->prev_item_type =
3331 g_variant_type_next (GVSB(builder)->prev_item_type);
3334 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3336 g_variant_builder_make_room (GVSB(builder));
3338 GVSB(builder)->children[GVSB(builder)->offset++] =
3339 g_variant_ref_sink (value);
3343 * g_variant_builder_open:
3344 * @builder: a #GVariantBuilder
3345 * @type: a #GVariantType
3347 * Opens a subcontainer inside the given @builder. When done adding
3348 * items to the subcontainer, g_variant_builder_close() must be called.
3350 * It is an error to call this function in any way that would cause an
3351 * inconsistent value to be constructed (ie: adding too many values or
3352 * a value of an incorrect type).
3357 g_variant_builder_open (GVariantBuilder *builder,
3358 const GVariantType *type)
3360 GVariantBuilder *parent;
3362 g_return_if_fail (is_valid_builder (builder));
3363 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3364 g_return_if_fail (!GVSB(builder)->expected_type ||
3365 g_variant_type_is_subtype_of (type,
3366 GVSB(builder)->expected_type));
3367 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3368 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3371 parent = g_slice_dup (GVariantBuilder, builder);
3372 g_variant_builder_init (builder, type);
3373 GVSB(builder)->parent = parent;
3375 /* push the prev_item_type down into the subcontainer */
3376 if (GVSB(parent)->prev_item_type)
3378 if (!GVSB(builder)->uniform_item_types)
3379 /* tuples and dict entries */
3380 GVSB(builder)->prev_item_type =
3381 g_variant_type_first (GVSB(parent)->prev_item_type);
3383 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3384 /* maybes and arrays */
3385 GVSB(builder)->prev_item_type =
3386 g_variant_type_element (GVSB(parent)->prev_item_type);
3391 * g_variant_builder_close:
3392 * @builder: a #GVariantBuilder
3394 * Closes the subcontainer inside the given @builder that was opened by
3395 * the most recent call to g_variant_builder_open().
3397 * It is an error to call this function in any way that would create an
3398 * inconsistent value to be constructed (ie: too few values added to the
3404 g_variant_builder_close (GVariantBuilder *builder)
3406 GVariantBuilder *parent;
3408 g_return_if_fail (is_valid_builder (builder));
3409 g_return_if_fail (GVSB(builder)->parent != NULL);
3411 parent = GVSB(builder)->parent;
3412 GVSB(builder)->parent = NULL;
3414 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3417 g_slice_free (GVariantBuilder, parent);
3421 * g_variant_make_maybe_type:
3422 * @element: a #GVariant
3424 * Return the type of a maybe containing @element.
3426 static GVariantType *
3427 g_variant_make_maybe_type (GVariant *element)
3429 return g_variant_type_new_maybe (g_variant_get_type (element));
3433 * g_variant_make_array_type:
3434 * @element: a #GVariant
3436 * Return the type of an array containing @element.
3438 static GVariantType *
3439 g_variant_make_array_type (GVariant *element)
3441 return g_variant_type_new_array (g_variant_get_type (element));
3445 * g_variant_builder_end:
3446 * @builder: a #GVariantBuilder
3447 * @returns: (transfer none): a new, floating, #GVariant
3449 * Ends the builder process and returns the constructed value.
3451 * It is not permissible to use @builder in any way after this call
3452 * except for reference counting operations (in the case of a
3453 * heap-allocated #GVariantBuilder) or by reinitialising it with
3454 * g_variant_builder_init() (in the case of stack-allocated).
3456 * It is an error to call this function in any way that would create an
3457 * inconsistent value to be constructed (ie: insufficient number of
3458 * items added to a container with a specific number of children
3459 * required). It is also an error to call this function if the builder
3460 * was created with an indefinite array or maybe type and no children
3461 * have been added; in this case it is impossible to infer the type of
3467 g_variant_builder_end (GVariantBuilder *builder)
3469 GVariantType *my_type;
3472 g_return_val_if_fail (is_valid_builder (builder), NULL);
3473 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3475 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3476 GVSB(builder)->prev_item_type != NULL ||
3477 g_variant_type_is_definite (GVSB(builder)->type),
3480 if (g_variant_type_is_definite (GVSB(builder)->type))
3481 my_type = g_variant_type_copy (GVSB(builder)->type);
3483 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3484 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3486 else if (g_variant_type_is_array (GVSB(builder)->type))
3487 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3489 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3490 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3491 GVSB(builder)->offset);
3493 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3494 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3495 GVSB(builder)->children[1]);
3497 g_assert_not_reached ();
3499 value = g_variant_new_from_children (my_type,
3500 g_renew (GVariant *,
3501 GVSB(builder)->children,
3502 GVSB(builder)->offset),
3503 GVSB(builder)->offset,
3504 GVSB(builder)->trusted);
3505 GVSB(builder)->children = NULL;
3506 GVSB(builder)->offset = 0;
3508 g_variant_builder_clear (builder);
3509 g_variant_type_free (my_type);
3514 /* Format strings {{{1 */
3516 * g_variant_format_string_scan:
3517 * @string: a string that may be prefixed with a format string
3518 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3520 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3522 * @returns: %TRUE if there was a valid format string
3524 * Checks the string pointed to by @string for starting with a properly
3525 * formed #GVariant varargs format string. If no valid format string is
3526 * found then %FALSE is returned.
3528 * If @string does start with a valid format string then %TRUE is
3529 * returned. If @endptr is non-%NULL then it is updated to point to the
3530 * first character after the format string.
3532 * If @limit is non-%NULL then @limit (and any charater after it) will
3533 * not be accessed and the effect is otherwise equivalent to if the
3534 * character at @limit were nul.
3536 * See the section on <link linkend='gvariant-format-strings'>GVariant
3537 * Format Strings</link>.
3542 g_variant_format_string_scan (const gchar *string,
3544 const gchar **endptr)
3546 #define next_char() (string == limit ? '\0' : *string++)
3547 #define peek_char() (string == limit ? '\0' : *string)
3550 switch (next_char())
3552 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
3553 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
3554 case 'g': case 'v': case '*': case '?': case 'r':
3558 return g_variant_format_string_scan (string, limit, endptr);
3562 return g_variant_type_string_scan (string, limit, endptr);
3565 while (peek_char() != ')')
3566 if (!g_variant_format_string_scan (string, limit, &string))
3569 next_char(); /* consume ')' */
3579 if (c != 's' && c != 'o' && c != 'g')
3587 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
3588 * The terminating null character is considered to be
3589 * part of the string.
3591 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3595 if (!g_variant_format_string_scan (string, limit, &string))
3598 if (next_char() != '}')
3604 if ((c = next_char()) == 'a')
3606 if ((c = next_char()) == '&')
3608 if ((c = next_char()) == 'a')
3610 if ((c = next_char()) == 'y')
3611 break; /* '^a&ay' */
3614 else if (c == 's' || c == 'o')
3615 break; /* '^a&s', '^a&o' */
3620 if ((c = next_char()) == 'y')
3624 else if (c == 's' || c == 'o')
3625 break; /* '^as', '^ao' */
3632 if ((c = next_char()) == 'a')
3634 if ((c = next_char()) == 'y')
3644 if (c != 's' && c != 'o' && c != 'g')
3663 * g_variant_format_string_scan_type:
3664 * @string: a string that may be prefixed with a format string
3665 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
3667 * @endptr: (allow-none) (default NULL): location to store the end pointer,
3669 * @returns: (allow-none): a #GVariantType if there was a valid format string
3671 * If @string starts with a valid format string then this function will
3672 * return the type that the format string corresponds to. Otherwise
3673 * this function returns %NULL.
3675 * Use g_variant_type_free() to free the return value when you no longer
3678 * This function is otherwise exactly like
3679 * g_variant_format_string_scan().
3684 g_variant_format_string_scan_type (const gchar *string,
3686 const gchar **endptr)
3688 const gchar *my_end;
3695 if (!g_variant_format_string_scan (string, limit, endptr))
3698 dest = new = g_malloc (*endptr - string + 1);
3699 while (string != *endptr)
3701 if (*string != '@' && *string != '&' && *string != '^')
3707 return (GVariantType *) G_VARIANT_TYPE (new);
3711 valid_format_string (const gchar *format_string,
3715 const gchar *endptr;
3718 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3720 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3723 g_critical ("`%s' is not a valid GVariant format string",
3726 g_critical ("`%s' does not have a valid GVariant format "
3727 "string as a prefix", format_string);
3730 g_variant_type_free (type);
3735 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3740 fragment = g_strndup (format_string, endptr - format_string);
3741 typestr = g_variant_type_dup_string (type);
3743 g_critical ("the GVariant format string `%s' has a type of "
3744 "`%s' but the given value has a type of `%s'",
3745 fragment, typestr, g_variant_get_type_string (value));
3747 g_variant_type_free (type);
3752 g_variant_type_free (type);
3757 /* Variable Arguments {{{1 */
3758 /* We consider 2 main classes of format strings:
3760 * - recursive format strings
3761 * these are ones that result in recursion and the collection of
3762 * possibly more than one argument. Maybe types, tuples,
3763 * dictionary entries.
3765 * - leaf format string
3766 * these result in the collection of a single argument.
3768 * Leaf format strings are further subdivided into two categories:
3770 * - single non-null pointer ("nnp")
3771 * these either collect or return a single non-null pointer.
3774 * these collect or return something else (bool, number, etc).
3776 * Based on the above, the varargs handling code is split into 4 main parts:
3778 * - nnp handling code
3779 * - leaf handling code (which may invoke nnp code)
3780 * - generic handling code (may be recursive, may invoke leaf code)
3781 * - user-facing API (which invokes the generic code)
3783 * Each section implements some of the following functions:
3786 * collect the arguments for the format string as if
3787 * g_variant_new() had been called, but do nothing with them. used
3788 * for skipping over arguments when constructing a Nothing maybe
3792 * create a GVariant *
3795 * unpack a GVariant *
3797 * - free (nnp only):
3798 * free a previously allocated item
3802 g_variant_format_string_is_leaf (const gchar *str)
3804 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
3808 g_variant_format_string_is_nnp (const gchar *str)
3810 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
3811 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
3812 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
3815 /* Single non-null pointer ("nnp") {{{2 */
3817 g_variant_valist_free_nnp (const gchar *str,
3823 g_variant_iter_free (ptr);
3827 if (str[2] != '&') /* '^as', '^ao' */
3829 else /* '^a&s', '^a&o' */
3843 g_variant_unref (ptr);
3850 g_assert_not_reached ();
3855 g_variant_scan_convenience (const gchar **str,
3878 g_variant_valist_new_nnp (const gchar **str,
3889 const GVariantType *type;
3892 value = g_variant_builder_end (ptr);
3893 type = g_variant_get_type (value);
3895 if G_UNLIKELY (!g_variant_type_is_array (type))
3896 g_error ("g_variant_new: expected array GVariantBuilder but "
3897 "the built value has type `%s'",
3898 g_variant_get_type_string (value));
3900 type = g_variant_type_element (type);
3902 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
3903 g_error ("g_variant_new: expected GVariantBuilder array element "
3904 "type `%s' but the built value has element type `%s'",
3905 g_variant_type_dup_string ((GVariantType *) *str),
3906 g_variant_get_type_string (value) + 1);
3908 g_variant_type_string_scan (*str, NULL, str);
3914 /* special case: NULL pointer for empty array */
3916 const GVariantType *type = (GVariantType *) *str;
3918 g_variant_type_string_scan (*str, NULL, str);
3920 if G_UNLIKELY (!g_variant_type_is_definite (type))
3921 g_error ("g_variant_new: NULL pointer given with indefinite "
3922 "array type; unable to determine which type of empty "
3923 "array to construct.");
3925 return g_variant_new_array (type, NULL, 0);
3932 value = g_variant_new_string (ptr);
3935 value = g_variant_new_string ("[Invalid UTF-8]");
3941 return g_variant_new_object_path (ptr);
3944 return g_variant_new_signature (ptr);
3952 type = g_variant_scan_convenience (str, &constant, &arrays);
3955 return g_variant_new_strv (ptr, -1);
3958 return g_variant_new_objv (ptr, -1);
3961 return g_variant_new_bytestring_array (ptr, -1);
3963 return g_variant_new_bytestring (ptr);
3967 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
3968 g_error ("g_variant_new: expected GVariant of type `%s' but "
3969 "received value has type `%s'",
3970 g_variant_type_dup_string ((GVariantType *) *str),
3971 g_variant_get_type_string (ptr));
3973 g_variant_type_string_scan (*str, NULL, str);
3981 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
3982 g_error ("g_variant_new: format string `?' expects basic-typed "
3983 "GVariant, but received value has type `%s'",
3984 g_variant_get_type_string (ptr));
3989 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
3990 g_error ("g_variant_new: format string `r` expects tuple-typed "
3991 "GVariant, but received value has type `%s'",
3992 g_variant_get_type_string (ptr));
3997 return g_variant_new_variant (ptr);
4000 g_assert_not_reached ();
4005 g_variant_valist_get_nnp (const gchar **str,
4011 g_variant_type_string_scan (*str, NULL, str);
4012 return g_variant_iter_new (value);
4016 return (gchar *) g_variant_get_string (value, NULL);
4021 return g_variant_dup_string (value, NULL);
4029 type = g_variant_scan_convenience (str, &constant, &arrays);
4034 return g_variant_get_strv (value, NULL);
4036 return g_variant_dup_strv (value, NULL);
4039 else if (type == 'o')
4042 return g_variant_get_objv (value, NULL);
4044 return g_variant_dup_objv (value, NULL);
4047 else if (arrays > 1)
4050 return g_variant_get_bytestring_array (value, NULL);
4052 return g_variant_dup_bytestring_array (value, NULL);
4058 return (gchar *) g_variant_get_bytestring (value);
4060 return g_variant_dup_bytestring (value, NULL);
4065 g_variant_type_string_scan (*str, NULL, str);
4071 return g_variant_ref (value);
4074 return g_variant_get_variant (value);
4077 g_assert_not_reached ();
4083 g_variant_valist_skip_leaf (const gchar **str,
4086 if (g_variant_format_string_is_nnp (*str))
4088 g_variant_format_string_scan (*str, NULL, str);
4089 va_arg (*app, gpointer);
4107 va_arg (*app, guint64);
4111 va_arg (*app, gdouble);
4115 g_assert_not_reached ();
4120 g_variant_valist_new_leaf (const gchar **str,
4123 if (g_variant_format_string_is_nnp (*str))
4124 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4129 return g_variant_new_boolean (va_arg (*app, gboolean));
4132 return g_variant_new_byte (va_arg (*app, guint));
4135 return g_variant_new_int16 (va_arg (*app, gint));
4138 return g_variant_new_uint16 (va_arg (*app, guint));
4141 return g_variant_new_int32 (va_arg (*app, gint));
4144 return g_variant_new_uint32 (va_arg (*app, guint));
4147 return g_variant_new_int64 (va_arg (*app, gint64));
4150 return g_variant_new_uint64 (va_arg (*app, guint64));
4153 return g_variant_new_handle (va_arg (*app, gint));
4156 return g_variant_new_double (va_arg (*app, gdouble));
4159 g_assert_not_reached ();
4163 /* The code below assumes this */
4164 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4165 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4168 g_variant_valist_get_leaf (const gchar **str,
4173 gpointer ptr = va_arg (*app, gpointer);
4177 g_variant_format_string_scan (*str, NULL, str);
4181 if (g_variant_format_string_is_nnp (*str))
4183 gpointer *nnp = (gpointer *) ptr;
4185 if (free && *nnp != NULL)
4186 g_variant_valist_free_nnp (*str, *nnp);
4191 *nnp = g_variant_valist_get_nnp (str, value);
4193 g_variant_format_string_scan (*str, NULL, str);
4203 *(gboolean *) ptr = g_variant_get_boolean (value);
4207 *(guchar *) ptr = g_variant_get_byte (value);
4211 *(gint16 *) ptr = g_variant_get_int16 (value);
4215 *(guint16 *) ptr = g_variant_get_uint16 (value);
4219 *(gint32 *) ptr = g_variant_get_int32 (value);
4223 *(guint32 *) ptr = g_variant_get_uint32 (value);
4227 *(gint64 *) ptr = g_variant_get_int64 (value);
4231 *(guint64 *) ptr = g_variant_get_uint64 (value);
4235 *(gint32 *) ptr = g_variant_get_handle (value);
4239 *(gdouble *) ptr = g_variant_get_double (value);
4248 *(guchar *) ptr = 0;
4253 *(guint16 *) ptr = 0;
4260 *(guint32 *) ptr = 0;
4266 *(guint64 *) ptr = 0;
4271 g_assert_not_reached ();
4274 /* Generic (recursive) {{{2 */
4276 g_variant_valist_skip (const gchar **str,
4279 if (g_variant_format_string_is_leaf (*str))
4280 g_variant_valist_skip_leaf (str, app);
4282 else if (**str == 'm') /* maybe */
4286 if (!g_variant_format_string_is_nnp (*str))
4287 va_arg (*app, gboolean);
4289 g_variant_valist_skip (str, app);
4291 else /* tuple, dictionary entry */
4293 g_assert (**str == '(' || **str == '{');
4295 while (**str != ')' && **str != '}')
4296 g_variant_valist_skip (str, app);
4302 g_variant_valist_new (const gchar **str,
4305 if (g_variant_format_string_is_leaf (*str))
4306 return g_variant_valist_new_leaf (str, app);
4308 if (**str == 'm') /* maybe */
4310 GVariantType *type = NULL;
4311 GVariant *value = NULL;
4315 if (g_variant_format_string_is_nnp (*str))
4317 gpointer nnp = va_arg (*app, gpointer);
4320 value = g_variant_valist_new_nnp (str, nnp);
4322 type = g_variant_format_string_scan_type (*str, NULL, str);
4326 gboolean just = va_arg (*app, gboolean);
4329 value = g_variant_valist_new (str, app);
4332 type = g_variant_format_string_scan_type (*str, NULL, NULL);
4333 g_variant_valist_skip (str, app);
4337 value = g_variant_new_maybe (type, value);
4340 g_variant_type_free (type);
4344 else /* tuple, dictionary entry */
4349 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
4352 g_assert (**str == '{');
4353 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
4357 while (**str != ')' && **str != '}')
4358 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
4361 return g_variant_builder_end (&b);
4366 g_variant_valist_get (const gchar **str,
4371 if (g_variant_format_string_is_leaf (*str))
4372 g_variant_valist_get_leaf (str, value, free, app);
4374 else if (**str == 'm')
4379 value = g_variant_get_maybe (value);
4381 if (!g_variant_format_string_is_nnp (*str))
4383 gboolean *ptr = va_arg (*app, gboolean *);
4386 *ptr = value != NULL;
4389 g_variant_valist_get (str, value, free, app);
4392 g_variant_unref (value);
4395 else /* tuple, dictionary entry */
4399 g_assert (**str == '(' || **str == '{');
4402 while (**str != ')' && **str != '}')
4406 GVariant *child = g_variant_get_child_value (value, index++);
4407 g_variant_valist_get (str, child, free, app);
4408 g_variant_unref (child);
4411 g_variant_valist_get (str, NULL, free, app);
4417 /* User-facing API {{{2 */
4419 * g_variant_new: (skip)
4420 * @format_string: a #GVariant format string
4421 * @...: arguments, as per @format_string
4422 * @returns: a new floating #GVariant instance
4424 * Creates a new #GVariant instance.
4426 * Think of this function as an analogue to g_strdup_printf().
4428 * The type of the created instance and the arguments that are
4429 * expected by this function are determined by @format_string. See the
4430 * section on <link linkend='gvariant-format-strings'>GVariant Format
4431 * Strings</link>. Please note that the syntax of the format string is
4432 * very likely to be extended in the future.
4434 * The first character of the format string must not be '*' '?' '@' or
4435 * 'r'; in essence, a new #GVariant must always be constructed by this
4436 * function (and not merely passed through it unmodified).
4441 g_variant_new (const gchar *format_string,
4447 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
4448 format_string[0] != '?' && format_string[0] != '@' &&
4449 format_string[0] != '*' && format_string[0] != 'r',
4452 va_start (ap, format_string);
4453 value = g_variant_new_va (format_string, NULL, &ap);
4460 * g_variant_new_va: (skip)
4461 * @format_string: a string that is prefixed with a format string
4462 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4464 * @app: a pointer to a #va_list
4465 * @returns: a new, usually floating, #GVariant
4467 * This function is intended to be used by libraries based on
4468 * #GVariant that want to provide g_variant_new()-like functionality
4471 * The API is more general than g_variant_new() to allow a wider range
4474 * @format_string must still point to a valid format string, but it only
4475 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
4476 * non-%NULL then it is updated to point to the first character past the
4477 * end of the format string.
4479 * @app is a pointer to a #va_list. The arguments, according to
4480 * @format_string, are collected from this #va_list and the list is left
4481 * pointing to the argument following the last.
4483 * These two generalisations allow mixing of multiple calls to
4484 * g_variant_new_va() and g_variant_get_va() within a single actual
4485 * varargs call by the user.
4487 * The return value will be floating if it was a newly created GVariant
4488 * instance (for example, if the format string was "(ii)"). In the case
4489 * that the format_string was '*', '?', 'r', or a format starting with
4490 * '@' then the collected #GVariant pointer will be returned unmodified,
4491 * without adding any additional references.
4493 * In order to behave correctly in all cases it is necessary for the
4494 * calling function to g_variant_ref_sink() the return result before
4495 * returning control to the user that originally provided the pointer.
4496 * At this point, the caller will have their own full reference to the
4497 * result. This can also be done by adding the result to a container,
4498 * or by passing it to another g_variant_new() call.
4503 g_variant_new_va (const gchar *format_string,
4504 const gchar **endptr,
4509 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
4511 g_return_val_if_fail (app != NULL, NULL);
4513 value = g_variant_valist_new (&format_string, app);
4516 *endptr = format_string;
4522 * g_variant_get: (skip)
4523 * @value: a #GVariant instance
4524 * @format_string: a #GVariant format string
4525 * @...: arguments, as per @format_string
4527 * Deconstructs a #GVariant instance.
4529 * Think of this function as an analogue to scanf().
4531 * The arguments that are expected by this function are entirely
4532 * determined by @format_string. @format_string also restricts the
4533 * permissible types of @value. It is an error to give a value with
4534 * an incompatible type. See the section on <link
4535 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
4536 * Please note that the syntax of the format string is very likely to be
4537 * extended in the future.
4542 g_variant_get (GVariant *value,
4543 const gchar *format_string,
4548 g_return_if_fail (valid_format_string (format_string, TRUE, value));
4550 /* if any direct-pointer-access formats are in use, flatten first */
4551 if (strchr (format_string, '&'))
4552 g_variant_get_data (value);
4554 va_start (ap, format_string);
4555 g_variant_get_va (value, format_string, NULL, &ap);
4560 * g_variant_get_va: (skip)
4561 * @value: a #GVariant
4562 * @format_string: a string that is prefixed with a format string
4563 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4565 * @app: a pointer to a #va_list
4567 * This function is intended to be used by libraries based on #GVariant
4568 * that want to provide g_variant_get()-like functionality to their
4571 * The API is more general than g_variant_get() to allow a wider range
4574 * @format_string must still point to a valid format string, but it only
4575 * need to be nul-terminated if @endptr is %NULL. If @endptr is
4576 * non-%NULL then it is updated to point to the first character past the
4577 * end of the format string.
4579 * @app is a pointer to a #va_list. The arguments, according to
4580 * @format_string, are collected from this #va_list and the list is left
4581 * pointing to the argument following the last.
4583 * These two generalisations allow mixing of multiple calls to
4584 * g_variant_new_va() and g_variant_get_va() within a single actual
4585 * varargs call by the user.
4590 g_variant_get_va (GVariant *value,
4591 const gchar *format_string,
4592 const gchar **endptr,
4595 g_return_if_fail (valid_format_string (format_string, !endptr, value));
4596 g_return_if_fail (value != NULL);
4597 g_return_if_fail (app != NULL);
4599 /* if any direct-pointer-access formats are in use, flatten first */
4600 if (strchr (format_string, '&'))
4601 g_variant_get_data (value);
4603 g_variant_valist_get (&format_string, value, FALSE, app);
4606 *endptr = format_string;
4609 /* Varargs-enabled Utility Functions {{{1 */
4612 * g_variant_builder_add: (skp)
4613 * @builder: a #GVariantBuilder
4614 * @format_string: a #GVariant varargs format string
4615 * @...: arguments, as per @format_string
4617 * Adds to a #GVariantBuilder.
4619 * This call is a convenience wrapper that is exactly equivalent to
4620 * calling g_variant_new() followed by g_variant_builder_add_value().
4622 * This function might be used as follows:
4626 * make_pointless_dictionary (void)
4628 * GVariantBuilder *builder;
4631 * builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
4632 * for (i = 0; i < 16; i++)
4636 * sprintf (buf, "%d", i);
4637 * g_variant_builder_add (builder, "{is}", i, buf);
4640 * return g_variant_builder_end (builder);
4647 g_variant_builder_add (GVariantBuilder *builder,
4648 const gchar *format_string,
4654 va_start (ap, format_string);
4655 variant = g_variant_new_va (format_string, NULL, &ap);
4658 g_variant_builder_add_value (builder, variant);
4662 * g_variant_get_child: (skip)
4663 * @value: a container #GVariant
4664 * @index_: the index of the child to deconstruct
4665 * @format_string: a #GVariant format string
4666 * @...: arguments, as per @format_string
4668 * Reads a child item out of a container #GVariant instance and
4669 * deconstructs it according to @format_string. This call is
4670 * essentially a combination of g_variant_get_child_value() and
4676 g_variant_get_child (GVariant *value,
4678 const gchar *format_string,
4684 child = g_variant_get_child_value (value, index_);
4685 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4687 va_start (ap, format_string);
4688 g_variant_get_va (child, format_string, NULL, &ap);
4691 g_variant_unref (child);
4695 * g_variant_iter_next: (skip)
4696 * @iter: a #GVariantIter
4697 * @format_string: a GVariant format string
4698 * @...: the arguments to unpack the value into
4699 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4702 * Gets the next item in the container and unpacks it into the variable
4703 * argument list according to @format_string, returning %TRUE.
4705 * If no more items remain then %FALSE is returned.
4707 * All of the pointers given on the variable arguments list of this
4708 * function are assumed to point at uninitialised memory. It is the
4709 * responsibility of the caller to free all of the values returned by
4710 * the unpacking process.
4712 * See the section on <link linkend='gvariant-format-strings'>GVariant
4713 * Format Strings</link>.
4716 * <title>Memory management with g_variant_iter_next()</title>
4718 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4720 * iterate_dictionary (GVariant *dictionary)
4722 * GVariantIter iter;
4726 * g_variant_iter_init (&iter, dictionary);
4727 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4729 * g_print ("Item '%s' has type '%s'\n", key,
4730 * g_variant_get_type_string (value));
4732 * /<!-- -->* must free data for ourselves *<!-- -->/
4733 * g_variant_unref (value);
4740 * For a solution that is likely to be more convenient to C programmers
4741 * when dealing with loops, see g_variant_iter_loop().
4746 g_variant_iter_next (GVariantIter *iter,
4747 const gchar *format_string,
4752 value = g_variant_iter_next_value (iter);
4754 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
4761 va_start (ap, format_string);
4762 g_variant_valist_get (&format_string, value, FALSE, &ap);
4765 g_variant_unref (value);
4768 return value != NULL;
4772 * g_variant_iter_loop: (skip)
4773 * @iter: a #GVariantIter
4774 * @format_string: a GVariant format string
4775 * @...: the arguments to unpack the value into
4776 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4779 * Gets the next item in the container and unpacks it into the variable
4780 * argument list according to @format_string, returning %TRUE.
4782 * If no more items remain then %FALSE is returned.
4784 * On the first call to this function, the pointers appearing on the
4785 * variable argument list are assumed to point at uninitialised memory.
4786 * On the second and later calls, it is assumed that the same pointers
4787 * will be given and that they will point to the memory as set by the
4788 * previous call to this function. This allows the previous values to
4789 * be freed, as appropriate.
4791 * This function is intended to be used with a while loop as
4792 * demonstrated in the following example. This function can only be
4793 * used when iterating over an array. It is only valid to call this
4794 * function with a string constant for the format string and the same
4795 * string constant must be used each time. Mixing calls to this
4796 * function and g_variant_iter_next() or g_variant_iter_next_value() on
4797 * the same iterator is not recommended.
4799 * See the section on <link linkend='gvariant-format-strings'>GVariant
4800 * Format Strings</link>.
4803 * <title>Memory management with g_variant_iter_loop()</title>
4805 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4807 * iterate_dictionary (GVariant *dictionary)
4809 * GVariantIter iter;
4813 * g_variant_iter_init (&iter, dictionary);
4814 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
4816 * g_print ("Item '%s' has type '%s'\n", key,
4817 * g_variant_get_type_string (value));
4819 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
4825 * For most cases you should use g_variant_iter_next().
4827 * This function is really only useful when unpacking into #GVariant or
4828 * #GVariantIter in order to allow you to skip the call to
4829 * g_variant_unref() or g_variant_iter_free().
4831 * For example, if you are only looping over simple integer and string
4832 * types, g_variant_iter_next() is definitely preferred. For string
4833 * types, use the '&' prefix to avoid allocating any memory at all (and
4834 * thereby avoiding the need to free anything as well).
4839 g_variant_iter_loop (GVariantIter *iter,
4840 const gchar *format_string,
4843 gboolean first_time = GVSI(iter)->loop_format == NULL;
4847 g_return_val_if_fail (first_time ||
4848 format_string == GVSI(iter)->loop_format,
4853 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
4854 GVSI(iter)->loop_format = format_string;
4856 if (strchr (format_string, '&'))
4857 g_variant_get_data (GVSI(iter)->value);
4860 value = g_variant_iter_next_value (iter);
4862 g_return_val_if_fail (!first_time ||
4863 valid_format_string (format_string, TRUE, value),
4866 va_start (ap, format_string);
4867 g_variant_valist_get (&format_string, value, !first_time, &ap);
4871 g_variant_unref (value);
4873 return value != NULL;
4876 /* Serialised data {{{1 */
4878 g_variant_deep_copy (GVariant *value)
4880 switch (g_variant_classify (value))
4882 case G_VARIANT_CLASS_MAYBE:
4883 case G_VARIANT_CLASS_ARRAY:
4884 case G_VARIANT_CLASS_TUPLE:
4885 case G_VARIANT_CLASS_DICT_ENTRY:
4886 case G_VARIANT_CLASS_VARIANT:
4888 GVariantBuilder builder;
4892 g_variant_builder_init (&builder, g_variant_get_type (value));
4893 g_variant_iter_init (&iter, value);
4895 while ((child = g_variant_iter_next_value (&iter)))
4897 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
4898 g_variant_unref (child);
4901 return g_variant_builder_end (&builder);
4904 case G_VARIANT_CLASS_BOOLEAN:
4905 return g_variant_new_boolean (g_variant_get_boolean (value));
4907 case G_VARIANT_CLASS_BYTE:
4908 return g_variant_new_byte (g_variant_get_byte (value));
4910 case G_VARIANT_CLASS_INT16:
4911 return g_variant_new_int16 (g_variant_get_int16 (value));
4913 case G_VARIANT_CLASS_UINT16:
4914 return g_variant_new_uint16 (g_variant_get_uint16 (value));
4916 case G_VARIANT_CLASS_INT32:
4917 return g_variant_new_int32 (g_variant_get_int32 (value));
4919 case G_VARIANT_CLASS_UINT32:
4920 return g_variant_new_uint32 (g_variant_get_uint32 (value));
4922 case G_VARIANT_CLASS_INT64:
4923 return g_variant_new_int64 (g_variant_get_int64 (value));
4925 case G_VARIANT_CLASS_UINT64:
4926 return g_variant_new_uint64 (g_variant_get_uint64 (value));
4928 case G_VARIANT_CLASS_HANDLE:
4929 return g_variant_new_handle (g_variant_get_handle (value));
4931 case G_VARIANT_CLASS_DOUBLE:
4932 return g_variant_new_double (g_variant_get_double (value));
4934 case G_VARIANT_CLASS_STRING:
4935 return g_variant_new_string (g_variant_get_string (value, NULL));
4937 case G_VARIANT_CLASS_OBJECT_PATH:
4938 return g_variant_new_object_path (g_variant_get_string (value, NULL));
4940 case G_VARIANT_CLASS_SIGNATURE:
4941 return g_variant_new_signature (g_variant_get_string (value, NULL));
4944 g_assert_not_reached ();
4948 * g_variant_get_normal_form:
4949 * @value: a #GVariant
4950 * @returns: (transfer full): a trusted #GVariant
4952 * Gets a #GVariant instance that has the same value as @value and is
4953 * trusted to be in normal form.
4955 * If @value is already trusted to be in normal form then a new
4956 * reference to @value is returned.
4958 * If @value is not already trusted, then it is scanned to check if it
4959 * is in normal form. If it is found to be in normal form then it is
4960 * marked as trusted and a new reference to it is returned.
4962 * If @value is found not to be in normal form then a new trusted
4963 * #GVariant is created with the same value as @value.
4965 * It makes sense to call this function if you've received #GVariant
4966 * data from untrusted sources and you want to ensure your serialised
4967 * output is definitely in normal form.
4972 g_variant_get_normal_form (GVariant *value)
4976 if (g_variant_is_normal_form (value))
4977 return g_variant_ref (value);
4979 trusted = g_variant_deep_copy (value);
4980 g_assert (g_variant_is_trusted (trusted));
4982 return g_variant_ref_sink (trusted);
4986 * g_variant_byteswap:
4987 * @value: a #GVariant
4988 * @returns: (transfer full): the byteswapped form of @value
4990 * Performs a byteswapping operation on the contents of @value. The
4991 * result is that all multi-byte numeric data contained in @value is
4992 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
4993 * integers as well as file handles and double precision floating point
4996 * This function is an identity mapping on any value that does not
4997 * contain multi-byte numeric data. That include strings, booleans,
4998 * bytes and containers containing only these things (recursively).
5000 * The returned value is always in normal form and is marked as trusted.
5005 g_variant_byteswap (GVariant *value)
5007 GVariantTypeInfo *type_info;
5011 type_info = g_variant_get_type_info (value);
5013 g_variant_type_info_query (type_info, &alignment, NULL);
5016 /* (potentially) contains multi-byte numeric data */
5018 GVariantSerialised serialised;
5022 trusted = g_variant_get_normal_form (value);
5023 serialised.type_info = g_variant_get_type_info (trusted);
5024 serialised.size = g_variant_get_size (trusted);
5025 serialised.data = g_malloc (serialised.size);
5026 g_variant_store (trusted, serialised.data);
5027 g_variant_unref (trusted);
5029 g_variant_serialised_byteswap (serialised);
5031 buffer = g_buffer_new_take_data (serialised.data, serialised.size);
5032 new = g_variant_new_from_buffer (g_variant_get_type (value), buffer, TRUE);
5033 g_buffer_unref (buffer);
5036 /* contains no multi-byte data */
5039 return g_variant_ref_sink (new);
5043 * g_variant_new_from_data:
5044 * @type: a definite #GVariantType
5045 * @data: (array length=size) (element-type guint8): the serialised data
5046 * @size: the size of @data
5047 * @trusted: %TRUE if @data is definitely in normal form
5048 * @notify: (scope async): function to call when @data is no longer needed
5049 * @user_data: data for @notify
5050 * @returns: (transfer none): a new floating #GVariant of type @type
5052 * Creates a new #GVariant instance from serialised data.
5054 * @type is the type of #GVariant instance that will be constructed.
5055 * The interpretation of @data depends on knowing the type.
5057 * @data is not modified by this function and must remain valid with an
5058 * unchanging value until such a time as @notify is called with
5059 * @user_data. If the contents of @data change before that time then
5060 * the result is undefined.
5062 * If @data is trusted to be serialised data in normal form then
5063 * @trusted should be %TRUE. This applies to serialised data created
5064 * within this process or read from a trusted location on the disk (such
5065 * as a file installed in /usr/lib alongside your application). You
5066 * should set trusted to %FALSE if @data is read from the network, a
5067 * file in the user's home directory, etc.
5069 * If @data was not stored in this machine's native endianness, any multi-byte
5070 * numeric values in the returned variant will also be in non-native
5071 * endianness. g_variant_byteswap() can be used to recover the original values.
5073 * @notify will be called with @user_data when @data is no longer
5074 * needed. The exact time of this call is unspecified and might even be
5075 * before this function returns.
5080 g_variant_new_from_data (const GVariantType *type,
5084 GDestroyNotify notify,
5090 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5091 g_return_val_if_fail (data != NULL || size == 0, NULL);
5094 buffer = g_buffer_new_from_pointer (data, size, notify, user_data);
5096 buffer = g_buffer_new_from_static_data (data, size);
5098 value = g_variant_new_from_buffer (type, buffer, trusted);
5099 g_buffer_unref (buffer);
5105 /* vim:set foldmethod=marker: */