2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the licence, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: Ryan Lortie <desrt@desrt.ca>
25 #include <glib/gvariant-serialiser.h>
26 #include "gvariant-internal.h"
27 #include <glib/gvariant-core.h>
28 #include <glib/gtestutils.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gslice.h>
31 #include <glib/ghash.h>
32 #include <glib/gmem.h>
40 * @short_description: strongly typed value datatype
41 * @see_also: GVariantType
43 * #GVariant is a variant datatype; it stores a value along with
44 * information about the type of that value. The range of possible
45 * values is determined by the type. The type system used by #GVariant
48 * #GVariant instances always have a type and a value (which are given
49 * at construction time). The type and value of a #GVariant instance
50 * can never change other than by the #GVariant itself being
51 * destroyed. A #GVariant cannot contain a pointer.
53 * #GVariant is reference counted using g_variant_ref() and
54 * g_variant_unref(). #GVariant also has floating reference counts --
55 * see g_variant_ref_sink().
57 * #GVariant is completely threadsafe. A #GVariant instance can be
58 * concurrently accessed in any way from any number of threads without
61 * #GVariant is heavily optimised for dealing with data in serialised
62 * form. It works particularly well with data located in memory-mapped
63 * files. It can perform nearly all deserialisation operations in a
64 * small constant time, usually touching only a single memory page.
65 * Serialised #GVariant data can also be sent over the network.
67 * #GVariant is largely compatible with D-Bus. Almost all types of
68 * #GVariant instances can be sent over D-Bus. See #GVariantType for
69 * exceptions. (However, #GVariant's serialisation format is not the same
70 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
71 * in the gio library, for those.)
73 * For space-efficiency, the #GVariant serialisation format does not
74 * automatically include the variant's length, type or endianness,
75 * which must either be implied from context (such as knowledge that a
76 * particular file format always contains a little-endian
77 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
78 * or supplied out-of-band (for instance, a length, type and/or endianness
79 * indicator could be placed at the beginning of a file, network message
82 * A #GVariant's size is limited mainly by any lower level operating
83 * system constraints, such as the number of bits in #gsize. For
84 * example, it is reasonable to have a 2GB file mapped into memory
85 * with #GMappedFile, and call g_variant_new_from_data() on it.
87 * For convenience to C programmers, #GVariant features powerful
88 * varargs-based value construction and destruction. This feature is
89 * designed to be embedded in other libraries.
91 * There is a Python-inspired text language for describing #GVariant
92 * values. #GVariant includes a printer for this language and a parser
93 * with type inferencing.
97 * #GVariant tries to be quite efficient with respect to memory use.
98 * This section gives a rough idea of how much memory is used by the
99 * current implementation. The information here is subject to change
102 * The memory allocated by #GVariant can be grouped into 4 broad
103 * purposes: memory for serialised data, memory for the type
104 * information cache, buffer management memory and memory for the
105 * #GVariant structure itself.
107 * ## Serialised Data Memory
109 * This is the memory that is used for storing GVariant data in
110 * serialised form. This is what would be sent over the network or
111 * what would end up on disk, not counting any indicator of the
112 * endianness, or of the length or type of the top-level variant.
114 * The amount of memory required to store a boolean is 1 byte. 16,
115 * 32 and 64 bit integers and floating point numbers
116 * use their "natural" size. Strings (including object path and
117 * signature strings) are stored with a nul terminator, and as such
118 * 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.
124 * Arrays use the amount of space required to store each of their
125 * members, concatenated. Additionally, if the items stored in an
126 * array are not of a fixed-size (ie: strings, other arrays, etc)
127 * then an additional framing offset is stored for each item. The
128 * size of this offset is either 1, 2 or 4 bytes depending on the
129 * overall size of the container. Additionally, extra padding bytes
130 * are added as required for alignment of child values.
132 * Tuples (including dictionary entries) use the amount of space
133 * required to store each of their members, concatenated, plus one
134 * framing offset (as per arrays) for each non-fixed-sized item in
135 * the tuple, except for the last one. Additionally, extra padding
136 * bytes are added as required for alignment of child values.
138 * Variants use the same amount of space as the item inside of the
139 * variant, plus 1 byte, plus the length of the type string for the
140 * item inside the variant.
142 * As an example, consider a dictionary mapping strings to variants.
143 * In the case that the dictionary is empty, 0 bytes are required for
146 * If we add an item "width" that maps to the int32 value of 500 then
147 * we will use 4 byte to store the int32 (so 6 for the variant
148 * containing it) and 6 bytes for the string. The variant must be
149 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
150 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
151 * for the dictionary entry. An additional 1 byte is added to the
152 * array as a framing offset making a total of 15 bytes.
154 * If we add another entry, "title" that maps to a nullable string
155 * that happens to have a value of null, then we use 0 bytes for the
156 * null value (and 3 bytes for the variant to contain it along with
157 * its type string) plus 6 bytes for the string. Again, we need 2
158 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
160 * We now require extra padding between the two items in the array.
161 * After the 14 bytes of the first item, that's 2 bytes required.
162 * We now require 2 framing offsets for an extra two
163 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
166 * ## Type Information Cache
168 * For each GVariant type that currently exists in the program a type
169 * information structure is kept in the type information cache. The
170 * type information structure is required for rapid deserialisation.
172 * Continuing with the above example, if a #GVariant exists with the
173 * type "a{sv}" then a type information struct will exist for
174 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
175 * will share the same type information. Additionally, all
176 * single-digit types are stored in read-only static memory and do
177 * not contribute to the writable memory footprint of a program using
180 * Aside from the type information structures stored in read-only
181 * memory, there are two forms of type information. One is used for
182 * container types where there is a single element type: arrays and
183 * maybe types. The other is used for container types where there
184 * are multiple element types: tuples and dictionary entries.
186 * Array type info structures are 6 * sizeof (void *), plus the
187 * memory required to store the type string itself. This means that
188 * on 32-bit systems, the cache entry for "a{sv}" would require 30
189 * bytes of memory (plus malloc overhead).
191 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
192 * sizeof (void *) for each item in the tuple, plus the memory
193 * required to store the type string itself. A 2-item tuple, for
194 * example, would have a type information structure that consumed
195 * writable memory in the size of 14 * sizeof (void *) (plus type
196 * string) This means that on 32-bit systems, the cache entry for
197 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
199 * This means that in total, for our "a{sv}" example, 91 bytes of
200 * type information would be allocated.
202 * The type information cache, additionally, uses a #GHashTable to
203 * store and lookup the cached items and stores a pointer to this
204 * hash table in static storage. The hash table is freed when there
205 * are zero items in the type cache.
207 * Although these sizes may seem large it is important to remember
208 * that a program will probably only have a very small number of
209 * different types of values in it and that only one type information
210 * structure is required for many different values of the same type.
212 * ## Buffer Management Memory
214 * #GVariant uses an internal buffer management structure to deal
215 * with the various different possible sources of serialised data
216 * that it uses. The buffer is responsible for ensuring that the
217 * correct call is made when the data is no longer in use by
218 * #GVariant. This may involve a g_free() or a g_slice_free() or
219 * even g_mapped_file_unref().
221 * One buffer management structure is used for each chunk of
222 * serialised data. The size of the buffer management structure
223 * is 4 * (void *). On 32-bit systems, that's 16 bytes.
225 * ## GVariant structure
227 * The size of a #GVariant structure is 6 * (void *). On 32-bit
228 * systems, that's 24 bytes.
230 * #GVariant structures only exist if they are explicitly created
231 * with API calls. For example, if a #GVariant is constructed out of
232 * serialised data for the example given above (with the dictionary)
233 * then although there are 9 individual values that comprise the
234 * entire dictionary (two keys, two values, two variants containing
235 * the values, two dictionary entries, plus the dictionary itself),
236 * only 1 #GVariant instance exists -- the one referring to the
239 * If calls are made to start accessing the other values then
240 * #GVariant instances will exist for those values only for as long
241 * as they are in use (ie: until you call g_variant_unref()). The
242 * type information is shared. The serialised data and the buffer
243 * management structure for that serialised data is shared by the
248 * To put the entire example together, for our dictionary mapping
249 * strings to variants (with two entries, as given above), we are
250 * using 91 bytes of memory for type information, 29 byes of memory
251 * for the serialised data, 16 bytes for buffer management and 24
252 * bytes for the #GVariant instance, or a total of 160 bytes, plus
253 * malloc overhead. If we were to use g_variant_get_child_value() to
254 * access the two dictionary entries, we would use an additional 48
255 * bytes. If we were to have other dictionaries of the same type, we
256 * would use more memory for the serialised data and buffer
257 * management for those dictionaries, but the type information would
261 /* definition of GVariant structure is in gvariant-core.c */
263 /* this is a g_return_val_if_fail() for making
264 * sure a (GVariant *) has the required type.
266 #define TYPE_CHECK(value, TYPE, val) \
267 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
268 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
269 "g_variant_is_of_type (" #value \
274 /* Numeric Type Constructor/Getters {{{1 */
276 * g_variant_new_from_trusted:
277 * @type: the #GVariantType
278 * @data: the data to use
279 * @size: the size of @data
281 * Constructs a new trusted #GVariant instance from the provided data.
282 * This is used to implement g_variant_new_* for all the basic types.
284 * Returns: a new floating #GVariant
287 g_variant_new_from_trusted (const GVariantType *type,
294 bytes = g_bytes_new (data, size);
295 value = g_variant_new_from_bytes (type, bytes, TRUE);
296 g_bytes_unref (bytes);
302 * g_variant_new_boolean:
303 * @value: a #gboolean value
305 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
307 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
312 g_variant_new_boolean (gboolean value)
316 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
320 * g_variant_get_boolean:
321 * @value: a boolean #GVariant instance
323 * Returns the boolean value of @value.
325 * It is an error to call this function with a @value of any type
326 * other than %G_VARIANT_TYPE_BOOLEAN.
328 * Returns: %TRUE or %FALSE
333 g_variant_get_boolean (GVariant *value)
337 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
339 data = g_variant_get_data (value);
341 return data != NULL ? *data != 0 : FALSE;
344 /* the constructors and accessors for byte, int{16,32,64}, handles and
345 * floats all look pretty much exactly the same, so we reduce
348 #define NUMERIC_TYPE(TYPE, type, ctype) \
349 GVariant *g_variant_new_##type (ctype value) { \
350 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
351 &value, sizeof value); \
353 ctype g_variant_get_##type (GVariant *value) { \
355 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
356 data = g_variant_get_data (value); \
357 return data != NULL ? *data : 0; \
362 * g_variant_new_byte:
363 * @value: a #guint8 value
365 * Creates a new byte #GVariant instance.
367 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
372 * g_variant_get_byte:
373 * @value: a byte #GVariant instance
375 * Returns the byte value of @value.
377 * It is an error to call this function with a @value of any type
378 * other than %G_VARIANT_TYPE_BYTE.
384 NUMERIC_TYPE (BYTE, byte, guchar)
387 * g_variant_new_int16:
388 * @value: a #gint16 value
390 * Creates a new int16 #GVariant instance.
392 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
397 * g_variant_get_int16:
398 * @value: a int16 #GVariant instance
400 * Returns the 16-bit signed integer value of @value.
402 * It is an error to call this function with a @value of any type
403 * other than %G_VARIANT_TYPE_INT16.
409 NUMERIC_TYPE (INT16, int16, gint16)
412 * g_variant_new_uint16:
413 * @value: a #guint16 value
415 * Creates a new uint16 #GVariant instance.
417 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
422 * g_variant_get_uint16:
423 * @value: a uint16 #GVariant instance
425 * Returns the 16-bit unsigned integer value of @value.
427 * It is an error to call this function with a @value of any type
428 * other than %G_VARIANT_TYPE_UINT16.
430 * Returns: a #guint16
434 NUMERIC_TYPE (UINT16, uint16, guint16)
437 * g_variant_new_int32:
438 * @value: a #gint32 value
440 * Creates a new int32 #GVariant instance.
442 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
447 * g_variant_get_int32:
448 * @value: a int32 #GVariant instance
450 * Returns the 32-bit signed integer value of @value.
452 * It is an error to call this function with a @value of any type
453 * other than %G_VARIANT_TYPE_INT32.
459 NUMERIC_TYPE (INT32, int32, gint32)
462 * g_variant_new_uint32:
463 * @value: a #guint32 value
465 * Creates a new uint32 #GVariant instance.
467 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
472 * g_variant_get_uint32:
473 * @value: a uint32 #GVariant instance
475 * Returns the 32-bit unsigned integer value of @value.
477 * It is an error to call this function with a @value of any type
478 * other than %G_VARIANT_TYPE_UINT32.
480 * Returns: a #guint32
484 NUMERIC_TYPE (UINT32, uint32, guint32)
487 * g_variant_new_int64:
488 * @value: a #gint64 value
490 * Creates a new int64 #GVariant instance.
492 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
497 * g_variant_get_int64:
498 * @value: a int64 #GVariant instance
500 * Returns the 64-bit signed integer value of @value.
502 * It is an error to call this function with a @value of any type
503 * other than %G_VARIANT_TYPE_INT64.
509 NUMERIC_TYPE (INT64, int64, gint64)
512 * g_variant_new_uint64:
513 * @value: a #guint64 value
515 * Creates a new uint64 #GVariant instance.
517 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
522 * g_variant_get_uint64:
523 * @value: a uint64 #GVariant instance
525 * Returns the 64-bit unsigned integer value of @value.
527 * It is an error to call this function with a @value of any type
528 * other than %G_VARIANT_TYPE_UINT64.
530 * Returns: a #guint64
534 NUMERIC_TYPE (UINT64, uint64, guint64)
537 * g_variant_new_handle:
538 * @value: a #gint32 value
540 * Creates a new handle #GVariant instance.
542 * By convention, handles are indexes into an array of file descriptors
543 * that are sent alongside a D-Bus message. If you're not interacting
544 * with D-Bus, you probably don't need them.
546 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
551 * g_variant_get_handle:
552 * @value: a handle #GVariant instance
554 * Returns the 32-bit signed integer value of @value.
556 * It is an error to call this function with a @value of any type other
557 * than %G_VARIANT_TYPE_HANDLE.
559 * By convention, handles are indexes into an array of file descriptors
560 * that are sent alongside a D-Bus message. If you're not interacting
561 * with D-Bus, you probably don't need them.
567 NUMERIC_TYPE (HANDLE, handle, gint32)
570 * g_variant_new_float:
571 * @value: a #gfloat floating point value
573 * Creates a new float #GVariant instance.
575 * Returns: (transfer none): a floating reference to a new float #GVariant instance
580 * g_variant_get_float:
581 * @value: a float #GVariant instance
583 * Returns the single precision floating point value of @value.
585 * It is an error to call this function with a @value of any type
586 * other than %G_VARIANT_TYPE_FLOAT.
592 NUMERIC_TYPE (FLOAT, float, gfloat)
595 * g_variant_new_double:
596 * @value: a #gdouble floating point value
598 * Creates a new double #GVariant instance.
600 * Returns: (transfer none): a floating reference to a new double #GVariant instance
605 * g_variant_get_double:
606 * @value: a double #GVariant instance
608 * Returns the double precision floating point value of @value.
610 * It is an error to call this function with a @value of any type
611 * other than %G_VARIANT_TYPE_DOUBLE.
613 * Returns: a #gdouble
617 NUMERIC_TYPE (DOUBLE, double, gdouble)
619 /* Container type Constructor / Deconstructors {{{1 */
621 * g_variant_new_maybe:
622 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
623 * @child: (allow-none): the child value, or %NULL
625 * Depending on if @child is %NULL, either wraps @child inside of a
626 * maybe container or creates a Nothing instance for the given @type.
628 * At least one of @child_type and @child must be non-%NULL.
629 * If @child_type is non-%NULL then it must be a definite type.
630 * If they are both non-%NULL then @child_type must be the type
633 * If @child is a floating reference (see g_variant_ref_sink()), the new
634 * instance takes ownership of @child.
636 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
641 g_variant_new_maybe (const GVariantType *child_type,
644 GVariantType *maybe_type;
647 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
649 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
650 g_return_val_if_fail (child_type == NULL || child == NULL ||
651 g_variant_is_of_type (child, child_type),
654 if (child_type == NULL)
655 child_type = g_variant_get_type (child);
657 maybe_type = g_variant_type_new_maybe (child_type);
664 children = g_new (GVariant *, 1);
665 children[0] = g_variant_ref_sink (child);
666 trusted = g_variant_is_trusted (children[0]);
668 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
671 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
673 g_variant_type_free (maybe_type);
679 * g_variant_get_maybe:
680 * @value: a maybe-typed value
682 * Given a maybe-typed #GVariant instance, extract its value. If the
683 * value is Nothing, then this function returns %NULL.
685 * Returns: (allow-none) (transfer full): the contents of @value, or %NULL
690 g_variant_get_maybe (GVariant *value)
692 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
694 if (g_variant_n_children (value))
695 return g_variant_get_child_value (value, 0);
701 * g_variant_new_variant: (constructor)
702 * @value: a #GVariant instance
704 * Boxes @value. The result is a #GVariant instance representing a
705 * variant containing the original value.
707 * If @child is a floating reference (see g_variant_ref_sink()), the new
708 * instance takes ownership of @child.
710 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
715 g_variant_new_variant (GVariant *value)
717 g_return_val_if_fail (value != NULL, NULL);
719 g_variant_ref_sink (value);
721 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
722 g_memdup (&value, sizeof value),
723 1, g_variant_is_trusted (value));
727 * g_variant_get_variant:
728 * @value: a variant #GVariant instance
730 * Unboxes @value. The result is the #GVariant instance that was
731 * contained in @value.
733 * Returns: (transfer full): the item contained in the variant
738 g_variant_get_variant (GVariant *value)
740 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
742 return g_variant_get_child_value (value, 0);
746 * g_variant_new_array:
747 * @child_type: (allow-none): the element type of the new array
748 * @children: (allow-none) (array length=n_children): an array of
749 * #GVariant pointers, the children
750 * @n_children: the length of @children
752 * Creates a new #GVariant array from @children.
754 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
755 * child type is determined by inspecting the first element of the
756 * @children array. If @child_type is non-%NULL then it must be a
759 * The items of the array are taken from the @children array. No entry
760 * in the @children array may be %NULL.
762 * All items in the array must have the same type, which must be the
763 * same as @child_type, if given.
765 * If the @children are floating references (see g_variant_ref_sink()), the
766 * new instance takes ownership of them as if via g_variant_ref_sink().
768 * Returns: (transfer none): a floating reference to a new #GVariant array
773 g_variant_new_array (const GVariantType *child_type,
774 GVariant * const *children,
777 GVariantType *array_type;
778 GVariant **my_children;
783 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
784 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
785 g_return_val_if_fail (child_type == NULL ||
786 g_variant_type_is_definite (child_type), NULL);
788 my_children = g_new (GVariant *, n_children);
791 if (child_type == NULL)
792 child_type = g_variant_get_type (children[0]);
793 array_type = g_variant_type_new_array (child_type);
795 for (i = 0; i < n_children; i++)
797 TYPE_CHECK (children[i], child_type, NULL);
798 my_children[i] = g_variant_ref_sink (children[i]);
799 trusted &= g_variant_is_trusted (children[i]);
802 value = g_variant_new_from_children (array_type, my_children,
803 n_children, trusted);
804 g_variant_type_free (array_type);
810 * g_variant_make_tuple_type:
811 * @children: (array length=n_children): an array of GVariant *
812 * @n_children: the length of @children
814 * Return the type of a tuple containing @children as its items.
816 static GVariantType *
817 g_variant_make_tuple_type (GVariant * const *children,
820 const GVariantType **types;
824 types = g_new (const GVariantType *, n_children);
826 for (i = 0; i < n_children; i++)
827 types[i] = g_variant_get_type (children[i]);
829 type = g_variant_type_new_tuple (types, n_children);
836 * g_variant_new_tuple:
837 * @children: (array length=n_children): the items to make the tuple out of
838 * @n_children: the length of @children
840 * Creates a new tuple #GVariant out of the items in @children. The
841 * type is determined from the types of @children. No entry in the
842 * @children array may be %NULL.
844 * If @n_children is 0 then the unit tuple is constructed.
846 * If the @children are floating references (see g_variant_ref_sink()), the
847 * new instance takes ownership of them as if via g_variant_ref_sink().
849 * Returns: (transfer none): a floating reference to a new #GVariant tuple
854 g_variant_new_tuple (GVariant * const *children,
857 GVariantType *tuple_type;
858 GVariant **my_children;
863 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
865 my_children = g_new (GVariant *, n_children);
868 for (i = 0; i < n_children; i++)
870 my_children[i] = g_variant_ref_sink (children[i]);
871 trusted &= g_variant_is_trusted (children[i]);
874 tuple_type = g_variant_make_tuple_type (children, n_children);
875 value = g_variant_new_from_children (tuple_type, my_children,
876 n_children, trusted);
877 g_variant_type_free (tuple_type);
883 * g_variant_make_dict_entry_type:
884 * @key: a #GVariant, the key
885 * @val: a #GVariant, the value
887 * Return the type of a dictionary entry containing @key and @val as its
890 static GVariantType *
891 g_variant_make_dict_entry_type (GVariant *key,
894 return g_variant_type_new_dict_entry (g_variant_get_type (key),
895 g_variant_get_type (val));
899 * g_variant_new_dict_entry: (constructor)
900 * @key: a basic #GVariant, the key
901 * @value: a #GVariant, the value
903 * Creates a new dictionary entry #GVariant. @key and @value must be
904 * non-%NULL. @key must be a value of a basic type (ie: not a container).
906 * If the @key or @value are floating references (see g_variant_ref_sink()),
907 * the new instance takes ownership of them as if via g_variant_ref_sink().
909 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
914 g_variant_new_dict_entry (GVariant *key,
917 GVariantType *dict_type;
921 g_return_val_if_fail (key != NULL && value != NULL, NULL);
922 g_return_val_if_fail (!g_variant_is_container (key), NULL);
924 children = g_new (GVariant *, 2);
925 children[0] = g_variant_ref_sink (key);
926 children[1] = g_variant_ref_sink (value);
927 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
929 dict_type = g_variant_make_dict_entry_type (key, value);
930 value = g_variant_new_from_children (dict_type, children, 2, trusted);
931 g_variant_type_free (dict_type);
937 * g_variant_lookup: (skip)
938 * @dictionary: a dictionary #GVariant
939 * @key: the key to lookup in the dictionary
940 * @format_string: a GVariant format string
941 * @...: the arguments to unpack the value into
943 * Looks up a value in a dictionary #GVariant.
945 * This function is a wrapper around g_variant_lookup_value() and
946 * g_variant_get(). In the case that %NULL would have been returned,
947 * this function returns %FALSE. Otherwise, it unpacks the returned
948 * value and returns %TRUE.
950 * @format_string determines the C types that are used for unpacking
951 * the values and also determines if the values are copied or borrowed,
953 * [GVariant format strings][gvariant-format-strings-pointers].
955 * This function is currently implemented with a linear scan. If you
956 * plan to do many lookups then #GVariantDict may be more efficient.
958 * Returns: %TRUE if a value was unpacked
963 g_variant_lookup (GVariant *dictionary,
965 const gchar *format_string,
972 g_variant_get_data (dictionary);
974 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
975 value = g_variant_lookup_value (dictionary, key, type);
976 g_variant_type_free (type);
982 va_start (ap, format_string);
983 g_variant_get_va (value, format_string, NULL, &ap);
984 g_variant_unref (value);
995 * g_variant_lookup_value:
996 * @dictionary: a dictionary #GVariant
997 * @key: the key to lookup in the dictionary
998 * @expected_type: (allow-none): a #GVariantType, or %NULL
1000 * Looks up a value in a dictionary #GVariant.
1002 * This function works with dictionaries of the type a{s*} (and equally
1003 * well with type a{o*}, but we only further discuss the string case
1004 * for sake of clarity).
1006 * In the event that @dictionary has the type a{sv}, the @expected_type
1007 * string specifies what type of value is expected to be inside of the
1008 * variant. If the value inside the variant has a different type then
1009 * %NULL is returned. In the event that @dictionary has a value type other
1010 * than v then @expected_type must directly match the key type and it is
1011 * used to unpack the value directly or an error occurs.
1013 * In either case, if @key is not found in @dictionary, %NULL is returned.
1015 * If the key is found and the value has the correct type, it is
1016 * returned. If @expected_type was specified then any non-%NULL return
1017 * value will have this type.
1019 * This function is currently implemented with a linear scan. If you
1020 * plan to do many lookups then #GVariantDict may be more efficient.
1022 * Returns: (transfer full): the value of the dictionary key, or %NULL
1027 g_variant_lookup_value (GVariant *dictionary,
1029 const GVariantType *expected_type)
1035 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1036 G_VARIANT_TYPE ("a{s*}")) ||
1037 g_variant_is_of_type (dictionary,
1038 G_VARIANT_TYPE ("a{o*}")),
1041 g_variant_iter_init (&iter, dictionary);
1043 while ((entry = g_variant_iter_next_value (&iter)))
1045 GVariant *entry_key;
1048 entry_key = g_variant_get_child_value (entry, 0);
1049 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1050 g_variant_unref (entry_key);
1055 g_variant_unref (entry);
1061 value = g_variant_get_child_value (entry, 1);
1062 g_variant_unref (entry);
1064 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1068 tmp = g_variant_get_variant (value);
1069 g_variant_unref (value);
1071 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1073 g_variant_unref (tmp);
1080 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1081 g_variant_is_of_type (value, expected_type), NULL);
1087 * g_variant_get_fixed_array:
1088 * @value: a #GVariant array with fixed-sized elements
1089 * @n_elements: (out): a pointer to the location to store the number of items
1090 * @element_size: the size of each element
1092 * Provides access to the serialised data for an array of fixed-sized
1095 * @value must be an array with fixed-sized elements. Numeric types are
1096 * fixed-size, as are tuples containing only other fixed-sized types.
1098 * @element_size must be the size of a single element in the array,
1099 * as given by the section on
1100 * [serialized data memory][gvariant-serialised-data-memory].
1102 * In particular, arrays of these fixed-sized types can be interpreted
1103 * as an array of the given C type, with @element_size set to the size
1104 * the appropriate type:
1105 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1106 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1107 * - %G_VARIANT_TYPE_BYTE: #guchar
1108 * - %G_VARIANT_TYPE_HANDLE: #guint32
1109 * - %G_VARIANT_TYPE_FLOAT: #gfloat
1110 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1112 * For example, if calling this function for an array of 32-bit integers,
1113 * you might say sizeof(gint32). This value isn't used except for the purpose
1114 * of a double-check that the form of the serialised data matches the caller's
1117 * @n_elements, which must be non-%NULL is set equal to the number of
1118 * items in the array.
1120 * Returns: (array length=n_elements) (transfer none): a pointer to
1126 g_variant_get_fixed_array (GVariant *value,
1130 GVariantTypeInfo *array_info;
1131 gsize array_element_size;
1135 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1137 g_return_val_if_fail (n_elements != NULL, NULL);
1138 g_return_val_if_fail (element_size > 0, NULL);
1140 array_info = g_variant_get_type_info (value);
1141 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1143 g_return_val_if_fail (array_element_size, NULL);
1145 if G_UNLIKELY (array_element_size != element_size)
1147 if (array_element_size)
1148 g_critical ("g_variant_get_fixed_array: assertion "
1149 "'g_variant_array_has_fixed_size (value, element_size)' "
1150 "failed: array size %"G_GSIZE_FORMAT" does not match "
1151 "given element_size %"G_GSIZE_FORMAT".",
1152 array_element_size, element_size);
1154 g_critical ("g_variant_get_fixed_array: assertion "
1155 "'g_variant_array_has_fixed_size (value, element_size)' "
1156 "failed: array does not have fixed size.");
1159 data = g_variant_get_data (value);
1160 size = g_variant_get_size (value);
1162 if (size % element_size)
1165 *n_elements = size / element_size;
1174 * g_variant_new_fixed_array:
1175 * @element_type: the #GVariantType of each element
1176 * @elements: a pointer to the fixed array of contiguous elements
1177 * @n_elements: the number of elements
1178 * @element_size: the size of each element
1180 * Provides access to the serialised data for an array of fixed-sized
1183 * @value must be an array with fixed-sized elements. Numeric types are
1184 * fixed-size as are tuples containing only other fixed-sized types.
1186 * @element_size must be the size of a single element in the array.
1187 * For example, if calling this function for an array of 32-bit integers,
1188 * you might say sizeof(gint32). This value isn't used except for the purpose
1189 * of a double-check that the form of the serialised data matches the caller's
1192 * @n_elements, which must be non-%NULL is set equal to the number of
1193 * items in the array.
1195 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1200 g_variant_new_fixed_array (const GVariantType *element_type,
1201 gconstpointer elements,
1205 GVariantType *array_type;
1206 gsize array_element_size;
1207 GVariantTypeInfo *array_info;
1211 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1212 g_return_val_if_fail (element_size > 0, NULL);
1214 array_type = g_variant_type_new_array (element_type);
1215 array_info = g_variant_type_info_get (array_type);
1216 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1217 if G_UNLIKELY (array_element_size != element_size)
1219 if (array_element_size)
1220 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1221 " does not match given element_size %" G_GSIZE_FORMAT ".",
1222 array_element_size, element_size);
1224 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1228 data = g_memdup (elements, n_elements * element_size);
1229 value = g_variant_new_from_data (array_type, data,
1230 n_elements * element_size,
1231 FALSE, g_free, data);
1233 g_variant_type_free (array_type);
1234 g_variant_type_info_unref (array_info);
1239 /* String type constructor/getters/validation {{{1 */
1241 * g_variant_new_string:
1242 * @string: a normal utf8 nul-terminated string
1244 * Creates a string #GVariant with the contents of @string.
1246 * @string must be valid utf8.
1248 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1253 g_variant_new_string (const gchar *string)
1255 g_return_val_if_fail (string != NULL, NULL);
1256 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1258 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1259 string, strlen (string) + 1);
1263 * g_variant_new_take_string: (skip)
1264 * @string: a normal utf8 nul-terminated string
1266 * Creates a string #GVariant with the contents of @string.
1268 * @string must be valid utf8.
1270 * This function consumes @string. g_free() will be called on @string
1271 * when it is no longer required.
1273 * You must not modify or access @string in any other way after passing
1274 * it to this function. It is even possible that @string is immediately
1277 * Returns: (transfer none): a floating reference to a new string
1278 * #GVariant instance
1283 g_variant_new_take_string (gchar *string)
1288 g_return_val_if_fail (string != NULL, NULL);
1289 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1291 bytes = g_bytes_new_take (string, strlen (string) + 1);
1292 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1293 g_bytes_unref (bytes);
1299 * g_variant_new_printf: (skip)
1300 * @format_string: a printf-style format string
1301 * @...: arguments for @format_string
1303 * Creates a string-type GVariant using printf formatting.
1305 * This is similar to calling g_strdup_printf() and then
1306 * g_variant_new_string() but it saves a temporary variable and an
1309 * Returns: (transfer none): a floating reference to a new string
1310 * #GVariant instance
1315 g_variant_new_printf (const gchar *format_string,
1323 g_return_val_if_fail (format_string != NULL, NULL);
1325 va_start (ap, format_string);
1326 string = g_strdup_vprintf (format_string, ap);
1329 bytes = g_bytes_new_take (string, strlen (string) + 1);
1330 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1331 g_bytes_unref (bytes);
1337 * g_variant_new_object_path:
1338 * @object_path: a normal C nul-terminated string
1340 * Creates a D-Bus object path #GVariant with the contents of @string.
1341 * @string must be a valid D-Bus object path. Use
1342 * g_variant_is_object_path() if you're not sure.
1344 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1349 g_variant_new_object_path (const gchar *object_path)
1351 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1353 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1354 object_path, strlen (object_path) + 1);
1358 * g_variant_is_object_path:
1359 * @string: a normal C nul-terminated string
1361 * Determines if a given string is a valid D-Bus object path. You
1362 * should ensure that a string is a valid D-Bus object path before
1363 * passing it to g_variant_new_object_path().
1365 * A valid object path starts with '/' followed by zero or more
1366 * sequences of characters separated by '/' characters. Each sequence
1367 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1368 * (including the one following the final '/' character) may be empty.
1370 * Returns: %TRUE if @string is a D-Bus object path
1375 g_variant_is_object_path (const gchar *string)
1377 g_return_val_if_fail (string != NULL, FALSE);
1379 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1383 * g_variant_new_signature:
1384 * @signature: a normal C nul-terminated string
1386 * Creates a D-Bus type signature #GVariant with the contents of
1387 * @string. @string must be a valid D-Bus type signature. Use
1388 * g_variant_is_signature() if you're not sure.
1390 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1395 g_variant_new_signature (const gchar *signature)
1397 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1399 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1400 signature, strlen (signature) + 1);
1404 * g_variant_is_signature:
1405 * @string: a normal C nul-terminated string
1407 * Determines if a given string is a valid D-Bus type signature. You
1408 * should ensure that a string is a valid D-Bus type signature before
1409 * passing it to g_variant_new_signature().
1411 * D-Bus type signatures consist of zero or more definite #GVariantType
1412 * strings in sequence.
1414 * Returns: %TRUE if @string is a D-Bus type signature
1419 g_variant_is_signature (const gchar *string)
1421 g_return_val_if_fail (string != NULL, FALSE);
1423 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1427 * g_variant_get_string:
1428 * @value: a string #GVariant instance
1429 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1430 * to store the length
1432 * Returns the string value of a #GVariant instance with a string
1433 * type. This includes the types %G_VARIANT_TYPE_STRING,
1434 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1436 * The string will always be utf8 encoded.
1438 * If @length is non-%NULL then the length of the string (in bytes) is
1439 * returned there. For trusted values, this information is already
1440 * known. For untrusted values, a strlen() will be performed.
1442 * It is an error to call this function with a @value of any type
1443 * other than those three.
1445 * The return value remains valid as long as @value exists.
1447 * Returns: (transfer none): the constant string, utf8 encoded
1452 g_variant_get_string (GVariant *value,
1458 g_return_val_if_fail (value != NULL, NULL);
1459 g_return_val_if_fail (
1460 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1461 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1462 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1464 data = g_variant_get_data (value);
1465 size = g_variant_get_size (value);
1467 if (!g_variant_is_trusted (value))
1469 switch (g_variant_classify (value))
1471 case G_VARIANT_CLASS_STRING:
1472 if (g_variant_serialiser_is_string (data, size))
1479 case G_VARIANT_CLASS_OBJECT_PATH:
1480 if (g_variant_serialiser_is_object_path (data, size))
1487 case G_VARIANT_CLASS_SIGNATURE:
1488 if (g_variant_serialiser_is_signature (data, size))
1496 g_assert_not_reached ();
1507 * g_variant_dup_string:
1508 * @value: a string #GVariant instance
1509 * @length: (out): a pointer to a #gsize, to store the length
1511 * Similar to g_variant_get_string() except that instead of returning
1512 * a constant string, the string is duplicated.
1514 * The string will always be utf8 encoded.
1516 * The return value must be freed using g_free().
1518 * Returns: (transfer full): a newly allocated string, utf8 encoded
1523 g_variant_dup_string (GVariant *value,
1526 return g_strdup (g_variant_get_string (value, length));
1530 * g_variant_new_strv:
1531 * @strv: (array length=length) (element-type utf8): an array of strings
1532 * @length: the length of @strv, or -1
1534 * Constructs an array of strings #GVariant from the given array of
1537 * If @length is -1 then @strv is %NULL-terminated.
1539 * Returns: (transfer none): a new floating #GVariant instance
1544 g_variant_new_strv (const gchar * const *strv,
1550 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1553 length = g_strv_length ((gchar **) strv);
1555 strings = g_new (GVariant *, length);
1556 for (i = 0; i < length; i++)
1557 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1559 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1560 strings, length, TRUE);
1564 * g_variant_get_strv:
1565 * @value: an array of strings #GVariant
1566 * @length: (out) (allow-none): the length of the result, or %NULL
1568 * Gets the contents of an array of strings #GVariant. This call
1569 * makes a shallow copy; the return result should be released with
1570 * g_free(), but the individual strings must not be modified.
1572 * If @length is non-%NULL then the number of elements in the result
1573 * is stored there. In any case, the resulting array will be
1576 * For an empty array, @length will be set to 0 and a pointer to a
1577 * %NULL pointer will be returned.
1579 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1584 g_variant_get_strv (GVariant *value,
1591 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1593 g_variant_get_data (value);
1594 n = g_variant_n_children (value);
1595 strv = g_new (const gchar *, n + 1);
1597 for (i = 0; i < n; i++)
1601 string = g_variant_get_child_value (value, i);
1602 strv[i] = g_variant_get_string (string, NULL);
1603 g_variant_unref (string);
1614 * g_variant_dup_strv:
1615 * @value: an array of strings #GVariant
1616 * @length: (out) (allow-none): the length of the result, or %NULL
1618 * Gets the contents of an array of strings #GVariant. This call
1619 * makes a deep copy; the return result should be released with
1622 * If @length is non-%NULL then the number of elements in the result
1623 * is stored there. In any case, the resulting array will be
1626 * For an empty array, @length will be set to 0 and a pointer to a
1627 * %NULL pointer will be returned.
1629 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1634 g_variant_dup_strv (GVariant *value,
1641 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1643 n = g_variant_n_children (value);
1644 strv = g_new (gchar *, n + 1);
1646 for (i = 0; i < n; i++)
1650 string = g_variant_get_child_value (value, i);
1651 strv[i] = g_variant_dup_string (string, NULL);
1652 g_variant_unref (string);
1663 * g_variant_new_objv:
1664 * @strv: (array length=length) (element-type utf8): an array of strings
1665 * @length: the length of @strv, or -1
1667 * Constructs an array of object paths #GVariant from the given array of
1670 * Each string must be a valid #GVariant object path; see
1671 * g_variant_is_object_path().
1673 * If @length is -1 then @strv is %NULL-terminated.
1675 * Returns: (transfer none): a new floating #GVariant instance
1680 g_variant_new_objv (const gchar * const *strv,
1686 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1689 length = g_strv_length ((gchar **) strv);
1691 strings = g_new (GVariant *, length);
1692 for (i = 0; i < length; i++)
1693 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1695 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1696 strings, length, TRUE);
1700 * g_variant_get_objv:
1701 * @value: an array of object paths #GVariant
1702 * @length: (out) (allow-none): the length of the result, or %NULL
1704 * Gets the contents of an array of object paths #GVariant. This call
1705 * makes a shallow copy; the return result should be released with
1706 * g_free(), but the individual strings must not be modified.
1708 * If @length is non-%NULL then the number of elements in the result
1709 * is stored there. In any case, the resulting array will be
1712 * For an empty array, @length will be set to 0 and a pointer to a
1713 * %NULL pointer will be returned.
1715 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1720 g_variant_get_objv (GVariant *value,
1727 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1729 g_variant_get_data (value);
1730 n = g_variant_n_children (value);
1731 strv = g_new (const gchar *, n + 1);
1733 for (i = 0; i < n; i++)
1737 string = g_variant_get_child_value (value, i);
1738 strv[i] = g_variant_get_string (string, NULL);
1739 g_variant_unref (string);
1750 * g_variant_dup_objv:
1751 * @value: an array of object paths #GVariant
1752 * @length: (out) (allow-none): the length of the result, or %NULL
1754 * Gets the contents of an array of object paths #GVariant. This call
1755 * makes a deep copy; the return result should be released with
1758 * If @length is non-%NULL then the number of elements in the result
1759 * is stored there. In any case, the resulting array will be
1762 * For an empty array, @length will be set to 0 and a pointer to a
1763 * %NULL pointer will be returned.
1765 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1770 g_variant_dup_objv (GVariant *value,
1777 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1779 n = g_variant_n_children (value);
1780 strv = g_new (gchar *, n + 1);
1782 for (i = 0; i < n; i++)
1786 string = g_variant_get_child_value (value, i);
1787 strv[i] = g_variant_dup_string (string, NULL);
1788 g_variant_unref (string);
1800 * g_variant_new_bytestring:
1801 * @string: (array zero-terminated=1) (element-type guint8): a normal
1802 * nul-terminated string in no particular encoding
1804 * Creates an array-of-bytes #GVariant with the contents of @string.
1805 * This function is just like g_variant_new_string() except that the
1806 * string need not be valid utf8.
1808 * The nul terminator character at the end of the string is stored in
1811 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1816 g_variant_new_bytestring (const gchar *string)
1818 g_return_val_if_fail (string != NULL, NULL);
1820 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1821 string, strlen (string) + 1);
1825 * g_variant_get_bytestring:
1826 * @value: an array-of-bytes #GVariant instance
1828 * Returns the string value of a #GVariant instance with an
1829 * array-of-bytes type. The string has no particular encoding.
1831 * If the array does not end with a nul terminator character, the empty
1832 * string is returned. For this reason, you can always trust that a
1833 * non-%NULL nul-terminated string will be returned by this function.
1835 * If the array contains a nul terminator character somewhere other than
1836 * the last byte then the returned string is the string, up to the first
1837 * such nul character.
1839 * It is an error to call this function with a @value that is not an
1842 * The return value remains valid as long as @value exists.
1844 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1845 * the constant string
1850 g_variant_get_bytestring (GVariant *value)
1852 const gchar *string;
1855 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1857 /* Won't be NULL since this is an array type */
1858 string = g_variant_get_data (value);
1859 size = g_variant_get_size (value);
1861 if (size && string[size - 1] == '\0')
1868 * g_variant_dup_bytestring:
1869 * @value: an array-of-bytes #GVariant instance
1870 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1871 * the length (not including the nul terminator)
1873 * Similar to g_variant_get_bytestring() except that instead of
1874 * returning a constant string, the string is duplicated.
1876 * The return value must be freed using g_free().
1878 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1879 * a newly allocated string
1884 g_variant_dup_bytestring (GVariant *value,
1887 const gchar *original = g_variant_get_bytestring (value);
1890 /* don't crash in case get_bytestring() had an assert failure */
1891 if (original == NULL)
1894 size = strlen (original);
1899 return g_memdup (original, size + 1);
1903 * g_variant_new_bytestring_array:
1904 * @strv: (array length=length): an array of strings
1905 * @length: the length of @strv, or -1
1907 * Constructs an array of bytestring #GVariant from the given array of
1910 * If @length is -1 then @strv is %NULL-terminated.
1912 * Returns: (transfer none): a new floating #GVariant instance
1917 g_variant_new_bytestring_array (const gchar * const *strv,
1923 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1926 length = g_strv_length ((gchar **) strv);
1928 strings = g_new (GVariant *, length);
1929 for (i = 0; i < length; i++)
1930 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1932 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1933 strings, length, TRUE);
1937 * g_variant_get_bytestring_array:
1938 * @value: an array of array of bytes #GVariant ('aay')
1939 * @length: (out) (allow-none): the length of the result, or %NULL
1941 * Gets the contents of an array of array of bytes #GVariant. This call
1942 * makes a shallow copy; the return result should be released with
1943 * g_free(), but the individual strings must not be modified.
1945 * If @length is non-%NULL then the number of elements in the result is
1946 * stored there. In any case, the resulting array will be
1949 * For an empty array, @length will be set to 0 and a pointer to a
1950 * %NULL pointer will be returned.
1952 * Returns: (array length=length) (transfer container): an array of constant strings
1957 g_variant_get_bytestring_array (GVariant *value,
1964 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1966 g_variant_get_data (value);
1967 n = g_variant_n_children (value);
1968 strv = g_new (const gchar *, n + 1);
1970 for (i = 0; i < n; i++)
1974 string = g_variant_get_child_value (value, i);
1975 strv[i] = g_variant_get_bytestring (string);
1976 g_variant_unref (string);
1987 * g_variant_dup_bytestring_array:
1988 * @value: an array of array of bytes #GVariant ('aay')
1989 * @length: (out) (allow-none): the length of the result, or %NULL
1991 * Gets the contents of an array of array of bytes #GVariant. This call
1992 * makes a deep copy; the return result should be released with
1995 * If @length is non-%NULL then the number of elements in the result is
1996 * stored there. In any case, the resulting array will be
1999 * For an empty array, @length will be set to 0 and a pointer to a
2000 * %NULL pointer will be returned.
2002 * Returns: (array length=length) (transfer full): an array of strings
2007 g_variant_dup_bytestring_array (GVariant *value,
2014 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2016 g_variant_get_data (value);
2017 n = g_variant_n_children (value);
2018 strv = g_new (gchar *, n + 1);
2020 for (i = 0; i < n; i++)
2024 string = g_variant_get_child_value (value, i);
2025 strv[i] = g_variant_dup_bytestring (string, NULL);
2026 g_variant_unref (string);
2036 /* Type checking and querying {{{1 */
2038 * g_variant_get_type:
2039 * @value: a #GVariant
2041 * Determines the type of @value.
2043 * The return value is valid for the lifetime of @value and must not
2046 * Returns: a #GVariantType
2050 const GVariantType *
2051 g_variant_get_type (GVariant *value)
2053 GVariantTypeInfo *type_info;
2055 g_return_val_if_fail (value != NULL, NULL);
2057 type_info = g_variant_get_type_info (value);
2059 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2063 * g_variant_get_type_string:
2064 * @value: a #GVariant
2066 * Returns the type string of @value. Unlike the result of calling
2067 * g_variant_type_peek_string(), this string is nul-terminated. This
2068 * string belongs to #GVariant and must not be freed.
2070 * Returns: the type string for the type of @value
2075 g_variant_get_type_string (GVariant *value)
2077 GVariantTypeInfo *type_info;
2079 g_return_val_if_fail (value != NULL, NULL);
2081 type_info = g_variant_get_type_info (value);
2083 return g_variant_type_info_get_type_string (type_info);
2087 * g_variant_is_of_type:
2088 * @value: a #GVariant instance
2089 * @type: a #GVariantType
2091 * Checks if a value has a type matching the provided type.
2093 * Returns: %TRUE if the type of @value matches @type
2098 g_variant_is_of_type (GVariant *value,
2099 const GVariantType *type)
2101 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2105 * g_variant_is_container:
2106 * @value: a #GVariant instance
2108 * Checks if @value is a container.
2110 * Returns: %TRUE if @value is a container
2115 g_variant_is_container (GVariant *value)
2117 return g_variant_type_is_container (g_variant_get_type (value));
2122 * g_variant_classify:
2123 * @value: a #GVariant
2125 * Classifies @value according to its top-level type.
2127 * Returns: the #GVariantClass of @value
2133 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2134 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2135 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2136 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2137 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2138 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2139 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2140 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2141 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2142 * @G_VARIANT_CLASS_FLOAT: The #GVariant is a single precision floating
2144 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2146 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2147 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2149 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2150 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2151 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2152 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2153 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2154 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2156 * The range of possible top-level types of #GVariant instances.
2161 g_variant_classify (GVariant *value)
2163 g_return_val_if_fail (value != NULL, 0);
2165 return *g_variant_get_type_string (value);
2168 /* Pretty printer {{{1 */
2169 /* This function is not introspectable because if @string is NULL,
2170 @returns is (transfer full), otherwise it is (transfer none), which
2171 is not supported by GObjectIntrospection */
2173 * g_variant_print_string: (skip)
2174 * @value: a #GVariant
2175 * @string: (allow-none) (default NULL): a #GString, or %NULL
2176 * @type_annotate: %TRUE if type information should be included in
2179 * Behaves as g_variant_print(), but operates on a #GString.
2181 * If @string is non-%NULL then it is appended to and returned. Else,
2182 * a new empty #GString is allocated and it is returned.
2184 * Returns: a #GString containing the string
2189 g_variant_print_string (GVariant *value,
2191 gboolean type_annotate)
2193 if G_UNLIKELY (string == NULL)
2194 string = g_string_new (NULL);
2196 switch (g_variant_classify (value))
2198 case G_VARIANT_CLASS_MAYBE:
2200 g_string_append_printf (string, "@%s ",
2201 g_variant_get_type_string (value));
2203 if (g_variant_n_children (value))
2205 gchar *printed_child;
2210 * Consider the case of the type "mmi". In this case we could
2211 * write "just just 4", but "4" alone is totally unambiguous,
2212 * so we try to drop "just" where possible.
2214 * We have to be careful not to always drop "just", though,
2215 * since "nothing" needs to be distinguishable from "just
2216 * nothing". The case where we need to ensure we keep the
2217 * "just" is actually exactly the case where we have a nested
2220 * Instead of searching for that nested Nothing, we just print
2221 * the contained value into a separate string and see if we
2222 * end up with "nothing" at the end of it. If so, we need to
2223 * add "just" at our level.
2225 element = g_variant_get_child_value (value, 0);
2226 printed_child = g_variant_print (element, FALSE);
2227 g_variant_unref (element);
2229 if (g_str_has_suffix (printed_child, "nothing"))
2230 g_string_append (string, "just ");
2231 g_string_append (string, printed_child);
2232 g_free (printed_child);
2235 g_string_append (string, "nothing");
2239 case G_VARIANT_CLASS_ARRAY:
2240 /* it's an array so the first character of the type string is 'a'
2242 * if the first two characters are 'ay' then it's a bytestring.
2243 * under certain conditions we print those as strings.
2245 if (g_variant_get_type_string (value)[1] == 'y')
2251 /* first determine if it is a byte string.
2252 * that's when there's a single nul character: at the end.
2254 str = g_variant_get_data (value);
2255 size = g_variant_get_size (value);
2257 for (i = 0; i < size; i++)
2261 /* first nul byte is the last byte -> it's a byte string. */
2264 gchar *escaped = g_strescape (str, NULL);
2266 /* use double quotes only if a ' is in the string */
2267 if (strchr (str, '\''))
2268 g_string_append_printf (string, "b\"%s\"", escaped);
2270 g_string_append_printf (string, "b'%s'", escaped);
2277 /* fall through and handle normally... */;
2281 * if the first two characters are 'a{' then it's an array of
2282 * dictionary entries (ie: a dictionary) so we print that
2285 if (g_variant_get_type_string (value)[1] == '{')
2288 const gchar *comma = "";
2291 if ((n = g_variant_n_children (value)) == 0)
2294 g_string_append_printf (string, "@%s ",
2295 g_variant_get_type_string (value));
2296 g_string_append (string, "{}");
2300 g_string_append_c (string, '{');
2301 for (i = 0; i < n; i++)
2303 GVariant *entry, *key, *val;
2305 g_string_append (string, comma);
2308 entry = g_variant_get_child_value (value, i);
2309 key = g_variant_get_child_value (entry, 0);
2310 val = g_variant_get_child_value (entry, 1);
2311 g_variant_unref (entry);
2313 g_variant_print_string (key, string, type_annotate);
2314 g_variant_unref (key);
2315 g_string_append (string, ": ");
2316 g_variant_print_string (val, string, type_annotate);
2317 g_variant_unref (val);
2318 type_annotate = FALSE;
2320 g_string_append_c (string, '}');
2323 /* normal (non-dictionary) array */
2325 const gchar *comma = "";
2328 if ((n = g_variant_n_children (value)) == 0)
2331 g_string_append_printf (string, "@%s ",
2332 g_variant_get_type_string (value));
2333 g_string_append (string, "[]");
2337 g_string_append_c (string, '[');
2338 for (i = 0; i < n; i++)
2342 g_string_append (string, comma);
2345 element = g_variant_get_child_value (value, i);
2347 g_variant_print_string (element, string, type_annotate);
2348 g_variant_unref (element);
2349 type_annotate = FALSE;
2351 g_string_append_c (string, ']');
2356 case G_VARIANT_CLASS_TUPLE:
2360 n = g_variant_n_children (value);
2362 g_string_append_c (string, '(');
2363 for (i = 0; i < n; i++)
2367 element = g_variant_get_child_value (value, i);
2368 g_variant_print_string (element, string, type_annotate);
2369 g_string_append (string, ", ");
2370 g_variant_unref (element);
2373 /* for >1 item: remove final ", "
2374 * for 1 item: remove final " ", but leave the ","
2375 * for 0 items: there is only "(", so remove nothing
2377 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2378 g_string_append_c (string, ')');
2382 case G_VARIANT_CLASS_DICT_ENTRY:
2386 g_string_append_c (string, '{');
2388 element = g_variant_get_child_value (value, 0);
2389 g_variant_print_string (element, string, type_annotate);
2390 g_variant_unref (element);
2392 g_string_append (string, ", ");
2394 element = g_variant_get_child_value (value, 1);
2395 g_variant_print_string (element, string, type_annotate);
2396 g_variant_unref (element);
2398 g_string_append_c (string, '}');
2402 case G_VARIANT_CLASS_VARIANT:
2404 GVariant *child = g_variant_get_variant (value);
2406 /* Always annotate types in nested variants, because they are
2407 * (by nature) of variable type.
2409 g_string_append_c (string, '<');
2410 g_variant_print_string (child, string, TRUE);
2411 g_string_append_c (string, '>');
2413 g_variant_unref (child);
2417 case G_VARIANT_CLASS_BOOLEAN:
2418 if (g_variant_get_boolean (value))
2419 g_string_append (string, "true");
2421 g_string_append (string, "false");
2424 case G_VARIANT_CLASS_STRING:
2426 const gchar *str = g_variant_get_string (value, NULL);
2427 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2429 g_string_append_c (string, quote);
2433 gunichar c = g_utf8_get_char (str);
2435 if (c == quote || c == '\\')
2436 g_string_append_c (string, '\\');
2438 if (g_unichar_isprint (c))
2439 g_string_append_unichar (string, c);
2443 g_string_append_c (string, '\\');
2448 g_string_append_c (string, 'a');
2452 g_string_append_c (string, 'b');
2456 g_string_append_c (string, 'f');
2460 g_string_append_c (string, 'n');
2464 g_string_append_c (string, 'r');
2468 g_string_append_c (string, 't');
2472 g_string_append_c (string, 'v');
2476 g_string_append_printf (string, "u%04x", c);
2480 g_string_append_printf (string, "U%08x", c);
2483 str = g_utf8_next_char (str);
2486 g_string_append_c (string, quote);
2490 case G_VARIANT_CLASS_BYTE:
2492 g_string_append (string, "byte ");
2493 g_string_append_printf (string, "0x%02x",
2494 g_variant_get_byte (value));
2497 case G_VARIANT_CLASS_INT16:
2499 g_string_append (string, "int16 ");
2500 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2501 g_variant_get_int16 (value));
2504 case G_VARIANT_CLASS_UINT16:
2506 g_string_append (string, "uint16 ");
2507 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2508 g_variant_get_uint16 (value));
2511 case G_VARIANT_CLASS_INT32:
2512 /* Never annotate this type because it is the default for numbers
2513 * (and this is a *pretty* printer)
2515 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2516 g_variant_get_int32 (value));
2519 case G_VARIANT_CLASS_HANDLE:
2521 g_string_append (string, "handle ");
2522 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2523 g_variant_get_handle (value));
2526 case G_VARIANT_CLASS_UINT32:
2528 g_string_append (string, "uint32 ");
2529 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2530 g_variant_get_uint32 (value));
2533 case G_VARIANT_CLASS_INT64:
2535 g_string_append (string, "int64 ");
2536 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2537 g_variant_get_int64 (value));
2540 case G_VARIANT_CLASS_UINT64:
2542 g_string_append (string, "uint64 ");
2543 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2544 g_variant_get_uint64 (value));
2547 case G_VARIANT_CLASS_FLOAT:
2552 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_float (value));
2554 for (i = 0; buffer[i]; i++)
2555 if (buffer[i] == '.' || buffer[i] == 'e' ||
2556 buffer[i] == 'n' || buffer[i] == 'N')
2559 /* if there is no '.' or 'e' in the float then add one */
2560 if (buffer[i] == '\0')
2568 g_string_append (string, "float ");
2569 g_string_append (string, buffer);
2573 case G_VARIANT_CLASS_DOUBLE:
2578 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2580 for (i = 0; buffer[i]; i++)
2581 if (buffer[i] == '.' || buffer[i] == 'e' ||
2582 buffer[i] == 'n' || buffer[i] == 'N')
2585 /* if there is no '.' or 'e' in the float then add one */
2586 if (buffer[i] == '\0')
2593 g_string_append (string, buffer);
2597 case G_VARIANT_CLASS_OBJECT_PATH:
2599 g_string_append (string, "objectpath ");
2600 g_string_append_printf (string, "\'%s\'",
2601 g_variant_get_string (value, NULL));
2604 case G_VARIANT_CLASS_SIGNATURE:
2606 g_string_append (string, "signature ");
2607 g_string_append_printf (string, "\'%s\'",
2608 g_variant_get_string (value, NULL));
2612 g_assert_not_reached ();
2620 * @value: a #GVariant
2621 * @type_annotate: %TRUE if type information should be included in
2624 * Pretty-prints @value in the format understood by g_variant_parse().
2626 * The format is described [here][gvariant-text].
2628 * If @type_annotate is %TRUE, then type information is included in
2631 * Returns: (transfer full): a newly-allocated string holding the result.
2636 g_variant_print (GVariant *value,
2637 gboolean type_annotate)
2639 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2643 /* Hash, Equal, Compare {{{1 */
2646 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2648 * Generates a hash value for a #GVariant instance.
2650 * The output of this function is guaranteed to be the same for a given
2651 * value only per-process. It may change between different processor
2652 * architectures or even different versions of GLib. Do not use this
2653 * function as a basis for building protocols or file formats.
2655 * The type of @value is #gconstpointer only to allow use of this
2656 * function with #GHashTable. @value must be a #GVariant.
2658 * Returns: a hash value corresponding to @value
2663 g_variant_hash (gconstpointer value_)
2665 GVariant *value = (GVariant *) value_;
2667 switch (g_variant_classify (value))
2669 case G_VARIANT_CLASS_STRING:
2670 case G_VARIANT_CLASS_OBJECT_PATH:
2671 case G_VARIANT_CLASS_SIGNATURE:
2672 return g_str_hash (g_variant_get_string (value, NULL));
2674 case G_VARIANT_CLASS_BOOLEAN:
2675 /* this is a very odd thing to hash... */
2676 return g_variant_get_boolean (value);
2678 case G_VARIANT_CLASS_BYTE:
2679 return g_variant_get_byte (value);
2681 case G_VARIANT_CLASS_INT16:
2682 case G_VARIANT_CLASS_UINT16:
2686 ptr = g_variant_get_data (value);
2694 case G_VARIANT_CLASS_INT32:
2695 case G_VARIANT_CLASS_UINT32:
2696 case G_VARIANT_CLASS_HANDLE:
2697 case G_VARIANT_CLASS_FLOAT:
2701 ptr = g_variant_get_data (value);
2709 case G_VARIANT_CLASS_INT64:
2710 case G_VARIANT_CLASS_UINT64:
2711 case G_VARIANT_CLASS_DOUBLE:
2712 /* need a separate case for these guys because otherwise
2713 * performance could be quite bad on big endian systems
2718 ptr = g_variant_get_data (value);
2721 return ptr[0] + ptr[1];
2727 g_return_val_if_fail (!g_variant_is_container (value), 0);
2728 g_assert_not_reached ();
2734 * @one: (type GVariant): a #GVariant instance
2735 * @two: (type GVariant): a #GVariant instance
2737 * Checks if @one and @two have the same type and value.
2739 * The types of @one and @two are #gconstpointer only to allow use of
2740 * this function with #GHashTable. They must each be a #GVariant.
2742 * Returns: %TRUE if @one and @two are equal
2747 g_variant_equal (gconstpointer one,
2752 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2754 if (g_variant_get_type_info ((GVariant *) one) !=
2755 g_variant_get_type_info ((GVariant *) two))
2758 /* if both values are trusted to be in their canonical serialised form
2759 * then a simple memcmp() of their serialised data will answer the
2762 * if not, then this might generate a false negative (since it is
2763 * possible for two different byte sequences to represent the same
2764 * value). for now we solve this by pretty-printing both values and
2765 * comparing the result.
2767 if (g_variant_is_trusted ((GVariant *) one) &&
2768 g_variant_is_trusted ((GVariant *) two))
2770 gconstpointer data_one, data_two;
2771 gsize size_one, size_two;
2773 size_one = g_variant_get_size ((GVariant *) one);
2774 size_two = g_variant_get_size ((GVariant *) two);
2776 if (size_one != size_two)
2779 data_one = g_variant_get_data ((GVariant *) one);
2780 data_two = g_variant_get_data ((GVariant *) two);
2782 equal = memcmp (data_one, data_two, size_one) == 0;
2786 gchar *strone, *strtwo;
2788 strone = g_variant_print ((GVariant *) one, FALSE);
2789 strtwo = g_variant_print ((GVariant *) two, FALSE);
2790 equal = strcmp (strone, strtwo) == 0;
2799 * g_variant_compare:
2800 * @one: (type GVariant): a basic-typed #GVariant instance
2801 * @two: (type GVariant): a #GVariant instance of the same type
2803 * Compares @one and @two.
2805 * The types of @one and @two are #gconstpointer only to allow use of
2806 * this function with #GTree, #GPtrArray, etc. They must each be a
2809 * Comparison is only defined for basic types (ie: booleans, numbers,
2810 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2811 * ordered in the usual way. Strings are in ASCII lexographical order.
2813 * It is a programmer error to attempt to compare container values or
2814 * two values that have types that are not exactly equal. For example,
2815 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2816 * integer. Also note that this function is not particularly
2817 * well-behaved when it comes to comparison of floats; in particular,
2818 * the handling of incomparable values (ie: NaN) is undefined.
2820 * If you only require an equality comparison, g_variant_equal() is more
2823 * Returns: negative value if a < b;
2825 * positive value if a > b.
2830 g_variant_compare (gconstpointer one,
2833 GVariant *a = (GVariant *) one;
2834 GVariant *b = (GVariant *) two;
2836 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2838 switch (g_variant_classify (a))
2840 case G_VARIANT_CLASS_BOOLEAN:
2841 return g_variant_get_boolean (a) -
2842 g_variant_get_boolean (b);
2844 case G_VARIANT_CLASS_BYTE:
2845 return ((gint) g_variant_get_byte (a)) -
2846 ((gint) g_variant_get_byte (b));
2848 case G_VARIANT_CLASS_INT16:
2849 return ((gint) g_variant_get_int16 (a)) -
2850 ((gint) g_variant_get_int16 (b));
2852 case G_VARIANT_CLASS_UINT16:
2853 return ((gint) g_variant_get_uint16 (a)) -
2854 ((gint) g_variant_get_uint16 (b));
2856 case G_VARIANT_CLASS_INT32:
2858 gint32 a_val = g_variant_get_int32 (a);
2859 gint32 b_val = g_variant_get_int32 (b);
2861 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2864 case G_VARIANT_CLASS_UINT32:
2866 guint32 a_val = g_variant_get_uint32 (a);
2867 guint32 b_val = g_variant_get_uint32 (b);
2869 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2872 case G_VARIANT_CLASS_INT64:
2874 gint64 a_val = g_variant_get_int64 (a);
2875 gint64 b_val = g_variant_get_int64 (b);
2877 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2880 case G_VARIANT_CLASS_UINT64:
2882 guint64 a_val = g_variant_get_uint64 (a);
2883 guint64 b_val = g_variant_get_uint64 (b);
2885 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2888 case G_VARIANT_CLASS_FLOAT:
2890 gfloat a_val = g_variant_get_float (a);
2891 gfloat b_val = g_variant_get_float (b);
2893 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2896 case G_VARIANT_CLASS_DOUBLE:
2898 gdouble a_val = g_variant_get_double (a);
2899 gdouble b_val = g_variant_get_double (b);
2901 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2904 case G_VARIANT_CLASS_STRING:
2905 case G_VARIANT_CLASS_OBJECT_PATH:
2906 case G_VARIANT_CLASS_SIGNATURE:
2907 return strcmp (g_variant_get_string (a, NULL),
2908 g_variant_get_string (b, NULL));
2911 g_return_val_if_fail (!g_variant_is_container (a), 0);
2912 g_assert_not_reached ();
2916 /* GVariantIter {{{1 */
2918 * GVariantIter: (skip)
2920 * #GVariantIter is an opaque data structure and can only be accessed
2921 * using the following functions.
2928 const gchar *loop_format;
2934 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2938 struct stack_iter iter;
2940 GVariant *value_ref;
2944 #define GVSI(i) ((struct stack_iter *) (i))
2945 #define GVHI(i) ((struct heap_iter *) (i))
2946 #define GVSI_MAGIC ((gsize) 3579507750u)
2947 #define GVHI_MAGIC ((gsize) 1450270775u)
2948 #define is_valid_iter(i) (i != NULL && \
2949 GVSI(i)->magic == GVSI_MAGIC)
2950 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2954 * g_variant_iter_new:
2955 * @value: a container #GVariant
2957 * Creates a heap-allocated #GVariantIter for iterating over the items
2960 * Use g_variant_iter_free() to free the return value when you no longer
2963 * A reference is taken to @value and will be released only when
2964 * g_variant_iter_free() is called.
2966 * Returns: (transfer full): a new heap-allocated #GVariantIter
2971 g_variant_iter_new (GVariant *value)
2975 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2976 GVHI(iter)->value_ref = g_variant_ref (value);
2977 GVHI(iter)->magic = GVHI_MAGIC;
2979 g_variant_iter_init (iter, value);
2985 * g_variant_iter_init: (skip)
2986 * @iter: a pointer to a #GVariantIter
2987 * @value: a container #GVariant
2989 * Initialises (without allocating) a #GVariantIter. @iter may be
2990 * completely uninitialised prior to this call; its old value is
2993 * The iterator remains valid for as long as @value exists, and need not
2994 * be freed in any way.
2996 * Returns: the number of items in @value
3001 g_variant_iter_init (GVariantIter *iter,
3004 GVSI(iter)->magic = GVSI_MAGIC;
3005 GVSI(iter)->value = value;
3006 GVSI(iter)->n = g_variant_n_children (value);
3008 GVSI(iter)->loop_format = NULL;
3010 return GVSI(iter)->n;
3014 * g_variant_iter_copy:
3015 * @iter: a #GVariantIter
3017 * Creates a new heap-allocated #GVariantIter to iterate over the
3018 * container that was being iterated over by @iter. Iteration begins on
3019 * the new iterator from the current position of the old iterator but
3020 * the two copies are independent past that point.
3022 * Use g_variant_iter_free() to free the return value when you no longer
3025 * A reference is taken to the container that @iter is iterating over
3026 * and will be releated only when g_variant_iter_free() is called.
3028 * Returns: (transfer full): a new heap-allocated #GVariantIter
3033 g_variant_iter_copy (GVariantIter *iter)
3037 g_return_val_if_fail (is_valid_iter (iter), 0);
3039 copy = g_variant_iter_new (GVSI(iter)->value);
3040 GVSI(copy)->i = GVSI(iter)->i;
3046 * g_variant_iter_n_children:
3047 * @iter: a #GVariantIter
3049 * Queries the number of child items in the container that we are
3050 * iterating over. This is the total number of items -- not the number
3051 * of items remaining.
3053 * This function might be useful for preallocation of arrays.
3055 * Returns: the number of children in the container
3060 g_variant_iter_n_children (GVariantIter *iter)
3062 g_return_val_if_fail (is_valid_iter (iter), 0);
3064 return GVSI(iter)->n;
3068 * g_variant_iter_free:
3069 * @iter: (transfer full): a heap-allocated #GVariantIter
3071 * Frees a heap-allocated #GVariantIter. Only call this function on
3072 * iterators that were returned by g_variant_iter_new() or
3073 * g_variant_iter_copy().
3078 g_variant_iter_free (GVariantIter *iter)
3080 g_return_if_fail (is_valid_heap_iter (iter));
3082 g_variant_unref (GVHI(iter)->value_ref);
3083 GVHI(iter)->magic = 0;
3085 g_slice_free (struct heap_iter, GVHI(iter));
3089 * g_variant_iter_next_value:
3090 * @iter: a #GVariantIter
3092 * Gets the next item in the container. If no more items remain then
3093 * %NULL is returned.
3095 * Use g_variant_unref() to drop your reference on the return value when
3096 * you no longer need it.
3098 * Here is an example for iterating with g_variant_iter_next_value():
3099 * |[<!-- language="C" -->
3100 * // recursively iterate a container
3102 * iterate_container_recursive (GVariant *container)
3104 * GVariantIter iter;
3107 * g_variant_iter_init (&iter, container);
3108 * while ((child = g_variant_iter_next_value (&iter)))
3110 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3112 * if (g_variant_is_container (child))
3113 * iterate_container_recursive (child);
3115 * g_variant_unref (child);
3120 * Returns: (allow-none) (transfer full): a #GVariant, or %NULL
3125 g_variant_iter_next_value (GVariantIter *iter)
3127 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3129 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3131 g_critical ("g_variant_iter_next_value: must not be called again "
3132 "after NULL has already been returned.");
3138 if (GVSI(iter)->i < GVSI(iter)->n)
3139 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3144 /* GVariantBuilder {{{1 */
3148 * A utility type for constructing container-type #GVariant instances.
3150 * This is an opaque structure and may only be accessed using the
3151 * following functions.
3153 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3154 * access it from more than one thread.
3157 struct stack_builder
3159 GVariantBuilder *parent;
3162 /* type constraint explicitly specified by 'type'.
3163 * for tuple types, this moves along as we add more items.
3165 const GVariantType *expected_type;
3167 /* type constraint implied by previous array item.
3169 const GVariantType *prev_item_type;
3171 /* constraints on the number of children. max = -1 for unlimited. */
3175 /* dynamically-growing pointer array */
3176 GVariant **children;
3177 gsize allocated_children;
3180 /* set to '1' if all items in the container will have the same type
3181 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3183 guint uniform_item_types : 1;
3185 /* set to '1' initially and changed to '0' if an untrusted value is
3193 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3197 GVariantBuilder builder;
3203 #define GVSB(b) ((struct stack_builder *) (b))
3204 #define GVHB(b) ((struct heap_builder *) (b))
3205 #define GVSB_MAGIC ((gsize) 1033660112u)
3206 #define GVHB_MAGIC ((gsize) 3087242682u)
3207 #define is_valid_builder(b) (b != NULL && \
3208 GVSB(b)->magic == GVSB_MAGIC)
3209 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3212 * g_variant_builder_new:
3213 * @type: a container type
3215 * Allocates and initialises a new #GVariantBuilder.
3217 * You should call g_variant_builder_unref() on the return value when it
3218 * is no longer needed. The memory will not be automatically freed by
3221 * In most cases it is easier to place a #GVariantBuilder directly on
3222 * the stack of the calling function and initialise it with
3223 * g_variant_builder_init().
3225 * Returns: (transfer full): a #GVariantBuilder
3230 g_variant_builder_new (const GVariantType *type)
3232 GVariantBuilder *builder;
3234 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3235 g_variant_builder_init (builder, type);
3236 GVHB(builder)->magic = GVHB_MAGIC;
3237 GVHB(builder)->ref_count = 1;
3243 * g_variant_builder_unref:
3244 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3246 * Decreases the reference count on @builder.
3248 * In the event that there are no more references, releases all memory
3249 * associated with the #GVariantBuilder.
3251 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3252 * things will happen.
3257 g_variant_builder_unref (GVariantBuilder *builder)
3259 g_return_if_fail (is_valid_heap_builder (builder));
3261 if (--GVHB(builder)->ref_count)
3264 g_variant_builder_clear (builder);
3265 GVHB(builder)->magic = 0;
3267 g_slice_free (struct heap_builder, GVHB(builder));
3271 * g_variant_builder_ref:
3272 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3274 * Increases the reference count on @builder.
3276 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3277 * things will happen.
3279 * Returns: (transfer full): a new reference to @builder
3284 g_variant_builder_ref (GVariantBuilder *builder)
3286 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3288 GVHB(builder)->ref_count++;
3294 * g_variant_builder_clear: (skip)
3295 * @builder: a #GVariantBuilder
3297 * Releases all memory associated with a #GVariantBuilder without
3298 * freeing the #GVariantBuilder structure itself.
3300 * It typically only makes sense to do this on a stack-allocated
3301 * #GVariantBuilder if you want to abort building the value part-way
3302 * through. This function need not be called if you call
3303 * g_variant_builder_end() and it also doesn't need to be called on
3304 * builders allocated with g_variant_builder_new (see
3305 * g_variant_builder_unref() for that).
3307 * This function leaves the #GVariantBuilder structure set to all-zeros.
3308 * It is valid to call this function on either an initialised
3309 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3310 * to call this function on uninitialised memory.
3315 g_variant_builder_clear (GVariantBuilder *builder)
3319 if (GVSB(builder)->magic == 0)
3320 /* all-zeros case */
3323 g_return_if_fail (is_valid_builder (builder));
3325 g_variant_type_free (GVSB(builder)->type);
3327 for (i = 0; i < GVSB(builder)->offset; i++)
3328 g_variant_unref (GVSB(builder)->children[i]);
3330 g_free (GVSB(builder)->children);
3332 if (GVSB(builder)->parent)
3334 g_variant_builder_clear (GVSB(builder)->parent);
3335 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3338 memset (builder, 0, sizeof (GVariantBuilder));
3342 * g_variant_builder_init: (skip)
3343 * @builder: a #GVariantBuilder
3344 * @type: a container type
3346 * Initialises a #GVariantBuilder structure.
3348 * @type must be non-%NULL. It specifies the type of container to
3349 * construct. It can be an indefinite type such as
3350 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3351 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3354 * After the builder is initialised, values are added using
3355 * g_variant_builder_add_value() or g_variant_builder_add().
3357 * After all the child values are added, g_variant_builder_end() frees
3358 * the memory associated with the builder and returns the #GVariant that
3361 * This function completely ignores the previous contents of @builder.
3362 * On one hand this means that it is valid to pass in completely
3363 * uninitialised memory. On the other hand, this means that if you are
3364 * initialising over top of an existing #GVariantBuilder you need to
3365 * first call g_variant_builder_clear() in order to avoid leaking
3368 * You must not call g_variant_builder_ref() or
3369 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3370 * with this function. If you ever pass a reference to a
3371 * #GVariantBuilder outside of the control of your own code then you
3372 * should assume that the person receiving that reference may try to use
3373 * reference counting; you should use g_variant_builder_new() instead of
3379 g_variant_builder_init (GVariantBuilder *builder,
3380 const GVariantType *type)
3382 g_return_if_fail (type != NULL);
3383 g_return_if_fail (g_variant_type_is_container (type));
3385 memset (builder, 0, sizeof (GVariantBuilder));
3387 GVSB(builder)->type = g_variant_type_copy (type);
3388 GVSB(builder)->magic = GVSB_MAGIC;
3389 GVSB(builder)->trusted = TRUE;
3391 switch (*(const gchar *) type)
3393 case G_VARIANT_CLASS_VARIANT:
3394 GVSB(builder)->uniform_item_types = TRUE;
3395 GVSB(builder)->allocated_children = 1;
3396 GVSB(builder)->expected_type = NULL;
3397 GVSB(builder)->min_items = 1;
3398 GVSB(builder)->max_items = 1;
3401 case G_VARIANT_CLASS_ARRAY:
3402 GVSB(builder)->uniform_item_types = TRUE;
3403 GVSB(builder)->allocated_children = 8;
3404 GVSB(builder)->expected_type =
3405 g_variant_type_element (GVSB(builder)->type);
3406 GVSB(builder)->min_items = 0;
3407 GVSB(builder)->max_items = -1;
3410 case G_VARIANT_CLASS_MAYBE:
3411 GVSB(builder)->uniform_item_types = TRUE;
3412 GVSB(builder)->allocated_children = 1;
3413 GVSB(builder)->expected_type =
3414 g_variant_type_element (GVSB(builder)->type);
3415 GVSB(builder)->min_items = 0;
3416 GVSB(builder)->max_items = 1;
3419 case G_VARIANT_CLASS_DICT_ENTRY:
3420 GVSB(builder)->uniform_item_types = FALSE;
3421 GVSB(builder)->allocated_children = 2;
3422 GVSB(builder)->expected_type =
3423 g_variant_type_key (GVSB(builder)->type);
3424 GVSB(builder)->min_items = 2;
3425 GVSB(builder)->max_items = 2;
3428 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3429 GVSB(builder)->uniform_item_types = FALSE;
3430 GVSB(builder)->allocated_children = 8;
3431 GVSB(builder)->expected_type = NULL;
3432 GVSB(builder)->min_items = 0;
3433 GVSB(builder)->max_items = -1;
3436 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3437 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3438 GVSB(builder)->expected_type =
3439 g_variant_type_first (GVSB(builder)->type);
3440 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3441 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3442 GVSB(builder)->uniform_item_types = FALSE;
3446 g_assert_not_reached ();
3449 GVSB(builder)->children = g_new (GVariant *,
3450 GVSB(builder)->allocated_children);
3454 g_variant_builder_make_room (struct stack_builder *builder)
3456 if (builder->offset == builder->allocated_children)
3458 builder->allocated_children *= 2;
3459 builder->children = g_renew (GVariant *, builder->children,
3460 builder->allocated_children);
3465 * g_variant_builder_add_value:
3466 * @builder: a #GVariantBuilder
3467 * @value: a #GVariant
3469 * Adds @value to @builder.
3471 * It is an error to call this function in any way that would create an
3472 * inconsistent value to be constructed. Some examples of this are
3473 * putting different types of items into an array, putting the wrong
3474 * types or number of items in a tuple, putting more than one value into
3477 * If @value is a floating reference (see g_variant_ref_sink()),
3478 * the @builder instance takes ownership of @value.
3483 g_variant_builder_add_value (GVariantBuilder *builder,
3486 g_return_if_fail (is_valid_builder (builder));
3487 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3488 g_return_if_fail (!GVSB(builder)->expected_type ||
3489 g_variant_is_of_type (value,
3490 GVSB(builder)->expected_type));
3491 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3492 g_variant_is_of_type (value,
3493 GVSB(builder)->prev_item_type));
3495 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3497 if (!GVSB(builder)->uniform_item_types)
3499 /* advance our expected type pointers */
3500 if (GVSB(builder)->expected_type)
3501 GVSB(builder)->expected_type =
3502 g_variant_type_next (GVSB(builder)->expected_type);
3504 if (GVSB(builder)->prev_item_type)
3505 GVSB(builder)->prev_item_type =
3506 g_variant_type_next (GVSB(builder)->prev_item_type);
3509 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3511 g_variant_builder_make_room (GVSB(builder));
3513 GVSB(builder)->children[GVSB(builder)->offset++] =
3514 g_variant_ref_sink (value);
3518 * g_variant_builder_open:
3519 * @builder: a #GVariantBuilder
3520 * @type: a #GVariantType
3522 * Opens a subcontainer inside the given @builder. When done adding
3523 * items to the subcontainer, g_variant_builder_close() must be called.
3525 * It is an error to call this function in any way that would cause an
3526 * inconsistent value to be constructed (ie: adding too many values or
3527 * a value of an incorrect type).
3532 g_variant_builder_open (GVariantBuilder *builder,
3533 const GVariantType *type)
3535 GVariantBuilder *parent;
3537 g_return_if_fail (is_valid_builder (builder));
3538 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3539 g_return_if_fail (!GVSB(builder)->expected_type ||
3540 g_variant_type_is_subtype_of (type,
3541 GVSB(builder)->expected_type));
3542 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3543 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3546 parent = g_slice_dup (GVariantBuilder, builder);
3547 g_variant_builder_init (builder, type);
3548 GVSB(builder)->parent = parent;
3550 /* push the prev_item_type down into the subcontainer */
3551 if (GVSB(parent)->prev_item_type)
3553 if (!GVSB(builder)->uniform_item_types)
3554 /* tuples and dict entries */
3555 GVSB(builder)->prev_item_type =
3556 g_variant_type_first (GVSB(parent)->prev_item_type);
3558 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3559 /* maybes and arrays */
3560 GVSB(builder)->prev_item_type =
3561 g_variant_type_element (GVSB(parent)->prev_item_type);
3566 * g_variant_builder_close:
3567 * @builder: a #GVariantBuilder
3569 * Closes the subcontainer inside the given @builder that was opened by
3570 * the most recent call to g_variant_builder_open().
3572 * It is an error to call this function in any way that would create an
3573 * inconsistent value to be constructed (ie: too few values added to the
3579 g_variant_builder_close (GVariantBuilder *builder)
3581 GVariantBuilder *parent;
3583 g_return_if_fail (is_valid_builder (builder));
3584 g_return_if_fail (GVSB(builder)->parent != NULL);
3586 parent = GVSB(builder)->parent;
3587 GVSB(builder)->parent = NULL;
3589 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3592 g_slice_free (GVariantBuilder, parent);
3596 * g_variant_make_maybe_type:
3597 * @element: a #GVariant
3599 * Return the type of a maybe containing @element.
3601 static GVariantType *
3602 g_variant_make_maybe_type (GVariant *element)
3604 return g_variant_type_new_maybe (g_variant_get_type (element));
3608 * g_variant_make_array_type:
3609 * @element: a #GVariant
3611 * Return the type of an array containing @element.
3613 static GVariantType *
3614 g_variant_make_array_type (GVariant *element)
3616 return g_variant_type_new_array (g_variant_get_type (element));
3620 * g_variant_builder_end:
3621 * @builder: a #GVariantBuilder
3623 * Ends the builder process and returns the constructed value.
3625 * It is not permissible to use @builder in any way after this call
3626 * except for reference counting operations (in the case of a
3627 * heap-allocated #GVariantBuilder) or by reinitialising it with
3628 * g_variant_builder_init() (in the case of stack-allocated).
3630 * It is an error to call this function in any way that would create an
3631 * inconsistent value to be constructed (ie: insufficient number of
3632 * items added to a container with a specific number of children
3633 * required). It is also an error to call this function if the builder
3634 * was created with an indefinite array or maybe type and no children
3635 * have been added; in this case it is impossible to infer the type of
3638 * Returns: (transfer none): a new, floating, #GVariant
3643 g_variant_builder_end (GVariantBuilder *builder)
3645 GVariantType *my_type;
3648 g_return_val_if_fail (is_valid_builder (builder), NULL);
3649 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3651 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3652 GVSB(builder)->prev_item_type != NULL ||
3653 g_variant_type_is_definite (GVSB(builder)->type),
3656 if (g_variant_type_is_definite (GVSB(builder)->type))
3657 my_type = g_variant_type_copy (GVSB(builder)->type);
3659 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3660 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3662 else if (g_variant_type_is_array (GVSB(builder)->type))
3663 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3665 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3666 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3667 GVSB(builder)->offset);
3669 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3670 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3671 GVSB(builder)->children[1]);
3673 g_assert_not_reached ();
3675 value = g_variant_new_from_children (my_type,
3676 g_renew (GVariant *,
3677 GVSB(builder)->children,
3678 GVSB(builder)->offset),
3679 GVSB(builder)->offset,
3680 GVSB(builder)->trusted);
3681 GVSB(builder)->children = NULL;
3682 GVSB(builder)->offset = 0;
3684 g_variant_builder_clear (builder);
3685 g_variant_type_free (my_type);
3690 /* GVariantDict {{{1 */
3695 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3697 * It can be used for doing a sequence of dictionary lookups in an
3698 * efficient way on an existing #GVariant dictionary or it can be used
3699 * to construct new dictionaries with a hashtable-like interface. It
3700 * can also be used for taking existing dictionaries and modifying them
3701 * in order to create new ones.
3703 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3706 * It is possible to use #GVariantDict allocated on the stack or on the
3707 * heap. When using a stack-allocated #GVariantDict, you begin with a
3708 * call to g_variant_dict_init() and free the resources with a call to
3709 * g_variant_dict_clear().
3711 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3712 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3713 * and g_variant_dict_unref().
3715 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3716 * dictionary-type #GVariant. When used with stack-allocated instances,
3717 * this also implicitly frees all associated memory, but for
3718 * heap-allocated instances, you must still call g_variant_dict_unref()
3721 * You will typically want to use a heap-allocated #GVariantDict when
3722 * you expose it as part of an API. For most other uses, the
3723 * stack-allocated form will be more convenient.
3725 * Consider the following two examples that do the same thing in each
3726 * style: take an existing dictionary and look up the "count" uint32
3727 * key, adding 1 to it if it is found, or returning an error if the
3728 * key is not found. Each returns the new dictionary as a floating
3731 * ## Using a stack-allocated GVariantDict
3733 * |[<!-- language="C" -->
3735 * add_to_count (GVariant *orig,
3738 * GVariantDict dict;
3741 * g_variant_dict_init (&dict, orig);
3742 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3744 * g_set_error (...);
3745 * g_variant_dict_clear (&dict);
3749 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3751 * return g_variant_dict_end (&dict);
3755 * ## Using heap-allocated GVariantDict
3757 * |[<!-- language="C" -->
3759 * add_to_count (GVariant *orig,
3762 * GVariantDict *dict;
3766 * dict = g_variant_dict_new (orig);
3768 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3770 * g_variant_dict_insert (dict, "count", "u", count + 1);
3771 * result = g_variant_dict_end (dict);
3775 * g_set_error (...);
3779 * g_variant_dict_unref (dict);
3793 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3797 struct stack_dict dict;
3802 #define GVSD(d) ((struct stack_dict *) (d))
3803 #define GVHD(d) ((struct heap_dict *) (d))
3804 #define GVSD_MAGIC ((gsize) 2579507750u)
3805 #define GVHD_MAGIC ((gsize) 2450270775u)
3806 #define is_valid_dict(d) (d != NULL && \
3807 GVSD(d)->magic == GVSD_MAGIC)
3808 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3811 * g_variant_dict_new:
3812 * @from_asv: (allow-none): the #GVariant with which to initialise the
3815 * Allocates and initialises a new #GVariantDict.
3817 * You should call g_variant_dict_unref() on the return value when it
3818 * is no longer needed. The memory will not be automatically freed by
3821 * In some cases it may be easier to place a #GVariantDict directly on
3822 * the stack of the calling function and initialise it with
3823 * g_variant_dict_init(). This is particularly useful when you are
3824 * using #GVariantDict to construct a #GVariant.
3826 * Returns: (transfer full): a #GVariantDict
3831 g_variant_dict_new (GVariant *from_asv)
3835 dict = g_slice_alloc (sizeof (struct heap_dict));
3836 g_variant_dict_init (dict, from_asv);
3837 GVHD(dict)->magic = GVHD_MAGIC;
3838 GVHD(dict)->ref_count = 1;
3844 * g_variant_dict_init: (skip)
3845 * @dict: a #GVariantDict
3846 * @from_asv: (allow-none): the initial value for @dict
3848 * Initialises a #GVariantDict structure.
3850 * If @from_asv is given, it is used to initialise the dictionary.
3852 * This function completely ignores the previous contents of @dict. On
3853 * one hand this means that it is valid to pass in completely
3854 * uninitialised memory. On the other hand, this means that if you are
3855 * initialising over top of an existing #GVariantDict you need to first
3856 * call g_variant_dict_clear() in order to avoid leaking memory.
3858 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3859 * #GVariantDict that was initialised with this function. If you ever
3860 * pass a reference to a #GVariantDict outside of the control of your
3861 * own code then you should assume that the person receiving that
3862 * reference may try to use reference counting; you should use
3863 * g_variant_dict_new() instead of this function.
3868 g_variant_dict_init (GVariantDict *dict,
3875 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3876 GVSD(dict)->magic = GVSD_MAGIC;
3880 g_variant_iter_init (&iter, from_asv);
3881 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3882 g_hash_table_insert (GVSD(dict)->values, key, value);
3887 * g_variant_dict_lookup:
3888 * @dict: a #GVariantDict
3889 * @key: the key to lookup in the dictionary
3890 * @format_string: a GVariant format string
3891 * @...: the arguments to unpack the value into
3893 * Looks up a value in a #GVariantDict.
3895 * This function is a wrapper around g_variant_dict_lookup_value() and
3896 * g_variant_get(). In the case that %NULL would have been returned,
3897 * this function returns %FALSE. Otherwise, it unpacks the returned
3898 * value and returns %TRUE.
3900 * @format_string determines the C types that are used for unpacking the
3901 * values and also determines if the values are copied or borrowed, see the
3902 * section on [GVariant format strings][gvariant-format-strings-pointers].
3904 * Returns: %TRUE if a value was unpacked
3909 g_variant_dict_lookup (GVariantDict *dict,
3911 const gchar *format_string,
3917 g_return_val_if_fail (is_valid_dict (dict), FALSE);
3918 g_return_val_if_fail (key != NULL, FALSE);
3919 g_return_val_if_fail (format_string != NULL, FALSE);
3921 value = g_hash_table_lookup (GVSD(dict)->values, key);
3923 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3926 va_start (ap, format_string);
3927 g_variant_get_va (value, format_string, NULL, &ap);
3934 * g_variant_dict_lookup_value:
3935 * @dict: a #GVariantDict
3936 * @key: the key to lookup in the dictionary
3937 * @expected_type: (allow-none): a #GVariantType, or %NULL
3939 * Looks up a value in a #GVariantDict.
3941 * If @key is not found in @dictionary, %NULL is returned.
3943 * The @expected_type string specifies what type of value is expected.
3944 * If the value associated with @key has a different type then %NULL is
3947 * If the key is found and the value has the correct type, it is
3948 * returned. If @expected_type was specified then any non-%NULL return
3949 * value will have this type.
3951 * Returns: (transfer full): the value of the dictionary key, or %NULL
3956 g_variant_dict_lookup_value (GVariantDict *dict,
3958 const GVariantType *expected_type)
3962 g_return_val_if_fail (is_valid_dict (dict), NULL);
3963 g_return_val_if_fail (key != NULL, NULL);
3965 result = g_hash_table_lookup (GVSD(dict)->values, key);
3967 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
3968 return g_variant_ref (result);
3974 * g_variant_dict_contains:
3975 * @dict: a #GVariantDict
3976 * @key: the key to lookup in the dictionary
3978 * Checks if @key exists in @dict.
3980 * Returns: %TRUE if @key is in @dict
3985 g_variant_dict_contains (GVariantDict *dict,
3988 g_return_val_if_fail (is_valid_dict (dict), FALSE);
3989 g_return_val_if_fail (key != NULL, FALSE);
3991 return g_hash_table_contains (GVSD(dict)->values, key);
3995 * g_variant_dict_insert:
3996 * @dict: a #GVariantDict
3997 * @key: the key to insert a value for
3998 * @format_string: a #GVariant varargs format string
3999 * @...: arguments, as per @format_string
4001 * Inserts a value into a #GVariantDict.
4003 * This call is a convenience wrapper that is exactly equivalent to
4004 * calling g_variant_new() followed by g_variant_dict_insert_value().
4009 g_variant_dict_insert (GVariantDict *dict,
4011 const gchar *format_string,
4016 g_return_if_fail (is_valid_dict (dict));
4017 g_return_if_fail (key != NULL);
4018 g_return_if_fail (format_string != NULL);
4020 va_start (ap, format_string);
4021 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4026 * g_variant_dict_insert_value:
4027 * @dict: a #GVariantDict
4028 * @key: the key to insert a value for
4029 * @value: the value to insert
4031 * Inserts (or replaces) a key in a #GVariantDict.
4033 * @value is consumed if it is floating.
4038 g_variant_dict_insert_value (GVariantDict *dict,
4042 g_return_if_fail (is_valid_dict (dict));
4043 g_return_if_fail (key != NULL);
4044 g_return_if_fail (value != NULL);
4046 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4050 * g_variant_dict_remove:
4051 * @dict: a #GVariantDict
4052 * @key: the key to remove
4054 * Removes a key and its associated value from a #GVariantDict.
4056 * Returns: %TRUE if the key was found and removed
4061 g_variant_dict_remove (GVariantDict *dict,
4064 g_return_val_if_fail (is_valid_dict (dict), FALSE);
4065 g_return_val_if_fail (key != NULL, FALSE);
4067 return g_hash_table_remove (GVSD(dict)->values, key);
4071 * g_variant_dict_clear:
4072 * @dict: a #GVariantDict
4074 * Releases all memory associated with a #GVariantDict without freeing
4075 * the #GVariantDict structure itself.
4077 * It typically only makes sense to do this on a stack-allocated
4078 * #GVariantDict if you want to abort building the value part-way
4079 * through. This function need not be called if you call
4080 * g_variant_dict_end() and it also doesn't need to be called on dicts
4081 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4084 * It is valid to call this function on either an initialised
4085 * #GVariantDict or one that was previously cleared by an earlier call
4086 * to g_variant_dict_clear() but it is not valid to call this function
4087 * on uninitialised memory.
4092 g_variant_dict_clear (GVariantDict *dict)
4094 if (GVSD(dict)->magic == 0)
4095 /* all-zeros case */
4098 g_return_if_fail (is_valid_dict (dict));
4100 g_hash_table_unref (GVSD(dict)->values);
4101 GVSD(dict)->values = NULL;
4103 GVSD(dict)->magic = 0;
4107 * g_variant_dict_end:
4108 * @dict: a #GVariantDict
4110 * Returns the current value of @dict as a #GVariant of type
4111 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4113 * It is not permissible to use @dict in any way after this call except
4114 * for reference counting operations (in the case of a heap-allocated
4115 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4116 * the case of stack-allocated).
4118 * Returns: (transfer none): a new, floating, #GVariant
4123 g_variant_dict_end (GVariantDict *dict)
4125 GVariantBuilder builder;
4126 GHashTableIter iter;
4127 gpointer key, value;
4129 g_return_val_if_fail (is_valid_dict (dict), NULL);
4131 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4133 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4134 while (g_hash_table_iter_next (&iter, &key, &value))
4135 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4137 g_variant_dict_clear (dict);
4139 return g_variant_builder_end (&builder);
4143 * g_variant_dict_ref:
4144 * @dict: a heap-allocated #GVariantDict
4146 * Increases the reference count on @dict.
4148 * Don't call this on stack-allocated #GVariantDict instances or bad
4149 * things will happen.
4151 * Returns: (transfer full): a new reference to @dict
4156 g_variant_dict_ref (GVariantDict *dict)
4158 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4160 GVHD(dict)->ref_count++;
4166 * g_variant_dict_unref:
4167 * @dict: (transfer full): a heap-allocated #GVariantDict
4169 * Decreases the reference count on @dict.
4171 * In the event that there are no more references, releases all memory
4172 * associated with the #GVariantDict.
4174 * Don't call this on stack-allocated #GVariantDict instances or bad
4175 * things will happen.
4180 g_variant_dict_unref (GVariantDict *dict)
4182 g_return_if_fail (is_valid_heap_dict (dict));
4184 if (--GVHD(dict)->ref_count == 0)
4186 g_variant_dict_clear (dict);
4187 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4192 /* Format strings {{{1 */
4194 * g_variant_format_string_scan:
4195 * @string: a string that may be prefixed with a format string
4196 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
4198 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4201 * Checks the string pointed to by @string for starting with a properly
4202 * formed #GVariant varargs format string. If no valid format string is
4203 * found then %FALSE is returned.
4205 * If @string does start with a valid format string then %TRUE is
4206 * returned. If @endptr is non-%NULL then it is updated to point to the
4207 * first character after the format string.
4209 * If @limit is non-%NULL then @limit (and any charater after it) will
4210 * not be accessed and the effect is otherwise equivalent to if the
4211 * character at @limit were nul.
4213 * See the section on [GVariant format strings][gvariant-format-strings].
4215 * Returns: %TRUE if there was a valid format string
4220 g_variant_format_string_scan (const gchar *string,
4222 const gchar **endptr)
4224 #define next_char() (string == limit ? '\0' : *string++)
4225 #define peek_char() (string == limit ? '\0' : *string)
4228 switch (next_char())
4230 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4231 case 'x': case 't': case 'h': case 'f': case 'd': case 's':
4232 case 'o': case 'g': case 'v': case '*': case '?': case 'r':
4236 return g_variant_format_string_scan (string, limit, endptr);
4240 return g_variant_type_string_scan (string, limit, endptr);
4243 while (peek_char() != ')')
4244 if (!g_variant_format_string_scan (string, limit, &string))
4247 next_char(); /* consume ')' */
4257 if (c != 's' && c != 'o' && c != 'g')
4265 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4266 * The terminating null character is considered to be
4267 * part of the string.
4269 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4273 if (!g_variant_format_string_scan (string, limit, &string))
4276 if (next_char() != '}')
4282 if ((c = next_char()) == 'a')
4284 if ((c = next_char()) == '&')
4286 if ((c = next_char()) == 'a')
4288 if ((c = next_char()) == 'y')
4289 break; /* '^a&ay' */
4292 else if (c == 's' || c == 'o')
4293 break; /* '^a&s', '^a&o' */
4298 if ((c = next_char()) == 'y')
4302 else if (c == 's' || c == 'o')
4303 break; /* '^as', '^ao' */
4310 if ((c = next_char()) == 'a')
4312 if ((c = next_char()) == 'y')
4322 if (c != 's' && c != 'o' && c != 'g')
4341 * g_variant_check_format_string:
4342 * @value: a #GVariant
4343 * @format_string: a valid #GVariant format string
4344 * @copy_only: %TRUE to ensure the format string makes deep copies
4346 * Checks if calling g_variant_get() with @format_string on @value would
4347 * be valid from a type-compatibility standpoint. @format_string is
4348 * assumed to be a valid format string (from a syntactic standpoint).
4350 * If @copy_only is %TRUE then this function additionally checks that it
4351 * would be safe to call g_variant_unref() on @value immediately after
4352 * the call to g_variant_get() without invalidating the result. This is
4353 * only possible if deep copies are made (ie: there are no pointers to
4354 * the data inside of the soon-to-be-freed #GVariant instance). If this
4355 * check fails then a g_critical() is printed and %FALSE is returned.
4357 * This function is meant to be used by functions that wish to provide
4358 * varargs accessors to #GVariant values of uncertain values (eg:
4359 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4361 * Returns: %TRUE if @format_string is safe to use
4366 g_variant_check_format_string (GVariant *value,
4367 const gchar *format_string,
4370 const gchar *original_format = format_string;
4371 const gchar *type_string;
4373 /* Interesting factoid: assuming a format string is valid, it can be
4374 * converted to a type string by removing all '@' '&' and '^'
4377 * Instead of doing that, we can just skip those characters when
4378 * comparing it to the type string of @value.
4380 * For the copy-only case we can just drop the '&' from the list of
4381 * characters to skip over. A '&' will never appear in a type string
4382 * so we know that it won't be possible to return %TRUE if it is in a
4385 type_string = g_variant_get_type_string (value);
4387 while (*type_string || *format_string)
4389 gchar format = *format_string++;
4394 if G_UNLIKELY (copy_only)
4396 /* for the love of all that is good, please don't mark this string for translation... */
4397 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4398 "interface to validate the passed format string for type safety. The passed format "
4399 "(%s) contains a '&' character which would result in a pointer being returned to the "
4400 "data inside of a GVariant instance that may no longer exist by the time the function "
4401 "returns. Modify your code to use a format string without '&'.", original_format);
4408 /* ignore these 2 (or 3) */
4412 /* attempt to consume one of 'bynqiuxthdsog' */
4414 char s = *type_string++;
4416 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4422 /* ensure it's a tuple */
4423 if (*type_string != '(')
4428 /* consume a full type string for the '*' or 'r' */
4429 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4435 /* attempt to consume exactly one character equal to the format */
4436 if (format != *type_string++)
4445 * g_variant_format_string_scan_type:
4446 * @string: a string that may be prefixed with a format string
4447 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
4449 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4452 * If @string starts with a valid format string then this function will
4453 * return the type that the format string corresponds to. Otherwise
4454 * this function returns %NULL.
4456 * Use g_variant_type_free() to free the return value when you no longer
4459 * This function is otherwise exactly like
4460 * g_variant_format_string_scan().
4462 * Returns: (allow-none): a #GVariantType if there was a valid format string
4467 g_variant_format_string_scan_type (const gchar *string,
4469 const gchar **endptr)
4471 const gchar *my_end;
4478 if (!g_variant_format_string_scan (string, limit, endptr))
4481 dest = new = g_malloc (*endptr - string + 1);
4482 while (string != *endptr)
4484 if (*string != '@' && *string != '&' && *string != '^')
4490 return (GVariantType *) G_VARIANT_TYPE (new);
4494 valid_format_string (const gchar *format_string,
4498 const gchar *endptr;
4501 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4503 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4506 g_critical ("'%s' is not a valid GVariant format string",
4509 g_critical ("'%s' does not have a valid GVariant format "
4510 "string as a prefix", format_string);
4513 g_variant_type_free (type);
4518 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4523 fragment = g_strndup (format_string, endptr - format_string);
4524 typestr = g_variant_type_dup_string (type);
4526 g_critical ("the GVariant format string '%s' has a type of "
4527 "'%s' but the given value has a type of '%s'",
4528 fragment, typestr, g_variant_get_type_string (value));
4530 g_variant_type_free (type);
4537 g_variant_type_free (type);
4542 /* Variable Arguments {{{1 */
4543 /* We consider 2 main classes of format strings:
4545 * - recursive format strings
4546 * these are ones that result in recursion and the collection of
4547 * possibly more than one argument. Maybe types, tuples,
4548 * dictionary entries.
4550 * - leaf format string
4551 * these result in the collection of a single argument.
4553 * Leaf format strings are further subdivided into two categories:
4555 * - single non-null pointer ("nnp")
4556 * these either collect or return a single non-null pointer.
4559 * these collect or return something else (bool, number, etc).
4561 * Based on the above, the varargs handling code is split into 4 main parts:
4563 * - nnp handling code
4564 * - leaf handling code (which may invoke nnp code)
4565 * - generic handling code (may be recursive, may invoke leaf code)
4566 * - user-facing API (which invokes the generic code)
4568 * Each section implements some of the following functions:
4571 * collect the arguments for the format string as if
4572 * g_variant_new() had been called, but do nothing with them. used
4573 * for skipping over arguments when constructing a Nothing maybe
4577 * create a GVariant *
4580 * unpack a GVariant *
4582 * - free (nnp only):
4583 * free a previously allocated item
4587 g_variant_format_string_is_leaf (const gchar *str)
4589 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4593 g_variant_format_string_is_nnp (const gchar *str)
4595 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4596 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4597 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4600 /* Single non-null pointer ("nnp") {{{2 */
4602 g_variant_valist_free_nnp (const gchar *str,
4608 g_variant_iter_free (ptr);
4612 if (str[2] != '&') /* '^as', '^ao' */
4614 else /* '^a&s', '^a&o' */
4628 g_variant_unref (ptr);
4635 g_assert_not_reached ();
4640 g_variant_scan_convenience (const gchar **str,
4663 g_variant_valist_new_nnp (const gchar **str,
4674 const GVariantType *type;
4677 value = g_variant_builder_end (ptr);
4678 type = g_variant_get_type (value);
4680 if G_UNLIKELY (!g_variant_type_is_array (type))
4681 g_error ("g_variant_new: expected array GVariantBuilder but "
4682 "the built value has type '%s'",
4683 g_variant_get_type_string (value));
4685 type = g_variant_type_element (type);
4687 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4688 g_error ("g_variant_new: expected GVariantBuilder array element "
4689 "type '%s' but the built value has element type '%s'",
4690 g_variant_type_dup_string ((GVariantType *) *str),
4691 g_variant_get_type_string (value) + 1);
4693 g_variant_type_string_scan (*str, NULL, str);
4699 /* special case: NULL pointer for empty array */
4701 const GVariantType *type = (GVariantType *) *str;
4703 g_variant_type_string_scan (*str, NULL, str);
4705 if G_UNLIKELY (!g_variant_type_is_definite (type))
4706 g_error ("g_variant_new: NULL pointer given with indefinite "
4707 "array type; unable to determine which type of empty "
4708 "array to construct.");
4710 return g_variant_new_array (type, NULL, 0);
4717 value = g_variant_new_string (ptr);
4720 value = g_variant_new_string ("[Invalid UTF-8]");
4726 return g_variant_new_object_path (ptr);
4729 return g_variant_new_signature (ptr);
4737 type = g_variant_scan_convenience (str, &constant, &arrays);
4740 return g_variant_new_strv (ptr, -1);
4743 return g_variant_new_objv (ptr, -1);
4746 return g_variant_new_bytestring_array (ptr, -1);
4748 return g_variant_new_bytestring (ptr);
4752 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4753 g_error ("g_variant_new: expected GVariant of type '%s' but "
4754 "received value has type '%s'",
4755 g_variant_type_dup_string ((GVariantType *) *str),
4756 g_variant_get_type_string (ptr));
4758 g_variant_type_string_scan (*str, NULL, str);
4766 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4767 g_error ("g_variant_new: format string '?' expects basic-typed "
4768 "GVariant, but received value has type '%s'",
4769 g_variant_get_type_string (ptr));
4774 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4775 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4776 "GVariant, but received value has type '%s'",
4777 g_variant_get_type_string (ptr));
4782 return g_variant_new_variant (ptr);
4785 g_assert_not_reached ();
4790 g_variant_valist_get_nnp (const gchar **str,
4796 g_variant_type_string_scan (*str, NULL, str);
4797 return g_variant_iter_new (value);
4801 return (gchar *) g_variant_get_string (value, NULL);
4806 return g_variant_dup_string (value, NULL);
4814 type = g_variant_scan_convenience (str, &constant, &arrays);
4819 return g_variant_get_strv (value, NULL);
4821 return g_variant_dup_strv (value, NULL);
4824 else if (type == 'o')
4827 return g_variant_get_objv (value, NULL);
4829 return g_variant_dup_objv (value, NULL);
4832 else if (arrays > 1)
4835 return g_variant_get_bytestring_array (value, NULL);
4837 return g_variant_dup_bytestring_array (value, NULL);
4843 return (gchar *) g_variant_get_bytestring (value);
4845 return g_variant_dup_bytestring (value, NULL);
4850 g_variant_type_string_scan (*str, NULL, str);
4856 return g_variant_ref (value);
4859 return g_variant_get_variant (value);
4862 g_assert_not_reached ();
4868 g_variant_valist_skip_leaf (const gchar **str,
4871 if (g_variant_format_string_is_nnp (*str))
4873 g_variant_format_string_scan (*str, NULL, str);
4874 va_arg (*app, gpointer);
4892 va_arg (*app, guint64);
4897 va_arg (*app, gdouble);
4901 g_assert_not_reached ();
4906 g_variant_valist_new_leaf (const gchar **str,
4909 if (g_variant_format_string_is_nnp (*str))
4910 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4915 return g_variant_new_boolean (va_arg (*app, gboolean));
4918 return g_variant_new_byte (va_arg (*app, guint));
4921 return g_variant_new_int16 (va_arg (*app, gint));
4924 return g_variant_new_uint16 (va_arg (*app, guint));
4927 return g_variant_new_int32 (va_arg (*app, gint));
4930 return g_variant_new_uint32 (va_arg (*app, guint));
4933 return g_variant_new_int64 (va_arg (*app, gint64));
4936 return g_variant_new_uint64 (va_arg (*app, guint64));
4939 return g_variant_new_handle (va_arg (*app, gint));
4942 return g_variant_new_float (va_arg (*app, gdouble));
4945 return g_variant_new_double (va_arg (*app, gdouble));
4948 g_assert_not_reached ();
4952 /* The code below assumes this */
4953 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4954 G_STATIC_ASSERT (sizeof (gfloat) == sizeof (guint32));
4955 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4958 g_variant_valist_get_leaf (const gchar **str,
4963 gpointer ptr = va_arg (*app, gpointer);
4967 g_variant_format_string_scan (*str, NULL, str);
4971 if (g_variant_format_string_is_nnp (*str))
4973 gpointer *nnp = (gpointer *) ptr;
4975 if (free && *nnp != NULL)
4976 g_variant_valist_free_nnp (*str, *nnp);
4981 *nnp = g_variant_valist_get_nnp (str, value);
4983 g_variant_format_string_scan (*str, NULL, str);
4993 *(gboolean *) ptr = g_variant_get_boolean (value);
4997 *(guchar *) ptr = g_variant_get_byte (value);
5001 *(gint16 *) ptr = g_variant_get_int16 (value);
5005 *(guint16 *) ptr = g_variant_get_uint16 (value);
5009 *(gint32 *) ptr = g_variant_get_int32 (value);
5013 *(guint32 *) ptr = g_variant_get_uint32 (value);
5017 *(gint64 *) ptr = g_variant_get_int64 (value);
5021 *(guint64 *) ptr = g_variant_get_uint64 (value);
5025 *(gint32 *) ptr = g_variant_get_handle (value);
5029 *(gfloat *) ptr = g_variant_get_float (value);
5033 *(gdouble *) ptr = g_variant_get_double (value);
5042 *(guchar *) ptr = 0;
5047 *(guint16 *) ptr = 0;
5055 *(guint32 *) ptr = 0;
5061 *(guint64 *) ptr = 0;
5066 g_assert_not_reached ();
5069 /* Generic (recursive) {{{2 */
5071 g_variant_valist_skip (const gchar **str,
5074 if (g_variant_format_string_is_leaf (*str))
5075 g_variant_valist_skip_leaf (str, app);
5077 else if (**str == 'm') /* maybe */
5081 if (!g_variant_format_string_is_nnp (*str))
5082 va_arg (*app, gboolean);
5084 g_variant_valist_skip (str, app);
5086 else /* tuple, dictionary entry */
5088 g_assert (**str == '(' || **str == '{');
5090 while (**str != ')' && **str != '}')
5091 g_variant_valist_skip (str, app);
5097 g_variant_valist_new (const gchar **str,
5100 if (g_variant_format_string_is_leaf (*str))
5101 return g_variant_valist_new_leaf (str, app);
5103 if (**str == 'm') /* maybe */
5105 GVariantType *type = NULL;
5106 GVariant *value = NULL;
5110 if (g_variant_format_string_is_nnp (*str))
5112 gpointer nnp = va_arg (*app, gpointer);
5115 value = g_variant_valist_new_nnp (str, nnp);
5117 type = g_variant_format_string_scan_type (*str, NULL, str);
5121 gboolean just = va_arg (*app, gboolean);
5124 value = g_variant_valist_new (str, app);
5127 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5128 g_variant_valist_skip (str, app);
5132 value = g_variant_new_maybe (type, value);
5135 g_variant_type_free (type);
5139 else /* tuple, dictionary entry */
5144 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5147 g_assert (**str == '{');
5148 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5152 while (**str != ')' && **str != '}')
5153 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5156 return g_variant_builder_end (&b);
5161 g_variant_valist_get (const gchar **str,
5166 if (g_variant_format_string_is_leaf (*str))
5167 g_variant_valist_get_leaf (str, value, free, app);
5169 else if (**str == 'm')
5174 value = g_variant_get_maybe (value);
5176 if (!g_variant_format_string_is_nnp (*str))
5178 gboolean *ptr = va_arg (*app, gboolean *);
5181 *ptr = value != NULL;
5184 g_variant_valist_get (str, value, free, app);
5187 g_variant_unref (value);
5190 else /* tuple, dictionary entry */
5194 g_assert (**str == '(' || **str == '{');
5197 while (**str != ')' && **str != '}')
5201 GVariant *child = g_variant_get_child_value (value, index++);
5202 g_variant_valist_get (str, child, free, app);
5203 g_variant_unref (child);
5206 g_variant_valist_get (str, NULL, free, app);
5212 /* User-facing API {{{2 */
5214 * g_variant_new: (skip)
5215 * @format_string: a #GVariant format string
5216 * @...: arguments, as per @format_string
5218 * Creates a new #GVariant instance.
5220 * Think of this function as an analogue to g_strdup_printf().
5222 * The type of the created instance and the arguments that are expected
5223 * by this function are determined by @format_string. See the section on
5224 * [GVariant format strings][gvariant-format-strings]. Please note that
5225 * the syntax of the format string is very likely to be extended in the
5228 * The first character of the format string must not be '*' '?' '@' or
5229 * 'r'; in essence, a new #GVariant must always be constructed by this
5230 * function (and not merely passed through it unmodified).
5232 * Note that the arguments must be of the correct width for their types
5233 * specified in @format_string. This can be achieved by casting them. See
5234 * the [GVariant varargs documentation][gvariant-varargs].
5236 * |[<!-- language="C" -->
5237 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5238 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5239 * GVariant *new_variant;
5241 * new_variant = g_variant_new ("(t^as)",
5242 * /<!-- -->* This cast is required. *<!-- -->/
5243 * (guint64) some_flags,
5247 * Returns: a new floating #GVariant instance
5252 g_variant_new (const gchar *format_string,
5258 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5259 format_string[0] != '?' && format_string[0] != '@' &&
5260 format_string[0] != '*' && format_string[0] != 'r',
5263 va_start (ap, format_string);
5264 value = g_variant_new_va (format_string, NULL, &ap);
5271 * g_variant_new_va: (skip)
5272 * @format_string: a string that is prefixed with a format string
5273 * @endptr: (allow-none) (default NULL): location to store the end pointer,
5275 * @app: a pointer to a #va_list
5277 * This function is intended to be used by libraries based on
5278 * #GVariant that want to provide g_variant_new()-like functionality
5281 * The API is more general than g_variant_new() to allow a wider range
5284 * @format_string must still point to a valid format string, but it only
5285 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5286 * non-%NULL then it is updated to point to the first character past the
5287 * end of the format string.
5289 * @app is a pointer to a #va_list. The arguments, according to
5290 * @format_string, are collected from this #va_list and the list is left
5291 * pointing to the argument following the last.
5293 * Note that the arguments in @app must be of the correct width for their
5294 * types specified in @format_string when collected into the #va_list.
5295 * See the [GVariant varargs documentation][gvariant-varargs.
5297 * These two generalisations allow mixing of multiple calls to
5298 * g_variant_new_va() and g_variant_get_va() within a single actual
5299 * varargs call by the user.
5301 * The return value will be floating if it was a newly created GVariant
5302 * instance (for example, if the format string was "(ii)"). In the case
5303 * that the format_string was '*', '?', 'r', or a format starting with
5304 * '@' then the collected #GVariant pointer will be returned unmodified,
5305 * without adding any additional references.
5307 * In order to behave correctly in all cases it is necessary for the
5308 * calling function to g_variant_ref_sink() the return result before
5309 * returning control to the user that originally provided the pointer.
5310 * At this point, the caller will have their own full reference to the
5311 * result. This can also be done by adding the result to a container,
5312 * or by passing it to another g_variant_new() call.
5314 * Returns: a new, usually floating, #GVariant
5319 g_variant_new_va (const gchar *format_string,
5320 const gchar **endptr,
5325 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5327 g_return_val_if_fail (app != NULL, NULL);
5329 value = g_variant_valist_new (&format_string, app);
5332 *endptr = format_string;
5338 * g_variant_get: (skip)
5339 * @value: a #GVariant instance
5340 * @format_string: a #GVariant format string
5341 * @...: arguments, as per @format_string
5343 * Deconstructs a #GVariant instance.
5345 * Think of this function as an analogue to scanf().
5347 * The arguments that are expected by this function are entirely
5348 * determined by @format_string. @format_string also restricts the
5349 * permissible types of @value. It is an error to give a value with
5350 * an incompatible type. See the section on
5351 * [GVariant format strings][gvariant-format-strings].
5352 * Please note that the syntax of the format string is very likely to be
5353 * extended in the future.
5355 * @format_string determines the C types that are used for unpacking
5356 * the values and also determines if the values are copied or borrowed,
5357 * see the section on
5358 * [GVariant format strings][gvariant-format-strings-pointers].
5363 g_variant_get (GVariant *value,
5364 const gchar *format_string,
5369 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5371 /* if any direct-pointer-access formats are in use, flatten first */
5372 if (strchr (format_string, '&'))
5373 g_variant_get_data (value);
5375 va_start (ap, format_string);
5376 g_variant_get_va (value, format_string, NULL, &ap);
5381 * g_variant_get_va: (skip)
5382 * @value: a #GVariant
5383 * @format_string: a string that is prefixed with a format string
5384 * @endptr: (allow-none) (default NULL): location to store the end pointer,
5386 * @app: a pointer to a #va_list
5388 * This function is intended to be used by libraries based on #GVariant
5389 * that want to provide g_variant_get()-like functionality to their
5392 * The API is more general than g_variant_get() to allow a wider range
5395 * @format_string must still point to a valid format string, but it only
5396 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5397 * non-%NULL then it is updated to point to the first character past the
5398 * end of the format string.
5400 * @app is a pointer to a #va_list. The arguments, according to
5401 * @format_string, are collected from this #va_list and the list is left
5402 * pointing to the argument following the last.
5404 * These two generalisations allow mixing of multiple calls to
5405 * g_variant_new_va() and g_variant_get_va() within a single actual
5406 * varargs call by the user.
5408 * @format_string determines the C types that are used for unpacking
5409 * the values and also determines if the values are copied or borrowed,
5410 * see the section on
5411 * [GVariant format strings][gvariant-format-strings-pointers].
5416 g_variant_get_va (GVariant *value,
5417 const gchar *format_string,
5418 const gchar **endptr,
5421 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5422 g_return_if_fail (value != NULL);
5423 g_return_if_fail (app != NULL);
5425 /* if any direct-pointer-access formats are in use, flatten first */
5426 if (strchr (format_string, '&'))
5427 g_variant_get_data (value);
5429 g_variant_valist_get (&format_string, value, FALSE, app);
5432 *endptr = format_string;
5435 /* Varargs-enabled Utility Functions {{{1 */
5438 * g_variant_builder_add: (skip)
5439 * @builder: a #GVariantBuilder
5440 * @format_string: a #GVariant varargs format string
5441 * @...: arguments, as per @format_string
5443 * Adds to a #GVariantBuilder.
5445 * This call is a convenience wrapper that is exactly equivalent to
5446 * calling g_variant_new() followed by g_variant_builder_add_value().
5448 * Note that the arguments must be of the correct width for their types
5449 * specified in @format_string. This can be achieved by casting them. See
5450 * the [GVariant varargs documentation][gvariant-varargs].
5452 * This function might be used as follows:
5454 * |[<!-- language="C" -->
5456 * make_pointless_dictionary (void)
5458 * GVariantBuilder builder;
5461 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5462 * for (i = 0; i < 16; i++)
5466 * sprintf (buf, "%d", i);
5467 * g_variant_builder_add (&builder, "{is}", i, buf);
5470 * return g_variant_builder_end (&builder);
5477 g_variant_builder_add (GVariantBuilder *builder,
5478 const gchar *format_string,
5484 va_start (ap, format_string);
5485 variant = g_variant_new_va (format_string, NULL, &ap);
5488 g_variant_builder_add_value (builder, variant);
5492 * g_variant_get_child: (skip)
5493 * @value: a container #GVariant
5494 * @index_: the index of the child to deconstruct
5495 * @format_string: a #GVariant format string
5496 * @...: arguments, as per @format_string
5498 * Reads a child item out of a container #GVariant instance and
5499 * deconstructs it according to @format_string. This call is
5500 * essentially a combination of g_variant_get_child_value() and
5503 * @format_string determines the C types that are used for unpacking
5504 * the values and also determines if the values are copied or borrowed,
5505 * see the section on
5506 * [GVariant format strings][gvariant-format-strings-pointers].
5511 g_variant_get_child (GVariant *value,
5513 const gchar *format_string,
5519 child = g_variant_get_child_value (value, index_);
5520 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5522 va_start (ap, format_string);
5523 g_variant_get_va (child, format_string, NULL, &ap);
5526 g_variant_unref (child);
5530 * g_variant_iter_next: (skip)
5531 * @iter: a #GVariantIter
5532 * @format_string: a GVariant format string
5533 * @...: the arguments to unpack the value into
5535 * Gets the next item in the container and unpacks it into the variable
5536 * argument list according to @format_string, returning %TRUE.
5538 * If no more items remain then %FALSE is returned.
5540 * All of the pointers given on the variable arguments list of this
5541 * function are assumed to point at uninitialised memory. It is the
5542 * responsibility of the caller to free all of the values returned by
5543 * the unpacking process.
5545 * Here is an example for memory management with g_variant_iter_next():
5546 * |[<!-- language="C" -->
5547 * // Iterates a dictionary of type 'a{sv}'
5549 * iterate_dictionary (GVariant *dictionary)
5551 * GVariantIter iter;
5555 * g_variant_iter_init (&iter, dictionary);
5556 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5558 * g_print ("Item '%s' has type '%s'\n", key,
5559 * g_variant_get_type_string (value));
5561 * // must free data for ourselves
5562 * g_variant_unref (value);
5568 * For a solution that is likely to be more convenient to C programmers
5569 * when dealing with loops, see g_variant_iter_loop().
5571 * @format_string determines the C types that are used for unpacking
5572 * the values and also determines if the values are copied or borrowed.
5574 * See the section on
5575 * [GVariant format strings][gvariant-format-strings-pointers].
5577 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5582 g_variant_iter_next (GVariantIter *iter,
5583 const gchar *format_string,
5588 value = g_variant_iter_next_value (iter);
5590 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5597 va_start (ap, format_string);
5598 g_variant_valist_get (&format_string, value, FALSE, &ap);
5601 g_variant_unref (value);
5604 return value != NULL;
5608 * g_variant_iter_loop: (skip)
5609 * @iter: a #GVariantIter
5610 * @format_string: a GVariant format string
5611 * @...: the arguments to unpack the value into
5613 * Gets the next item in the container and unpacks it into the variable
5614 * argument list according to @format_string, returning %TRUE.
5616 * If no more items remain then %FALSE is returned.
5618 * On the first call to this function, the pointers appearing on the
5619 * variable argument list are assumed to point at uninitialised memory.
5620 * On the second and later calls, it is assumed that the same pointers
5621 * will be given and that they will point to the memory as set by the
5622 * previous call to this function. This allows the previous values to
5623 * be freed, as appropriate.
5625 * This function is intended to be used with a while loop as
5626 * demonstrated in the following example. This function can only be
5627 * used when iterating over an array. It is only valid to call this
5628 * function with a string constant for the format string and the same
5629 * string constant must be used each time. Mixing calls to this
5630 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5631 * the same iterator causes undefined behavior.
5633 * If you break out of a such a while loop using g_variant_iter_loop() then
5634 * you must free or unreference all the unpacked values as you would with
5635 * g_variant_get(). Failure to do so will cause a memory leak.
5637 * Here is an example for memory management with g_variant_iter_loop():
5638 * |[<!-- language="C" -->
5639 * // Iterates a dictionary of type 'a{sv}'
5641 * iterate_dictionary (GVariant *dictionary)
5643 * GVariantIter iter;
5647 * g_variant_iter_init (&iter, dictionary);
5648 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5650 * g_print ("Item '%s' has type '%s'\n", key,
5651 * g_variant_get_type_string (value));
5653 * // no need to free 'key' and 'value' here
5654 * // unless breaking out of this loop
5659 * For most cases you should use g_variant_iter_next().
5661 * This function is really only useful when unpacking into #GVariant or
5662 * #GVariantIter in order to allow you to skip the call to
5663 * g_variant_unref() or g_variant_iter_free().
5665 * For example, if you are only looping over simple integer and string
5666 * types, g_variant_iter_next() is definitely preferred. For string
5667 * types, use the '&' prefix to avoid allocating any memory at all (and
5668 * thereby avoiding the need to free anything as well).
5670 * @format_string determines the C types that are used for unpacking
5671 * the values and also determines if the values are copied or borrowed.
5673 * See the section on
5674 * [GVariant format strings][gvariant-format-strings-pointers].
5676 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5682 g_variant_iter_loop (GVariantIter *iter,
5683 const gchar *format_string,
5686 gboolean first_time = GVSI(iter)->loop_format == NULL;
5690 g_return_val_if_fail (first_time ||
5691 format_string == GVSI(iter)->loop_format,
5696 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5697 GVSI(iter)->loop_format = format_string;
5699 if (strchr (format_string, '&'))
5700 g_variant_get_data (GVSI(iter)->value);
5703 value = g_variant_iter_next_value (iter);
5705 g_return_val_if_fail (!first_time ||
5706 valid_format_string (format_string, TRUE, value),
5709 va_start (ap, format_string);
5710 g_variant_valist_get (&format_string, value, !first_time, &ap);
5714 g_variant_unref (value);
5716 return value != NULL;
5719 /* Serialised data {{{1 */
5721 g_variant_deep_copy (GVariant *value)
5723 switch (g_variant_classify (value))
5725 case G_VARIANT_CLASS_MAYBE:
5726 case G_VARIANT_CLASS_ARRAY:
5727 case G_VARIANT_CLASS_TUPLE:
5728 case G_VARIANT_CLASS_DICT_ENTRY:
5729 case G_VARIANT_CLASS_VARIANT:
5731 GVariantBuilder builder;
5735 g_variant_builder_init (&builder, g_variant_get_type (value));
5736 g_variant_iter_init (&iter, value);
5738 while ((child = g_variant_iter_next_value (&iter)))
5740 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5741 g_variant_unref (child);
5744 return g_variant_builder_end (&builder);
5747 case G_VARIANT_CLASS_BOOLEAN:
5748 return g_variant_new_boolean (g_variant_get_boolean (value));
5750 case G_VARIANT_CLASS_BYTE:
5751 return g_variant_new_byte (g_variant_get_byte (value));
5753 case G_VARIANT_CLASS_INT16:
5754 return g_variant_new_int16 (g_variant_get_int16 (value));
5756 case G_VARIANT_CLASS_UINT16:
5757 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5759 case G_VARIANT_CLASS_INT32:
5760 return g_variant_new_int32 (g_variant_get_int32 (value));
5762 case G_VARIANT_CLASS_UINT32:
5763 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5765 case G_VARIANT_CLASS_INT64:
5766 return g_variant_new_int64 (g_variant_get_int64 (value));
5768 case G_VARIANT_CLASS_UINT64:
5769 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5771 case G_VARIANT_CLASS_HANDLE:
5772 return g_variant_new_handle (g_variant_get_handle (value));
5774 case G_VARIANT_CLASS_FLOAT:
5775 return g_variant_new_float (g_variant_get_float (value));
5777 case G_VARIANT_CLASS_DOUBLE:
5778 return g_variant_new_double (g_variant_get_double (value));
5780 case G_VARIANT_CLASS_STRING:
5781 return g_variant_new_string (g_variant_get_string (value, NULL));
5783 case G_VARIANT_CLASS_OBJECT_PATH:
5784 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5786 case G_VARIANT_CLASS_SIGNATURE:
5787 return g_variant_new_signature (g_variant_get_string (value, NULL));
5790 g_assert_not_reached ();
5794 * g_variant_get_normal_form:
5795 * @value: a #GVariant
5797 * Gets a #GVariant instance that has the same value as @value and is
5798 * trusted to be in normal form.
5800 * If @value is already trusted to be in normal form then a new
5801 * reference to @value is returned.
5803 * If @value is not already trusted, then it is scanned to check if it
5804 * is in normal form. If it is found to be in normal form then it is
5805 * marked as trusted and a new reference to it is returned.
5807 * If @value is found not to be in normal form then a new trusted
5808 * #GVariant is created with the same value as @value.
5810 * It makes sense to call this function if you've received #GVariant
5811 * data from untrusted sources and you want to ensure your serialised
5812 * output is definitely in normal form.
5814 * Returns: (transfer full): a trusted #GVariant
5819 g_variant_get_normal_form (GVariant *value)
5823 if (g_variant_is_normal_form (value))
5824 return g_variant_ref (value);
5826 trusted = g_variant_deep_copy (value);
5827 g_assert (g_variant_is_trusted (trusted));
5829 return g_variant_ref_sink (trusted);
5833 * g_variant_byteswap:
5834 * @value: a #GVariant
5836 * Performs a byteswapping operation on the contents of @value. The
5837 * result is that all multi-byte numeric data contained in @value is
5838 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5839 * integers as well as file handles and floating point values.
5841 * This function is an identity mapping on any value that does not
5842 * contain multi-byte numeric data. That include strings, booleans,
5843 * bytes and containers containing only these things (recursively).
5845 * The returned value is always in normal form and is marked as trusted.
5847 * Returns: (transfer full): the byteswapped form of @value
5852 g_variant_byteswap (GVariant *value)
5854 GVariantTypeInfo *type_info;
5858 type_info = g_variant_get_type_info (value);
5860 g_variant_type_info_query (type_info, &alignment, NULL);
5863 /* (potentially) contains multi-byte numeric data */
5865 GVariantSerialised serialised;
5869 trusted = g_variant_get_normal_form (value);
5870 serialised.type_info = g_variant_get_type_info (trusted);
5871 serialised.size = g_variant_get_size (trusted);
5872 serialised.data = g_malloc (serialised.size);
5873 g_variant_store (trusted, serialised.data);
5874 g_variant_unref (trusted);
5876 g_variant_serialised_byteswap (serialised);
5878 bytes = g_bytes_new_take (serialised.data, serialised.size);
5879 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5880 g_bytes_unref (bytes);
5883 /* contains no multi-byte data */
5886 return g_variant_ref_sink (new);
5890 * g_variant_new_from_data:
5891 * @type: a definite #GVariantType
5892 * @data: (array length=size) (element-type guint8): the serialised data
5893 * @size: the size of @data
5894 * @trusted: %TRUE if @data is definitely in normal form
5895 * @notify: (scope async): function to call when @data is no longer needed
5896 * @user_data: data for @notify
5898 * Creates a new #GVariant instance from serialised data.
5900 * @type is the type of #GVariant instance that will be constructed.
5901 * The interpretation of @data depends on knowing the type.
5903 * @data is not modified by this function and must remain valid with an
5904 * unchanging value until such a time as @notify is called with
5905 * @user_data. If the contents of @data change before that time then
5906 * the result is undefined.
5908 * If @data is trusted to be serialised data in normal form then
5909 * @trusted should be %TRUE. This applies to serialised data created
5910 * within this process or read from a trusted location on the disk (such
5911 * as a file installed in /usr/lib alongside your application). You
5912 * should set trusted to %FALSE if @data is read from the network, a
5913 * file in the user's home directory, etc.
5915 * If @data was not stored in this machine's native endianness, any multi-byte
5916 * numeric values in the returned variant will also be in non-native
5917 * endianness. g_variant_byteswap() can be used to recover the original values.
5919 * @notify will be called with @user_data when @data is no longer
5920 * needed. The exact time of this call is unspecified and might even be
5921 * before this function returns.
5923 * Returns: (transfer none): a new floating #GVariant of type @type
5928 g_variant_new_from_data (const GVariantType *type,
5932 GDestroyNotify notify,
5938 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5939 g_return_val_if_fail (data != NULL || size == 0, NULL);
5942 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5944 bytes = g_bytes_new_static (data, size);
5946 value = g_variant_new_from_bytes (type, bytes, trusted);
5947 g_bytes_unref (bytes);
5953 /* vim:set foldmethod=marker: */