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,
291 gpointer mydata = g_memdup (data, size);
293 return g_variant_new_serialised (g_variant_type_info_get (type),
294 g_bytes_new_take (mydata, size), mydata, size, TRUE);
298 * g_variant_new_boolean:
299 * @value: a #gboolean value
301 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
303 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
308 g_variant_new_boolean (gboolean value)
312 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
316 * g_variant_get_boolean:
317 * @value: a boolean #GVariant instance
319 * Returns the boolean value of @value.
321 * It is an error to call this function with a @value of any type
322 * other than %G_VARIANT_TYPE_BOOLEAN.
324 * Returns: %TRUE or %FALSE
329 g_variant_get_boolean (GVariant *value)
333 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
335 data = g_variant_get_data (value);
337 return data != NULL ? *data != 0 : FALSE;
340 /* the constructors and accessors for byte, int{16,32,64}, handles and
341 * floats all look pretty much exactly the same, so we reduce
344 #define NUMERIC_TYPE(TYPE, type, ctype) \
345 GVariant *g_variant_new_##type (ctype value) { \
346 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
347 &value, sizeof value); \
349 ctype g_variant_get_##type (GVariant *value) { \
351 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
352 data = g_variant_get_data (value); \
353 return data != NULL ? *data : 0; \
358 * g_variant_new_byte:
359 * @value: a #guint8 value
361 * Creates a new byte #GVariant instance.
363 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
368 * g_variant_get_byte:
369 * @value: a byte #GVariant instance
371 * Returns the byte value of @value.
373 * It is an error to call this function with a @value of any type
374 * other than %G_VARIANT_TYPE_BYTE.
380 NUMERIC_TYPE (BYTE, byte, guchar)
383 * g_variant_new_int16:
384 * @value: a #gint16 value
386 * Creates a new int16 #GVariant instance.
388 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
393 * g_variant_get_int16:
394 * @value: a int16 #GVariant instance
396 * Returns the 16-bit signed integer value of @value.
398 * It is an error to call this function with a @value of any type
399 * other than %G_VARIANT_TYPE_INT16.
405 NUMERIC_TYPE (INT16, int16, gint16)
408 * g_variant_new_uint16:
409 * @value: a #guint16 value
411 * Creates a new uint16 #GVariant instance.
413 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
418 * g_variant_get_uint16:
419 * @value: a uint16 #GVariant instance
421 * Returns the 16-bit unsigned integer value of @value.
423 * It is an error to call this function with a @value of any type
424 * other than %G_VARIANT_TYPE_UINT16.
426 * Returns: a #guint16
430 NUMERIC_TYPE (UINT16, uint16, guint16)
433 * g_variant_new_int32:
434 * @value: a #gint32 value
436 * Creates a new int32 #GVariant instance.
438 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
443 * g_variant_get_int32:
444 * @value: a int32 #GVariant instance
446 * Returns the 32-bit signed integer value of @value.
448 * It is an error to call this function with a @value of any type
449 * other than %G_VARIANT_TYPE_INT32.
455 NUMERIC_TYPE (INT32, int32, gint32)
458 * g_variant_new_uint32:
459 * @value: a #guint32 value
461 * Creates a new uint32 #GVariant instance.
463 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
468 * g_variant_get_uint32:
469 * @value: a uint32 #GVariant instance
471 * Returns the 32-bit unsigned integer value of @value.
473 * It is an error to call this function with a @value of any type
474 * other than %G_VARIANT_TYPE_UINT32.
476 * Returns: a #guint32
480 NUMERIC_TYPE (UINT32, uint32, guint32)
483 * g_variant_new_int64:
484 * @value: a #gint64 value
486 * Creates a new int64 #GVariant instance.
488 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
493 * g_variant_get_int64:
494 * @value: a int64 #GVariant instance
496 * Returns the 64-bit signed integer value of @value.
498 * It is an error to call this function with a @value of any type
499 * other than %G_VARIANT_TYPE_INT64.
505 NUMERIC_TYPE (INT64, int64, gint64)
508 * g_variant_new_uint64:
509 * @value: a #guint64 value
511 * Creates a new uint64 #GVariant instance.
513 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
518 * g_variant_get_uint64:
519 * @value: a uint64 #GVariant instance
521 * Returns the 64-bit unsigned integer value of @value.
523 * It is an error to call this function with a @value of any type
524 * other than %G_VARIANT_TYPE_UINT64.
526 * Returns: a #guint64
530 NUMERIC_TYPE (UINT64, uint64, guint64)
533 * g_variant_new_handle:
534 * @value: a #gint32 value
536 * Creates a new handle #GVariant instance.
538 * By convention, handles are indexes into an array of file descriptors
539 * that are sent alongside a D-Bus message. If you're not interacting
540 * with D-Bus, you probably don't need them.
542 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
547 * g_variant_get_handle:
548 * @value: a handle #GVariant instance
550 * Returns the 32-bit signed integer value of @value.
552 * It is an error to call this function with a @value of any type other
553 * than %G_VARIANT_TYPE_HANDLE.
555 * By convention, handles are indexes into an array of file descriptors
556 * that are sent alongside a D-Bus message. If you're not interacting
557 * with D-Bus, you probably don't need them.
563 NUMERIC_TYPE (HANDLE, handle, gint32)
566 * g_variant_new_float:
567 * @value: a #gfloat floating point value
569 * Creates a new float #GVariant instance.
571 * Returns: (transfer none): a floating reference to a new float #GVariant instance
576 * g_variant_get_float:
577 * @value: a float #GVariant instance
579 * Returns the single precision floating point value of @value.
581 * It is an error to call this function with a @value of any type
582 * other than %G_VARIANT_TYPE_FLOAT.
588 NUMERIC_TYPE (FLOAT, float, gfloat)
591 * g_variant_new_double:
592 * @value: a #gdouble floating point value
594 * Creates a new double #GVariant instance.
596 * Returns: (transfer none): a floating reference to a new double #GVariant instance
601 * g_variant_get_double:
602 * @value: a double #GVariant instance
604 * Returns the double precision floating point value of @value.
606 * It is an error to call this function with a @value of any type
607 * other than %G_VARIANT_TYPE_DOUBLE.
609 * Returns: a #gdouble
613 NUMERIC_TYPE (DOUBLE, double, gdouble)
615 /* Container type Constructor / Deconstructors {{{1 */
617 * g_variant_new_maybe:
618 * @child_type: (allow-none): the #GVariantType of the child, or %NULL
619 * @child: (allow-none): the child value, or %NULL
621 * Depending on if @child is %NULL, either wraps @child inside of a
622 * maybe container or creates a Nothing instance for the given @type.
624 * At least one of @child_type and @child must be non-%NULL.
625 * If @child_type is non-%NULL then it must be a definite type.
626 * If they are both non-%NULL then @child_type must be the type
629 * If @child is a floating reference (see g_variant_ref_sink()), the new
630 * instance takes ownership of @child.
632 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
637 g_variant_new_maybe (const GVariantType *child_type,
640 GVariantTypeInfo *type_info;
641 GVariantType *maybe_type;
643 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
645 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
646 g_return_val_if_fail (child_type == NULL || child == NULL ||
647 g_variant_is_of_type (child, child_type),
650 if (child_type == NULL)
651 child_type = g_variant_get_type (child);
653 maybe_type = g_variant_type_new_maybe (child_type);
654 type_info = g_variant_type_info_get (maybe_type);
655 g_variant_type_free (maybe_type);
662 children = g_new (GVariant *, 1);
663 children[0] = g_variant_ref_sink (child);
664 trusted = g_variant_is_trusted (children[0]);
666 return g_variant_new_from_children (type_info, children, 1, trusted);
669 return g_variant_new_from_children (type_info, NULL, 0, TRUE);
673 * g_variant_get_maybe:
674 * @value: a maybe-typed value
676 * Given a maybe-typed #GVariant instance, extract its value. If the
677 * value is Nothing, then this function returns %NULL.
679 * Returns: (allow-none) (transfer full): the contents of @value, or %NULL
684 g_variant_get_maybe (GVariant *value)
686 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
688 if (g_variant_n_children (value))
689 return g_variant_get_child_value (value, 0);
695 * g_variant_new_variant: (constructor)
696 * @value: a #GVariant instance
698 * Boxes @value. The result is a #GVariant instance representing a
699 * variant containing the original value.
701 * If @child is a floating reference (see g_variant_ref_sink()), the new
702 * instance takes ownership of @child.
704 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
709 g_variant_new_variant (GVariant *value)
711 g_return_val_if_fail (value != NULL, NULL);
713 g_variant_ref_sink (value);
715 return g_variant_new_from_children (g_variant_type_info_get (G_VARIANT_TYPE_VARIANT),
716 g_memdup (&value, sizeof value),
717 1, g_variant_is_trusted (value));
721 * g_variant_get_variant:
722 * @value: a variant #GVariant instance
724 * Unboxes @value. The result is the #GVariant instance that was
725 * contained in @value.
727 * Returns: (transfer full): the item contained in the variant
732 g_variant_get_variant (GVariant *value)
734 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
736 return g_variant_get_child_value (value, 0);
740 * g_variant_new_array:
741 * @child_type: (allow-none): the element type of the new array
742 * @children: (allow-none) (array length=n_children): an array of
743 * #GVariant pointers, the children
744 * @n_children: the length of @children
746 * Creates a new #GVariant array from @children.
748 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
749 * child type is determined by inspecting the first element of the
750 * @children array. If @child_type is non-%NULL then it must be a
753 * The items of the array are taken from the @children array. No entry
754 * in the @children array may be %NULL.
756 * All items in the array must have the same type, which must be the
757 * same as @child_type, if given.
759 * If the @children are floating references (see g_variant_ref_sink()), the
760 * new instance takes ownership of them as if via g_variant_ref_sink().
762 * Returns: (transfer none): a floating reference to a new #GVariant array
767 g_variant_new_array (const GVariantType *child_type,
768 GVariant * const *children,
771 GVariantTypeInfo *type_info;
772 GVariantType *array_type;
773 GVariant **my_children;
777 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
778 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
779 g_return_val_if_fail (child_type == NULL ||
780 g_variant_type_is_definite (child_type), NULL);
782 my_children = g_new (GVariant *, n_children);
785 if (child_type == NULL)
786 child_type = g_variant_get_type (children[0]);
787 array_type = g_variant_type_new_array (child_type);
788 type_info = g_variant_type_info_get (array_type);
789 g_variant_type_free (array_type);
791 for (i = 0; i < n_children; i++)
793 TYPE_CHECK (children[i], child_type, NULL);
794 my_children[i] = g_variant_ref_sink (children[i]);
795 trusted &= g_variant_is_trusted (children[i]);
798 return g_variant_new_from_children (type_info, my_children, n_children, trusted);
802 * g_variant_make_tuple_type:
803 * @children: (array length=n_children): an array of GVariant *
804 * @n_children: the length of @children
806 * Return the type of a tuple containing @children as its items.
808 static GVariantType *
809 g_variant_make_tuple_type (GVariant * const *children,
812 const GVariantType **types;
816 types = g_new (const GVariantType *, n_children);
818 for (i = 0; i < n_children; i++)
819 types[i] = g_variant_get_type (children[i]);
821 type = g_variant_type_new_tuple (types, n_children);
828 * g_variant_new_tuple:
829 * @children: (array length=n_children): the items to make the tuple out of
830 * @n_children: the length of @children
832 * Creates a new tuple #GVariant out of the items in @children. The
833 * type is determined from the types of @children. No entry in the
834 * @children array may be %NULL.
836 * If @n_children is 0 then the unit tuple is constructed.
838 * If the @children are floating references (see g_variant_ref_sink()), the
839 * new instance takes ownership of them as if via g_variant_ref_sink().
841 * Returns: (transfer none): a floating reference to a new #GVariant tuple
846 g_variant_new_tuple (GVariant * const *children,
849 GVariantTypeInfo *type_info;
850 GVariantType *tuple_type;
851 GVariant **my_children;
855 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
857 my_children = g_new (GVariant *, n_children);
860 for (i = 0; i < n_children; i++)
862 my_children[i] = g_variant_ref_sink (children[i]);
863 trusted &= g_variant_is_trusted (children[i]);
866 tuple_type = g_variant_make_tuple_type (children, n_children);
867 type_info = g_variant_type_info_get (tuple_type);
868 g_variant_type_free (tuple_type);
870 return g_variant_new_from_children (type_info, my_children, n_children, trusted);
874 * g_variant_make_dict_entry_type:
875 * @key: a #GVariant, the key
876 * @val: a #GVariant, the value
878 * Return the type of a dictionary entry containing @key and @val as its
881 static GVariantType *
882 g_variant_make_dict_entry_type (GVariant *key,
885 return g_variant_type_new_dict_entry (g_variant_get_type (key),
886 g_variant_get_type (val));
890 * g_variant_new_dict_entry: (constructor)
891 * @key: a basic #GVariant, the key
892 * @value: a #GVariant, the value
894 * Creates a new dictionary entry #GVariant. @key and @value must be
895 * non-%NULL. @key must be a value of a basic type (ie: not a container).
897 * If the @key or @value are floating references (see g_variant_ref_sink()),
898 * the new instance takes ownership of them as if via g_variant_ref_sink().
900 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
905 g_variant_new_dict_entry (GVariant *key,
908 GVariantTypeInfo *type_info;
909 GVariantType *dict_type;
913 g_return_val_if_fail (key != NULL && value != NULL, NULL);
914 g_return_val_if_fail (!g_variant_is_container (key), NULL);
916 children = g_new (GVariant *, 2);
917 children[0] = g_variant_ref_sink (key);
918 children[1] = g_variant_ref_sink (value);
919 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
921 dict_type = g_variant_make_dict_entry_type (key, value);
922 type_info = g_variant_type_info_get (dict_type);
923 g_variant_type_free (dict_type);
925 return g_variant_new_from_children (type_info, children, 2, trusted);
929 * g_variant_lookup: (skip)
930 * @dictionary: a dictionary #GVariant
931 * @key: the key to lookup in the dictionary
932 * @format_string: a GVariant format string
933 * @...: the arguments to unpack the value into
935 * Looks up a value in a dictionary #GVariant.
937 * This function is a wrapper around g_variant_lookup_value() and
938 * g_variant_get(). In the case that %NULL would have been returned,
939 * this function returns %FALSE. Otherwise, it unpacks the returned
940 * value and returns %TRUE.
942 * @format_string determines the C types that are used for unpacking
943 * the values and also determines if the values are copied or borrowed,
945 * [GVariant format strings][gvariant-format-strings-pointers].
947 * This function is currently implemented with a linear scan. If you
948 * plan to do many lookups then #GVariantDict may be more efficient.
950 * Returns: %TRUE if a value was unpacked
955 g_variant_lookup (GVariant *dictionary,
957 const gchar *format_string,
964 g_variant_get_data (dictionary);
966 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
967 value = g_variant_lookup_value (dictionary, key, type);
968 g_variant_type_free (type);
974 va_start (ap, format_string);
975 g_variant_get_va (value, format_string, NULL, &ap);
976 g_variant_unref (value);
987 * g_variant_lookup_value:
988 * @dictionary: a dictionary #GVariant
989 * @key: the key to lookup in the dictionary
990 * @expected_type: (allow-none): a #GVariantType, or %NULL
992 * Looks up a value in a dictionary #GVariant.
994 * This function works with dictionaries of the type a{s*} (and equally
995 * well with type a{o*}, but we only further discuss the string case
996 * for sake of clarity).
998 * In the event that @dictionary has the type a{sv}, the @expected_type
999 * string specifies what type of value is expected to be inside of the
1000 * variant. If the value inside the variant has a different type then
1001 * %NULL is returned. In the event that @dictionary has a value type other
1002 * than v then @expected_type must directly match the key type and it is
1003 * used to unpack the value directly or an error occurs.
1005 * In either case, if @key is not found in @dictionary, %NULL is returned.
1007 * If the key is found and the value has the correct type, it is
1008 * returned. If @expected_type was specified then any non-%NULL return
1009 * value will have this type.
1011 * This function is currently implemented with a linear scan. If you
1012 * plan to do many lookups then #GVariantDict may be more efficient.
1014 * Returns: (transfer full): the value of the dictionary key, or %NULL
1019 g_variant_lookup_value (GVariant *dictionary,
1021 const GVariantType *expected_type)
1027 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1028 G_VARIANT_TYPE ("a{s*}")) ||
1029 g_variant_is_of_type (dictionary,
1030 G_VARIANT_TYPE ("a{o*}")),
1033 g_variant_iter_init (&iter, dictionary);
1035 while ((entry = g_variant_iter_next_value (&iter)))
1037 GVariant *entry_key;
1040 entry_key = g_variant_get_child_value (entry, 0);
1041 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1042 g_variant_unref (entry_key);
1047 g_variant_unref (entry);
1053 value = g_variant_get_child_value (entry, 1);
1054 g_variant_unref (entry);
1056 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1060 tmp = g_variant_get_variant (value);
1061 g_variant_unref (value);
1063 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1065 g_variant_unref (tmp);
1072 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1073 g_variant_is_of_type (value, expected_type), NULL);
1079 * g_variant_get_fixed_array:
1080 * @value: a #GVariant array with fixed-sized elements
1081 * @n_elements: (out): a pointer to the location to store the number of items
1082 * @element_size: the size of each element
1084 * Provides access to the serialised data for an array of fixed-sized
1087 * @value must be an array with fixed-sized elements. Numeric types are
1088 * fixed-size, as are tuples containing only other fixed-sized types.
1090 * @element_size must be the size of a single element in the array,
1091 * as given by the section on
1092 * [serialized data memory][gvariant-serialised-data-memory].
1094 * In particular, arrays of these fixed-sized types can be interpreted
1095 * as an array of the given C type, with @element_size set to the size
1096 * the appropriate type:
1097 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1098 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1099 * - %G_VARIANT_TYPE_BYTE: #guchar
1100 * - %G_VARIANT_TYPE_HANDLE: #guint32
1101 * - %G_VARIANT_TYPE_FLOAT: #gfloat
1102 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1104 * For example, if calling this function for an array of 32-bit integers,
1105 * you might say sizeof(gint32). This value isn't used except for the purpose
1106 * of a double-check that the form of the serialised data matches the caller's
1109 * @n_elements, which must be non-%NULL is set equal to the number of
1110 * items in the array.
1112 * Returns: (array length=n_elements) (transfer none): a pointer to
1118 g_variant_get_fixed_array (GVariant *value,
1122 GVariantTypeInfo *array_info;
1123 gsize array_element_size;
1127 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1129 g_return_val_if_fail (n_elements != NULL, NULL);
1130 g_return_val_if_fail (element_size > 0, NULL);
1132 array_info = g_variant_get_type_info (value);
1133 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1135 g_return_val_if_fail (array_element_size, NULL);
1137 if G_UNLIKELY (array_element_size != element_size)
1139 if (array_element_size)
1140 g_critical ("g_variant_get_fixed_array: assertion "
1141 "'g_variant_array_has_fixed_size (value, element_size)' "
1142 "failed: array size %"G_GSIZE_FORMAT" does not match "
1143 "given element_size %"G_GSIZE_FORMAT".",
1144 array_element_size, element_size);
1146 g_critical ("g_variant_get_fixed_array: assertion "
1147 "'g_variant_array_has_fixed_size (value, element_size)' "
1148 "failed: array does not have fixed size.");
1151 data = g_variant_get_data (value);
1152 size = g_variant_get_size (value);
1154 if (size % element_size)
1157 *n_elements = size / element_size;
1166 * g_variant_new_fixed_array:
1167 * @element_type: the #GVariantType of each element
1168 * @elements: a pointer to the fixed array of contiguous elements
1169 * @n_elements: the number of elements
1170 * @element_size: the size of each element
1172 * Provides access to the serialised data for an array of fixed-sized
1175 * @value must be an array with fixed-sized elements. Numeric types are
1176 * fixed-size as are tuples containing only other fixed-sized types.
1178 * @element_size must be the size of a single element in the array.
1179 * For example, if calling this function for an array of 32-bit integers,
1180 * you might say sizeof(gint32). This value isn't used except for the purpose
1181 * of a double-check that the form of the serialised data matches the caller's
1184 * @n_elements, which must be non-%NULL is set equal to the number of
1185 * items in the array.
1187 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1192 g_variant_new_fixed_array (const GVariantType *element_type,
1193 gconstpointer elements,
1197 GVariantType *array_type;
1198 gsize array_element_size;
1199 GVariantTypeInfo *array_info;
1203 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1204 g_return_val_if_fail (element_size > 0, NULL);
1206 array_type = g_variant_type_new_array (element_type);
1207 array_info = g_variant_type_info_get (array_type);
1208 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1209 if G_UNLIKELY (array_element_size != element_size)
1211 if (array_element_size)
1212 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1213 " does not match given element_size %" G_GSIZE_FORMAT ".",
1214 array_element_size, element_size);
1216 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1220 data = g_memdup (elements, n_elements * element_size);
1221 value = g_variant_new_from_data (array_type, data,
1222 n_elements * element_size,
1223 FALSE, g_free, data);
1225 g_variant_type_free (array_type);
1226 g_variant_type_info_unref (array_info);
1231 /* String type constructor/getters/validation {{{1 */
1233 * g_variant_new_string:
1234 * @string: a normal utf8 nul-terminated string
1236 * Creates a string #GVariant with the contents of @string.
1238 * @string must be valid utf8.
1240 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1245 g_variant_new_string (const gchar *string)
1247 g_return_val_if_fail (string != NULL, NULL);
1248 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1250 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1251 string, strlen (string) + 1);
1255 * g_variant_new_take_string: (skip)
1256 * @string: a normal utf8 nul-terminated string
1258 * Creates a string #GVariant with the contents of @string.
1260 * @string must be valid utf8.
1262 * This function consumes @string. g_free() will be called on @string
1263 * when it is no longer required.
1265 * You must not modify or access @string in any other way after passing
1266 * it to this function. It is even possible that @string is immediately
1269 * Returns: (transfer none): a floating reference to a new string
1270 * #GVariant instance
1275 g_variant_new_take_string (gchar *string)
1280 g_return_val_if_fail (string != NULL, NULL);
1281 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1283 bytes = g_bytes_new_take (string, strlen (string) + 1);
1284 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1285 g_bytes_unref (bytes);
1291 * g_variant_new_printf: (skip)
1292 * @format_string: a printf-style format string
1293 * @...: arguments for @format_string
1295 * Creates a string-type GVariant using printf formatting.
1297 * This is similar to calling g_strdup_printf() and then
1298 * g_variant_new_string() but it saves a temporary variable and an
1301 * Returns: (transfer none): a floating reference to a new string
1302 * #GVariant instance
1307 g_variant_new_printf (const gchar *format_string,
1315 g_return_val_if_fail (format_string != NULL, NULL);
1317 va_start (ap, format_string);
1318 string = g_strdup_vprintf (format_string, ap);
1321 bytes = g_bytes_new_take (string, strlen (string) + 1);
1322 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1323 g_bytes_unref (bytes);
1329 * g_variant_new_object_path:
1330 * @object_path: a normal C nul-terminated string
1332 * Creates a D-Bus object path #GVariant with the contents of @string.
1333 * @string must be a valid D-Bus object path. Use
1334 * g_variant_is_object_path() if you're not sure.
1336 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1341 g_variant_new_object_path (const gchar *object_path)
1343 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1345 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1346 object_path, strlen (object_path) + 1);
1350 * g_variant_is_object_path:
1351 * @string: a normal C nul-terminated string
1353 * Determines if a given string is a valid D-Bus object path. You
1354 * should ensure that a string is a valid D-Bus object path before
1355 * passing it to g_variant_new_object_path().
1357 * A valid object path starts with '/' followed by zero or more
1358 * sequences of characters separated by '/' characters. Each sequence
1359 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1360 * (including the one following the final '/' character) may be empty.
1362 * Returns: %TRUE if @string is a D-Bus object path
1367 g_variant_is_object_path (const gchar *string)
1369 g_return_val_if_fail (string != NULL, FALSE);
1371 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1375 * g_variant_new_signature:
1376 * @signature: a normal C nul-terminated string
1378 * Creates a D-Bus type signature #GVariant with the contents of
1379 * @string. @string must be a valid D-Bus type signature. Use
1380 * g_variant_is_signature() if you're not sure.
1382 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1387 g_variant_new_signature (const gchar *signature)
1389 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1391 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1392 signature, strlen (signature) + 1);
1396 * g_variant_is_signature:
1397 * @string: a normal C nul-terminated string
1399 * Determines if a given string is a valid D-Bus type signature. You
1400 * should ensure that a string is a valid D-Bus type signature before
1401 * passing it to g_variant_new_signature().
1403 * D-Bus type signatures consist of zero or more definite #GVariantType
1404 * strings in sequence.
1406 * Returns: %TRUE if @string is a D-Bus type signature
1411 g_variant_is_signature (const gchar *string)
1413 g_return_val_if_fail (string != NULL, FALSE);
1415 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1419 * g_variant_get_string:
1420 * @value: a string #GVariant instance
1421 * @length: (allow-none) (default 0) (out): a pointer to a #gsize,
1422 * to store the length
1424 * Returns the string value of a #GVariant instance with a string
1425 * type. This includes the types %G_VARIANT_TYPE_STRING,
1426 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1428 * The string will always be utf8 encoded.
1430 * If @length is non-%NULL then the length of the string (in bytes) is
1431 * returned there. For trusted values, this information is already
1432 * known. For untrusted values, a strlen() will be performed.
1434 * It is an error to call this function with a @value of any type
1435 * other than those three.
1437 * The return value remains valid as long as @value exists.
1439 * Returns: (transfer none): the constant string, utf8 encoded
1444 g_variant_get_string (GVariant *value,
1450 g_return_val_if_fail (value != NULL, NULL);
1451 g_return_val_if_fail (
1452 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1453 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1454 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1456 data = g_variant_get_data (value);
1457 size = g_variant_get_size (value);
1459 if (!g_variant_is_trusted (value))
1461 switch (g_variant_classify (value))
1463 case G_VARIANT_CLASS_STRING:
1464 if (g_variant_serialiser_is_string (data, size))
1471 case G_VARIANT_CLASS_OBJECT_PATH:
1472 if (g_variant_serialiser_is_object_path (data, size))
1479 case G_VARIANT_CLASS_SIGNATURE:
1480 if (g_variant_serialiser_is_signature (data, size))
1488 g_assert_not_reached ();
1499 * g_variant_dup_string:
1500 * @value: a string #GVariant instance
1501 * @length: (out): a pointer to a #gsize, to store the length
1503 * Similar to g_variant_get_string() except that instead of returning
1504 * a constant string, the string is duplicated.
1506 * The string will always be utf8 encoded.
1508 * The return value must be freed using g_free().
1510 * Returns: (transfer full): a newly allocated string, utf8 encoded
1515 g_variant_dup_string (GVariant *value,
1518 return g_strdup (g_variant_get_string (value, length));
1522 * g_variant_new_strv:
1523 * @strv: (array length=length) (element-type utf8): an array of strings
1524 * @length: the length of @strv, or -1
1526 * Constructs an array of strings #GVariant from the given array of
1529 * If @length is -1 then @strv is %NULL-terminated.
1531 * Returns: (transfer none): a new floating #GVariant instance
1536 g_variant_new_strv (const gchar * const *strv,
1542 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1545 length = g_strv_length ((gchar **) strv);
1547 strings = g_new (GVariant *, length);
1548 for (i = 0; i < length; i++)
1549 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1551 return g_variant_new_from_children (g_variant_type_info_get (G_VARIANT_TYPE_STRING_ARRAY),
1552 strings, length, TRUE);
1556 * g_variant_get_strv:
1557 * @value: an array of strings #GVariant
1558 * @length: (out) (allow-none): the length of the result, or %NULL
1560 * Gets the contents of an array of strings #GVariant. This call
1561 * makes a shallow copy; the return result should be released with
1562 * g_free(), but the individual strings must not be modified.
1564 * If @length is non-%NULL then the number of elements in the result
1565 * is stored there. In any case, the resulting array will be
1568 * For an empty array, @length will be set to 0 and a pointer to a
1569 * %NULL pointer will be returned.
1571 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1576 g_variant_get_strv (GVariant *value,
1583 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1585 g_variant_get_data (value);
1586 n = g_variant_n_children (value);
1587 strv = g_new (const gchar *, n + 1);
1589 for (i = 0; i < n; i++)
1593 string = g_variant_get_child_value (value, i);
1594 strv[i] = g_variant_get_string (string, NULL);
1595 g_variant_unref (string);
1606 * g_variant_dup_strv:
1607 * @value: an array of strings #GVariant
1608 * @length: (out) (allow-none): the length of the result, or %NULL
1610 * Gets the contents of an array of strings #GVariant. This call
1611 * makes a deep copy; the return result should be released with
1614 * If @length is non-%NULL then the number of elements in the result
1615 * is stored there. In any case, the resulting array will be
1618 * For an empty array, @length will be set to 0 and a pointer to a
1619 * %NULL pointer will be returned.
1621 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1626 g_variant_dup_strv (GVariant *value,
1633 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1635 n = g_variant_n_children (value);
1636 strv = g_new (gchar *, n + 1);
1638 for (i = 0; i < n; i++)
1642 string = g_variant_get_child_value (value, i);
1643 strv[i] = g_variant_dup_string (string, NULL);
1644 g_variant_unref (string);
1655 * g_variant_new_objv:
1656 * @strv: (array length=length) (element-type utf8): an array of strings
1657 * @length: the length of @strv, or -1
1659 * Constructs an array of object paths #GVariant from the given array of
1662 * Each string must be a valid #GVariant object path; see
1663 * g_variant_is_object_path().
1665 * If @length is -1 then @strv is %NULL-terminated.
1667 * Returns: (transfer none): a new floating #GVariant instance
1672 g_variant_new_objv (const gchar * const *strv,
1678 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1681 length = g_strv_length ((gchar **) strv);
1683 strings = g_new (GVariant *, length);
1684 for (i = 0; i < length; i++)
1685 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1687 return g_variant_new_from_children (g_variant_type_info_get (G_VARIANT_TYPE_OBJECT_PATH_ARRAY),
1688 strings, length, TRUE);
1692 * g_variant_get_objv:
1693 * @value: an array of object paths #GVariant
1694 * @length: (out) (allow-none): the length of the result, or %NULL
1696 * Gets the contents of an array of object paths #GVariant. This call
1697 * makes a shallow copy; the return result should be released with
1698 * g_free(), but the individual strings must not be modified.
1700 * If @length is non-%NULL then the number of elements in the result
1701 * is stored there. In any case, the resulting array will be
1704 * For an empty array, @length will be set to 0 and a pointer to a
1705 * %NULL pointer will be returned.
1707 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1712 g_variant_get_objv (GVariant *value,
1719 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1721 g_variant_get_data (value);
1722 n = g_variant_n_children (value);
1723 strv = g_new (const gchar *, n + 1);
1725 for (i = 0; i < n; i++)
1729 string = g_variant_get_child_value (value, i);
1730 strv[i] = g_variant_get_string (string, NULL);
1731 g_variant_unref (string);
1742 * g_variant_dup_objv:
1743 * @value: an array of object paths #GVariant
1744 * @length: (out) (allow-none): the length of the result, or %NULL
1746 * Gets the contents of an array of object paths #GVariant. This call
1747 * makes a deep copy; the return result should be released with
1750 * If @length is non-%NULL then the number of elements in the result
1751 * is stored there. In any case, the resulting array will be
1754 * For an empty array, @length will be set to 0 and a pointer to a
1755 * %NULL pointer will be returned.
1757 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1762 g_variant_dup_objv (GVariant *value,
1769 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1771 n = g_variant_n_children (value);
1772 strv = g_new (gchar *, n + 1);
1774 for (i = 0; i < n; i++)
1778 string = g_variant_get_child_value (value, i);
1779 strv[i] = g_variant_dup_string (string, NULL);
1780 g_variant_unref (string);
1792 * g_variant_new_bytestring:
1793 * @string: (array zero-terminated=1) (element-type guint8): a normal
1794 * nul-terminated string in no particular encoding
1796 * Creates an array-of-bytes #GVariant with the contents of @string.
1797 * This function is just like g_variant_new_string() except that the
1798 * string need not be valid utf8.
1800 * The nul terminator character at the end of the string is stored in
1803 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1808 g_variant_new_bytestring (const gchar *string)
1810 g_return_val_if_fail (string != NULL, NULL);
1812 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1813 string, strlen (string) + 1);
1817 * g_variant_get_bytestring:
1818 * @value: an array-of-bytes #GVariant instance
1820 * Returns the string value of a #GVariant instance with an
1821 * array-of-bytes type. The string has no particular encoding.
1823 * If the array does not end with a nul terminator character, the empty
1824 * string is returned. For this reason, you can always trust that a
1825 * non-%NULL nul-terminated string will be returned by this function.
1827 * If the array contains a nul terminator character somewhere other than
1828 * the last byte then the returned string is the string, up to the first
1829 * such nul character.
1831 * It is an error to call this function with a @value that is not an
1834 * The return value remains valid as long as @value exists.
1836 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1837 * the constant string
1842 g_variant_get_bytestring (GVariant *value)
1844 const gchar *string;
1847 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1849 /* Won't be NULL since this is an array type */
1850 string = g_variant_get_data (value);
1851 size = g_variant_get_size (value);
1853 if (size && string[size - 1] == '\0')
1860 * g_variant_dup_bytestring:
1861 * @value: an array-of-bytes #GVariant instance
1862 * @length: (out) (allow-none) (default NULL): a pointer to a #gsize, to store
1863 * the length (not including the nul terminator)
1865 * Similar to g_variant_get_bytestring() except that instead of
1866 * returning a constant string, the string is duplicated.
1868 * The return value must be freed using g_free().
1870 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1871 * a newly allocated string
1876 g_variant_dup_bytestring (GVariant *value,
1879 const gchar *original = g_variant_get_bytestring (value);
1882 /* don't crash in case get_bytestring() had an assert failure */
1883 if (original == NULL)
1886 size = strlen (original);
1891 return g_memdup (original, size + 1);
1895 * g_variant_new_bytestring_array:
1896 * @strv: (array length=length): an array of strings
1897 * @length: the length of @strv, or -1
1899 * Constructs an array of bytestring #GVariant from the given array of
1902 * If @length is -1 then @strv is %NULL-terminated.
1904 * Returns: (transfer none): a new floating #GVariant instance
1909 g_variant_new_bytestring_array (const gchar * const *strv,
1915 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1918 length = g_strv_length ((gchar **) strv);
1920 strings = g_new (GVariant *, length);
1921 for (i = 0; i < length; i++)
1922 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1924 return g_variant_new_from_children (g_variant_type_info_get (G_VARIANT_TYPE_BYTESTRING_ARRAY),
1925 strings, length, TRUE);
1929 * g_variant_get_bytestring_array:
1930 * @value: an array of array of bytes #GVariant ('aay')
1931 * @length: (out) (allow-none): the length of the result, or %NULL
1933 * Gets the contents of an array of array of bytes #GVariant. This call
1934 * makes a shallow copy; the return result should be released with
1935 * g_free(), but the individual strings must not be modified.
1937 * If @length is non-%NULL then the number of elements in the result is
1938 * stored there. In any case, the resulting array will be
1941 * For an empty array, @length will be set to 0 and a pointer to a
1942 * %NULL pointer will be returned.
1944 * Returns: (array length=length) (transfer container): an array of constant strings
1949 g_variant_get_bytestring_array (GVariant *value,
1956 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1958 g_variant_get_data (value);
1959 n = g_variant_n_children (value);
1960 strv = g_new (const gchar *, n + 1);
1962 for (i = 0; i < n; i++)
1966 string = g_variant_get_child_value (value, i);
1967 strv[i] = g_variant_get_bytestring (string);
1968 g_variant_unref (string);
1979 * g_variant_dup_bytestring_array:
1980 * @value: an array of array of bytes #GVariant ('aay')
1981 * @length: (out) (allow-none): the length of the result, or %NULL
1983 * Gets the contents of an array of array of bytes #GVariant. This call
1984 * makes a deep copy; the return result should be released with
1987 * If @length is non-%NULL then the number of elements in the result is
1988 * stored there. In any case, the resulting array will be
1991 * For an empty array, @length will be set to 0 and a pointer to a
1992 * %NULL pointer will be returned.
1994 * Returns: (array length=length) (transfer full): an array of strings
1999 g_variant_dup_bytestring_array (GVariant *value,
2006 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2008 g_variant_get_data (value);
2009 n = g_variant_n_children (value);
2010 strv = g_new (gchar *, n + 1);
2012 for (i = 0; i < n; i++)
2016 string = g_variant_get_child_value (value, i);
2017 strv[i] = g_variant_dup_bytestring (string, NULL);
2018 g_variant_unref (string);
2028 /* Type checking and querying {{{1 */
2030 * g_variant_get_type:
2031 * @value: a #GVariant
2033 * Determines the type of @value.
2035 * The return value is valid for the lifetime of @value and must not
2038 * Returns: a #GVariantType
2042 const GVariantType *
2043 g_variant_get_type (GVariant *value)
2045 GVariantTypeInfo *type_info;
2047 g_return_val_if_fail (value != NULL, NULL);
2049 type_info = g_variant_get_type_info (value);
2051 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2055 * g_variant_get_type_string:
2056 * @value: a #GVariant
2058 * Returns the type string of @value. Unlike the result of calling
2059 * g_variant_type_peek_string(), this string is nul-terminated. This
2060 * string belongs to #GVariant and must not be freed.
2062 * Returns: the type string for the type of @value
2067 g_variant_get_type_string (GVariant *value)
2069 GVariantTypeInfo *type_info;
2071 g_return_val_if_fail (value != NULL, NULL);
2073 type_info = g_variant_get_type_info (value);
2075 return g_variant_type_info_get_type_string (type_info);
2079 * g_variant_is_of_type:
2080 * @value: a #GVariant instance
2081 * @type: a #GVariantType
2083 * Checks if a value has a type matching the provided type.
2085 * Returns: %TRUE if the type of @value matches @type
2090 g_variant_is_of_type (GVariant *value,
2091 const GVariantType *type)
2093 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2097 * g_variant_is_container:
2098 * @value: a #GVariant instance
2100 * Checks if @value is a container.
2102 * Returns: %TRUE if @value is a container
2107 g_variant_is_container (GVariant *value)
2109 return g_variant_type_is_container (g_variant_get_type (value));
2114 * g_variant_classify:
2115 * @value: a #GVariant
2117 * Classifies @value according to its top-level type.
2119 * Returns: the #GVariantClass of @value
2125 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2126 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2127 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2128 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2129 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2130 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2131 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2132 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2133 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2134 * @G_VARIANT_CLASS_FLOAT: The #GVariant is a single precision floating
2136 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2138 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2139 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2141 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2142 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2143 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2144 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2145 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2146 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2148 * The range of possible top-level types of #GVariant instances.
2153 g_variant_classify (GVariant *value)
2155 g_return_val_if_fail (value != NULL, 0);
2157 return *g_variant_get_type_string (value);
2160 /* Pretty printer {{{1 */
2161 /* This function is not introspectable because if @string is NULL,
2162 @returns is (transfer full), otherwise it is (transfer none), which
2163 is not supported by GObjectIntrospection */
2165 * g_variant_print_string: (skip)
2166 * @value: a #GVariant
2167 * @string: (allow-none) (default NULL): a #GString, or %NULL
2168 * @type_annotate: %TRUE if type information should be included in
2171 * Behaves as g_variant_print(), but operates on a #GString.
2173 * If @string is non-%NULL then it is appended to and returned. Else,
2174 * a new empty #GString is allocated and it is returned.
2176 * Returns: a #GString containing the string
2181 g_variant_print_string (GVariant *value,
2183 gboolean type_annotate)
2185 if G_UNLIKELY (string == NULL)
2186 string = g_string_new (NULL);
2188 switch (g_variant_classify (value))
2190 case G_VARIANT_CLASS_MAYBE:
2192 g_string_append_printf (string, "@%s ",
2193 g_variant_get_type_string (value));
2195 if (g_variant_n_children (value))
2197 gchar *printed_child;
2202 * Consider the case of the type "mmi". In this case we could
2203 * write "just just 4", but "4" alone is totally unambiguous,
2204 * so we try to drop "just" where possible.
2206 * We have to be careful not to always drop "just", though,
2207 * since "nothing" needs to be distinguishable from "just
2208 * nothing". The case where we need to ensure we keep the
2209 * "just" is actually exactly the case where we have a nested
2212 * Instead of searching for that nested Nothing, we just print
2213 * the contained value into a separate string and see if we
2214 * end up with "nothing" at the end of it. If so, we need to
2215 * add "just" at our level.
2217 element = g_variant_get_child_value (value, 0);
2218 printed_child = g_variant_print (element, FALSE);
2219 g_variant_unref (element);
2221 if (g_str_has_suffix (printed_child, "nothing"))
2222 g_string_append (string, "just ");
2223 g_string_append (string, printed_child);
2224 g_free (printed_child);
2227 g_string_append (string, "nothing");
2231 case G_VARIANT_CLASS_ARRAY:
2232 /* it's an array so the first character of the type string is 'a'
2234 * if the first two characters are 'ay' then it's a bytestring.
2235 * under certain conditions we print those as strings.
2237 if (g_variant_get_type_string (value)[1] == 'y')
2243 /* first determine if it is a byte string.
2244 * that's when there's a single nul character: at the end.
2246 str = g_variant_get_data (value);
2247 size = g_variant_get_size (value);
2249 for (i = 0; i < size; i++)
2253 /* first nul byte is the last byte -> it's a byte string. */
2256 gchar *escaped = g_strescape (str, NULL);
2258 /* use double quotes only if a ' is in the string */
2259 if (strchr (str, '\''))
2260 g_string_append_printf (string, "b\"%s\"", escaped);
2262 g_string_append_printf (string, "b'%s'", escaped);
2269 /* fall through and handle normally... */;
2273 * if the first two characters are 'a{' then it's an array of
2274 * dictionary entries (ie: a dictionary) so we print that
2277 if (g_variant_get_type_string (value)[1] == '{')
2280 const gchar *comma = "";
2283 if ((n = g_variant_n_children (value)) == 0)
2286 g_string_append_printf (string, "@%s ",
2287 g_variant_get_type_string (value));
2288 g_string_append (string, "{}");
2292 g_string_append_c (string, '{');
2293 for (i = 0; i < n; i++)
2295 GVariant *entry, *key, *val;
2297 g_string_append (string, comma);
2300 entry = g_variant_get_child_value (value, i);
2301 key = g_variant_get_child_value (entry, 0);
2302 val = g_variant_get_child_value (entry, 1);
2303 g_variant_unref (entry);
2305 g_variant_print_string (key, string, type_annotate);
2306 g_variant_unref (key);
2307 g_string_append (string, ": ");
2308 g_variant_print_string (val, string, type_annotate);
2309 g_variant_unref (val);
2310 type_annotate = FALSE;
2312 g_string_append_c (string, '}');
2315 /* normal (non-dictionary) array */
2317 const gchar *comma = "";
2320 if ((n = g_variant_n_children (value)) == 0)
2323 g_string_append_printf (string, "@%s ",
2324 g_variant_get_type_string (value));
2325 g_string_append (string, "[]");
2329 g_string_append_c (string, '[');
2330 for (i = 0; i < n; i++)
2334 g_string_append (string, comma);
2337 element = g_variant_get_child_value (value, i);
2339 g_variant_print_string (element, string, type_annotate);
2340 g_variant_unref (element);
2341 type_annotate = FALSE;
2343 g_string_append_c (string, ']');
2348 case G_VARIANT_CLASS_TUPLE:
2352 n = g_variant_n_children (value);
2354 g_string_append_c (string, '(');
2355 for (i = 0; i < n; i++)
2359 element = g_variant_get_child_value (value, i);
2360 g_variant_print_string (element, string, type_annotate);
2361 g_string_append (string, ", ");
2362 g_variant_unref (element);
2365 /* for >1 item: remove final ", "
2366 * for 1 item: remove final " ", but leave the ","
2367 * for 0 items: there is only "(", so remove nothing
2369 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2370 g_string_append_c (string, ')');
2374 case G_VARIANT_CLASS_DICT_ENTRY:
2378 g_string_append_c (string, '{');
2380 element = g_variant_get_child_value (value, 0);
2381 g_variant_print_string (element, string, type_annotate);
2382 g_variant_unref (element);
2384 g_string_append (string, ", ");
2386 element = g_variant_get_child_value (value, 1);
2387 g_variant_print_string (element, string, type_annotate);
2388 g_variant_unref (element);
2390 g_string_append_c (string, '}');
2394 case G_VARIANT_CLASS_VARIANT:
2396 GVariant *child = g_variant_get_variant (value);
2398 /* Always annotate types in nested variants, because they are
2399 * (by nature) of variable type.
2401 g_string_append_c (string, '<');
2402 g_variant_print_string (child, string, TRUE);
2403 g_string_append_c (string, '>');
2405 g_variant_unref (child);
2409 case G_VARIANT_CLASS_BOOLEAN:
2410 if (g_variant_get_boolean (value))
2411 g_string_append (string, "true");
2413 g_string_append (string, "false");
2416 case G_VARIANT_CLASS_STRING:
2418 const gchar *str = g_variant_get_string (value, NULL);
2419 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2421 g_string_append_c (string, quote);
2425 gunichar c = g_utf8_get_char (str);
2427 if (c == quote || c == '\\')
2428 g_string_append_c (string, '\\');
2430 if (g_unichar_isprint (c))
2431 g_string_append_unichar (string, c);
2435 g_string_append_c (string, '\\');
2440 g_string_append_c (string, 'a');
2444 g_string_append_c (string, 'b');
2448 g_string_append_c (string, 'f');
2452 g_string_append_c (string, 'n');
2456 g_string_append_c (string, 'r');
2460 g_string_append_c (string, 't');
2464 g_string_append_c (string, 'v');
2468 g_string_append_printf (string, "u%04x", c);
2472 g_string_append_printf (string, "U%08x", c);
2475 str = g_utf8_next_char (str);
2478 g_string_append_c (string, quote);
2482 case G_VARIANT_CLASS_BYTE:
2484 g_string_append (string, "byte ");
2485 g_string_append_printf (string, "0x%02x",
2486 g_variant_get_byte (value));
2489 case G_VARIANT_CLASS_INT16:
2491 g_string_append (string, "int16 ");
2492 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2493 g_variant_get_int16 (value));
2496 case G_VARIANT_CLASS_UINT16:
2498 g_string_append (string, "uint16 ");
2499 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2500 g_variant_get_uint16 (value));
2503 case G_VARIANT_CLASS_INT32:
2504 /* Never annotate this type because it is the default for numbers
2505 * (and this is a *pretty* printer)
2507 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2508 g_variant_get_int32 (value));
2511 case G_VARIANT_CLASS_HANDLE:
2513 g_string_append (string, "handle ");
2514 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2515 g_variant_get_handle (value));
2518 case G_VARIANT_CLASS_UINT32:
2520 g_string_append (string, "uint32 ");
2521 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2522 g_variant_get_uint32 (value));
2525 case G_VARIANT_CLASS_INT64:
2527 g_string_append (string, "int64 ");
2528 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2529 g_variant_get_int64 (value));
2532 case G_VARIANT_CLASS_UINT64:
2534 g_string_append (string, "uint64 ");
2535 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2536 g_variant_get_uint64 (value));
2539 case G_VARIANT_CLASS_FLOAT:
2544 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_float (value));
2546 for (i = 0; buffer[i]; i++)
2547 if (buffer[i] == '.' || buffer[i] == 'e' ||
2548 buffer[i] == 'n' || buffer[i] == 'N')
2551 /* if there is no '.' or 'e' in the float then add one */
2552 if (buffer[i] == '\0')
2560 g_string_append (string, "float ");
2561 g_string_append (string, buffer);
2565 case G_VARIANT_CLASS_DOUBLE:
2570 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2572 for (i = 0; buffer[i]; i++)
2573 if (buffer[i] == '.' || buffer[i] == 'e' ||
2574 buffer[i] == 'n' || buffer[i] == 'N')
2577 /* if there is no '.' or 'e' in the float then add one */
2578 if (buffer[i] == '\0')
2585 g_string_append (string, buffer);
2589 case G_VARIANT_CLASS_OBJECT_PATH:
2591 g_string_append (string, "objectpath ");
2592 g_string_append_printf (string, "\'%s\'",
2593 g_variant_get_string (value, NULL));
2596 case G_VARIANT_CLASS_SIGNATURE:
2598 g_string_append (string, "signature ");
2599 g_string_append_printf (string, "\'%s\'",
2600 g_variant_get_string (value, NULL));
2604 g_assert_not_reached ();
2612 * @value: a #GVariant
2613 * @type_annotate: %TRUE if type information should be included in
2616 * Pretty-prints @value in the format understood by g_variant_parse().
2618 * The format is described [here][gvariant-text].
2620 * If @type_annotate is %TRUE, then type information is included in
2623 * Returns: (transfer full): a newly-allocated string holding the result.
2628 g_variant_print (GVariant *value,
2629 gboolean type_annotate)
2631 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2635 /* Hash, Equal, Compare {{{1 */
2638 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2640 * Generates a hash value for a #GVariant instance.
2642 * The output of this function is guaranteed to be the same for a given
2643 * value only per-process. It may change between different processor
2644 * architectures or even different versions of GLib. Do not use this
2645 * function as a basis for building protocols or file formats.
2647 * The type of @value is #gconstpointer only to allow use of this
2648 * function with #GHashTable. @value must be a #GVariant.
2650 * Returns: a hash value corresponding to @value
2655 g_variant_hash (gconstpointer value_)
2657 GVariant *value = (GVariant *) value_;
2659 switch (g_variant_classify (value))
2661 case G_VARIANT_CLASS_STRING:
2662 case G_VARIANT_CLASS_OBJECT_PATH:
2663 case G_VARIANT_CLASS_SIGNATURE:
2664 return g_str_hash (g_variant_get_string (value, NULL));
2666 case G_VARIANT_CLASS_BOOLEAN:
2667 /* this is a very odd thing to hash... */
2668 return g_variant_get_boolean (value);
2670 case G_VARIANT_CLASS_BYTE:
2671 return g_variant_get_byte (value);
2673 case G_VARIANT_CLASS_INT16:
2674 case G_VARIANT_CLASS_UINT16:
2678 ptr = g_variant_get_data (value);
2686 case G_VARIANT_CLASS_INT32:
2687 case G_VARIANT_CLASS_UINT32:
2688 case G_VARIANT_CLASS_HANDLE:
2689 case G_VARIANT_CLASS_FLOAT:
2693 ptr = g_variant_get_data (value);
2701 case G_VARIANT_CLASS_INT64:
2702 case G_VARIANT_CLASS_UINT64:
2703 case G_VARIANT_CLASS_DOUBLE:
2704 /* need a separate case for these guys because otherwise
2705 * performance could be quite bad on big endian systems
2710 ptr = g_variant_get_data (value);
2713 return ptr[0] + ptr[1];
2719 g_return_val_if_fail (!g_variant_is_container (value), 0);
2720 g_assert_not_reached ();
2726 * @one: (type GVariant): a #GVariant instance
2727 * @two: (type GVariant): a #GVariant instance
2729 * Checks if @one and @two have the same type and value.
2731 * The types of @one and @two are #gconstpointer only to allow use of
2732 * this function with #GHashTable. They must each be a #GVariant.
2734 * Returns: %TRUE if @one and @two are equal
2739 g_variant_equal (gconstpointer one,
2744 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2746 if (g_variant_get_type_info ((GVariant *) one) !=
2747 g_variant_get_type_info ((GVariant *) two))
2750 /* if both values are trusted to be in their canonical serialised form
2751 * then a simple memcmp() of their serialised data will answer the
2754 * if not, then this might generate a false negative (since it is
2755 * possible for two different byte sequences to represent the same
2756 * value). for now we solve this by pretty-printing both values and
2757 * comparing the result.
2759 if (g_variant_is_trusted ((GVariant *) one) &&
2760 g_variant_is_trusted ((GVariant *) two))
2762 gconstpointer data_one, data_two;
2763 gsize size_one, size_two;
2765 size_one = g_variant_get_size ((GVariant *) one);
2766 size_two = g_variant_get_size ((GVariant *) two);
2768 if (size_one != size_two)
2771 data_one = g_variant_get_data ((GVariant *) one);
2772 data_two = g_variant_get_data ((GVariant *) two);
2774 equal = memcmp (data_one, data_two, size_one) == 0;
2778 gchar *strone, *strtwo;
2780 strone = g_variant_print ((GVariant *) one, FALSE);
2781 strtwo = g_variant_print ((GVariant *) two, FALSE);
2782 equal = strcmp (strone, strtwo) == 0;
2791 * g_variant_compare:
2792 * @one: (type GVariant): a basic-typed #GVariant instance
2793 * @two: (type GVariant): a #GVariant instance of the same type
2795 * Compares @one and @two.
2797 * The types of @one and @two are #gconstpointer only to allow use of
2798 * this function with #GTree, #GPtrArray, etc. They must each be a
2801 * Comparison is only defined for basic types (ie: booleans, numbers,
2802 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2803 * ordered in the usual way. Strings are in ASCII lexographical order.
2805 * It is a programmer error to attempt to compare container values or
2806 * two values that have types that are not exactly equal. For example,
2807 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2808 * integer. Also note that this function is not particularly
2809 * well-behaved when it comes to comparison of floats; in particular,
2810 * the handling of incomparable values (ie: NaN) is undefined.
2812 * If you only require an equality comparison, g_variant_equal() is more
2815 * Returns: negative value if a < b;
2817 * positive value if a > b.
2822 g_variant_compare (gconstpointer one,
2825 GVariant *a = (GVariant *) one;
2826 GVariant *b = (GVariant *) two;
2828 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2830 switch (g_variant_classify (a))
2832 case G_VARIANT_CLASS_BOOLEAN:
2833 return g_variant_get_boolean (a) -
2834 g_variant_get_boolean (b);
2836 case G_VARIANT_CLASS_BYTE:
2837 return ((gint) g_variant_get_byte (a)) -
2838 ((gint) g_variant_get_byte (b));
2840 case G_VARIANT_CLASS_INT16:
2841 return ((gint) g_variant_get_int16 (a)) -
2842 ((gint) g_variant_get_int16 (b));
2844 case G_VARIANT_CLASS_UINT16:
2845 return ((gint) g_variant_get_uint16 (a)) -
2846 ((gint) g_variant_get_uint16 (b));
2848 case G_VARIANT_CLASS_INT32:
2850 gint32 a_val = g_variant_get_int32 (a);
2851 gint32 b_val = g_variant_get_int32 (b);
2853 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2856 case G_VARIANT_CLASS_UINT32:
2858 guint32 a_val = g_variant_get_uint32 (a);
2859 guint32 b_val = g_variant_get_uint32 (b);
2861 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2864 case G_VARIANT_CLASS_INT64:
2866 gint64 a_val = g_variant_get_int64 (a);
2867 gint64 b_val = g_variant_get_int64 (b);
2869 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2872 case G_VARIANT_CLASS_UINT64:
2874 guint64 a_val = g_variant_get_uint64 (a);
2875 guint64 b_val = g_variant_get_uint64 (b);
2877 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2880 case G_VARIANT_CLASS_FLOAT:
2882 gfloat a_val = g_variant_get_float (a);
2883 gfloat b_val = g_variant_get_float (b);
2885 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2888 case G_VARIANT_CLASS_DOUBLE:
2890 gdouble a_val = g_variant_get_double (a);
2891 gdouble b_val = g_variant_get_double (b);
2893 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2896 case G_VARIANT_CLASS_STRING:
2897 case G_VARIANT_CLASS_OBJECT_PATH:
2898 case G_VARIANT_CLASS_SIGNATURE:
2899 return strcmp (g_variant_get_string (a, NULL),
2900 g_variant_get_string (b, NULL));
2903 g_return_val_if_fail (!g_variant_is_container (a), 0);
2904 g_assert_not_reached ();
2908 /* GVariantIter {{{1 */
2910 * GVariantIter: (skip)
2912 * #GVariantIter is an opaque data structure and can only be accessed
2913 * using the following functions.
2920 const gchar *loop_format;
2926 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2930 struct stack_iter iter;
2932 GVariant *value_ref;
2936 #define GVSI(i) ((struct stack_iter *) (i))
2937 #define GVHI(i) ((struct heap_iter *) (i))
2938 #define GVSI_MAGIC ((gsize) 3579507750u)
2939 #define GVHI_MAGIC ((gsize) 1450270775u)
2940 #define is_valid_iter(i) (i != NULL && \
2941 GVSI(i)->magic == GVSI_MAGIC)
2942 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2946 * g_variant_iter_new:
2947 * @value: a container #GVariant
2949 * Creates a heap-allocated #GVariantIter for iterating over the items
2952 * Use g_variant_iter_free() to free the return value when you no longer
2955 * A reference is taken to @value and will be released only when
2956 * g_variant_iter_free() is called.
2958 * Returns: (transfer full): a new heap-allocated #GVariantIter
2963 g_variant_iter_new (GVariant *value)
2967 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2968 GVHI(iter)->value_ref = g_variant_ref (value);
2969 GVHI(iter)->magic = GVHI_MAGIC;
2971 g_variant_iter_init (iter, value);
2977 * g_variant_iter_init: (skip)
2978 * @iter: a pointer to a #GVariantIter
2979 * @value: a container #GVariant
2981 * Initialises (without allocating) a #GVariantIter. @iter may be
2982 * completely uninitialised prior to this call; its old value is
2985 * The iterator remains valid for as long as @value exists, and need not
2986 * be freed in any way.
2988 * Returns: the number of items in @value
2993 g_variant_iter_init (GVariantIter *iter,
2996 GVSI(iter)->magic = GVSI_MAGIC;
2997 GVSI(iter)->value = value;
2998 GVSI(iter)->n = g_variant_n_children (value);
3000 GVSI(iter)->loop_format = NULL;
3002 return GVSI(iter)->n;
3006 * g_variant_iter_copy:
3007 * @iter: a #GVariantIter
3009 * Creates a new heap-allocated #GVariantIter to iterate over the
3010 * container that was being iterated over by @iter. Iteration begins on
3011 * the new iterator from the current position of the old iterator but
3012 * the two copies are independent past that point.
3014 * Use g_variant_iter_free() to free the return value when you no longer
3017 * A reference is taken to the container that @iter is iterating over
3018 * and will be releated only when g_variant_iter_free() is called.
3020 * Returns: (transfer full): a new heap-allocated #GVariantIter
3025 g_variant_iter_copy (GVariantIter *iter)
3029 g_return_val_if_fail (is_valid_iter (iter), 0);
3031 copy = g_variant_iter_new (GVSI(iter)->value);
3032 GVSI(copy)->i = GVSI(iter)->i;
3038 * g_variant_iter_n_children:
3039 * @iter: a #GVariantIter
3041 * Queries the number of child items in the container that we are
3042 * iterating over. This is the total number of items -- not the number
3043 * of items remaining.
3045 * This function might be useful for preallocation of arrays.
3047 * Returns: the number of children in the container
3052 g_variant_iter_n_children (GVariantIter *iter)
3054 g_return_val_if_fail (is_valid_iter (iter), 0);
3056 return GVSI(iter)->n;
3060 * g_variant_iter_free:
3061 * @iter: (transfer full): a heap-allocated #GVariantIter
3063 * Frees a heap-allocated #GVariantIter. Only call this function on
3064 * iterators that were returned by g_variant_iter_new() or
3065 * g_variant_iter_copy().
3070 g_variant_iter_free (GVariantIter *iter)
3072 g_return_if_fail (is_valid_heap_iter (iter));
3074 g_variant_unref (GVHI(iter)->value_ref);
3075 GVHI(iter)->magic = 0;
3077 g_slice_free (struct heap_iter, GVHI(iter));
3081 * g_variant_iter_next_value:
3082 * @iter: a #GVariantIter
3084 * Gets the next item in the container. If no more items remain then
3085 * %NULL is returned.
3087 * Use g_variant_unref() to drop your reference on the return value when
3088 * you no longer need it.
3090 * Here is an example for iterating with g_variant_iter_next_value():
3091 * |[<!-- language="C" -->
3092 * // recursively iterate a container
3094 * iterate_container_recursive (GVariant *container)
3096 * GVariantIter iter;
3099 * g_variant_iter_init (&iter, container);
3100 * while ((child = g_variant_iter_next_value (&iter)))
3102 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3104 * if (g_variant_is_container (child))
3105 * iterate_container_recursive (child);
3107 * g_variant_unref (child);
3112 * Returns: (allow-none) (transfer full): a #GVariant, or %NULL
3117 g_variant_iter_next_value (GVariantIter *iter)
3119 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3121 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3123 g_critical ("g_variant_iter_next_value: must not be called again "
3124 "after NULL has already been returned.");
3130 if (GVSI(iter)->i < GVSI(iter)->n)
3131 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3136 /* GVariantBuilder {{{1 */
3140 * A utility type for constructing container-type #GVariant instances.
3142 * This is an opaque structure and may only be accessed using the
3143 * following functions.
3145 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3146 * access it from more than one thread.
3149 struct stack_builder
3151 GVariantBuilder *parent;
3154 /* type constraint explicitly specified by 'type'.
3155 * for tuple types, this moves along as we add more items.
3157 const GVariantType *expected_type;
3159 /* type constraint implied by previous array item.
3161 const GVariantType *prev_item_type;
3163 /* constraints on the number of children. max = -1 for unlimited. */
3167 /* dynamically-growing pointer array */
3168 GVariant **children;
3169 gsize allocated_children;
3172 /* set to '1' if all items in the container will have the same type
3173 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3175 guint uniform_item_types : 1;
3177 /* set to '1' initially and changed to '0' if an untrusted value is
3185 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3189 GVariantBuilder builder;
3195 #define GVSB(b) ((struct stack_builder *) (b))
3196 #define GVHB(b) ((struct heap_builder *) (b))
3197 #define GVSB_MAGIC ((gsize) 1033660112u)
3198 #define GVHB_MAGIC ((gsize) 3087242682u)
3199 #define is_valid_builder(b) (b != NULL && \
3200 GVSB(b)->magic == GVSB_MAGIC)
3201 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3204 * g_variant_builder_new:
3205 * @type: a container type
3207 * Allocates and initialises a new #GVariantBuilder.
3209 * You should call g_variant_builder_unref() on the return value when it
3210 * is no longer needed. The memory will not be automatically freed by
3213 * In most cases it is easier to place a #GVariantBuilder directly on
3214 * the stack of the calling function and initialise it with
3215 * g_variant_builder_init().
3217 * Returns: (transfer full): a #GVariantBuilder
3222 g_variant_builder_new (const GVariantType *type)
3224 GVariantBuilder *builder;
3226 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3227 g_variant_builder_init (builder, type);
3228 GVHB(builder)->magic = GVHB_MAGIC;
3229 GVHB(builder)->ref_count = 1;
3235 * g_variant_builder_unref:
3236 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3238 * Decreases the reference count on @builder.
3240 * In the event that there are no more references, releases all memory
3241 * associated with the #GVariantBuilder.
3243 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3244 * things will happen.
3249 g_variant_builder_unref (GVariantBuilder *builder)
3251 g_return_if_fail (is_valid_heap_builder (builder));
3253 if (--GVHB(builder)->ref_count)
3256 g_variant_builder_clear (builder);
3257 GVHB(builder)->magic = 0;
3259 g_slice_free (struct heap_builder, GVHB(builder));
3263 * g_variant_builder_ref:
3264 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3266 * Increases the reference count on @builder.
3268 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3269 * things will happen.
3271 * Returns: (transfer full): a new reference to @builder
3276 g_variant_builder_ref (GVariantBuilder *builder)
3278 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3280 GVHB(builder)->ref_count++;
3286 * g_variant_builder_clear: (skip)
3287 * @builder: a #GVariantBuilder
3289 * Releases all memory associated with a #GVariantBuilder without
3290 * freeing the #GVariantBuilder structure itself.
3292 * It typically only makes sense to do this on a stack-allocated
3293 * #GVariantBuilder if you want to abort building the value part-way
3294 * through. This function need not be called if you call
3295 * g_variant_builder_end() and it also doesn't need to be called on
3296 * builders allocated with g_variant_builder_new (see
3297 * g_variant_builder_unref() for that).
3299 * This function leaves the #GVariantBuilder structure set to all-zeros.
3300 * It is valid to call this function on either an initialised
3301 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3302 * to call this function on uninitialised memory.
3307 g_variant_builder_clear (GVariantBuilder *builder)
3311 if (GVSB(builder)->magic == 0)
3312 /* all-zeros case */
3315 g_return_if_fail (is_valid_builder (builder));
3317 g_variant_type_free (GVSB(builder)->type);
3319 for (i = 0; i < GVSB(builder)->offset; i++)
3320 g_variant_unref (GVSB(builder)->children[i]);
3322 g_free (GVSB(builder)->children);
3324 if (GVSB(builder)->parent)
3326 g_variant_builder_clear (GVSB(builder)->parent);
3327 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3330 memset (builder, 0, sizeof (GVariantBuilder));
3334 * g_variant_builder_init: (skip)
3335 * @builder: a #GVariantBuilder
3336 * @type: a container type
3338 * Initialises a #GVariantBuilder structure.
3340 * @type must be non-%NULL. It specifies the type of container to
3341 * construct. It can be an indefinite type such as
3342 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3343 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3346 * After the builder is initialised, values are added using
3347 * g_variant_builder_add_value() or g_variant_builder_add().
3349 * After all the child values are added, g_variant_builder_end() frees
3350 * the memory associated with the builder and returns the #GVariant that
3353 * This function completely ignores the previous contents of @builder.
3354 * On one hand this means that it is valid to pass in completely
3355 * uninitialised memory. On the other hand, this means that if you are
3356 * initialising over top of an existing #GVariantBuilder you need to
3357 * first call g_variant_builder_clear() in order to avoid leaking
3360 * You must not call g_variant_builder_ref() or
3361 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3362 * with this function. If you ever pass a reference to a
3363 * #GVariantBuilder outside of the control of your own code then you
3364 * should assume that the person receiving that reference may try to use
3365 * reference counting; you should use g_variant_builder_new() instead of
3371 g_variant_builder_init (GVariantBuilder *builder,
3372 const GVariantType *type)
3374 g_return_if_fail (type != NULL);
3375 g_return_if_fail (g_variant_type_is_container (type));
3377 memset (builder, 0, sizeof (GVariantBuilder));
3379 GVSB(builder)->type = g_variant_type_copy (type);
3380 GVSB(builder)->magic = GVSB_MAGIC;
3381 GVSB(builder)->trusted = TRUE;
3383 switch (*(const gchar *) type)
3385 case G_VARIANT_CLASS_VARIANT:
3386 GVSB(builder)->uniform_item_types = TRUE;
3387 GVSB(builder)->allocated_children = 1;
3388 GVSB(builder)->expected_type = NULL;
3389 GVSB(builder)->min_items = 1;
3390 GVSB(builder)->max_items = 1;
3393 case G_VARIANT_CLASS_ARRAY:
3394 GVSB(builder)->uniform_item_types = TRUE;
3395 GVSB(builder)->allocated_children = 8;
3396 GVSB(builder)->expected_type =
3397 g_variant_type_element (GVSB(builder)->type);
3398 GVSB(builder)->min_items = 0;
3399 GVSB(builder)->max_items = -1;
3402 case G_VARIANT_CLASS_MAYBE:
3403 GVSB(builder)->uniform_item_types = TRUE;
3404 GVSB(builder)->allocated_children = 1;
3405 GVSB(builder)->expected_type =
3406 g_variant_type_element (GVSB(builder)->type);
3407 GVSB(builder)->min_items = 0;
3408 GVSB(builder)->max_items = 1;
3411 case G_VARIANT_CLASS_DICT_ENTRY:
3412 GVSB(builder)->uniform_item_types = FALSE;
3413 GVSB(builder)->allocated_children = 2;
3414 GVSB(builder)->expected_type =
3415 g_variant_type_key (GVSB(builder)->type);
3416 GVSB(builder)->min_items = 2;
3417 GVSB(builder)->max_items = 2;
3420 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3421 GVSB(builder)->uniform_item_types = FALSE;
3422 GVSB(builder)->allocated_children = 8;
3423 GVSB(builder)->expected_type = NULL;
3424 GVSB(builder)->min_items = 0;
3425 GVSB(builder)->max_items = -1;
3428 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3429 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3430 GVSB(builder)->expected_type =
3431 g_variant_type_first (GVSB(builder)->type);
3432 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3433 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3434 GVSB(builder)->uniform_item_types = FALSE;
3438 g_assert_not_reached ();
3441 GVSB(builder)->children = g_new (GVariant *,
3442 GVSB(builder)->allocated_children);
3446 g_variant_builder_make_room (struct stack_builder *builder)
3448 if (builder->offset == builder->allocated_children)
3450 builder->allocated_children *= 2;
3451 builder->children = g_renew (GVariant *, builder->children,
3452 builder->allocated_children);
3457 * g_variant_builder_add_value:
3458 * @builder: a #GVariantBuilder
3459 * @value: a #GVariant
3461 * Adds @value to @builder.
3463 * It is an error to call this function in any way that would create an
3464 * inconsistent value to be constructed. Some examples of this are
3465 * putting different types of items into an array, putting the wrong
3466 * types or number of items in a tuple, putting more than one value into
3469 * If @value is a floating reference (see g_variant_ref_sink()),
3470 * the @builder instance takes ownership of @value.
3475 g_variant_builder_add_value (GVariantBuilder *builder,
3478 g_return_if_fail (is_valid_builder (builder));
3479 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3480 g_return_if_fail (!GVSB(builder)->expected_type ||
3481 g_variant_is_of_type (value,
3482 GVSB(builder)->expected_type));
3483 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3484 g_variant_is_of_type (value,
3485 GVSB(builder)->prev_item_type));
3487 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3489 if (!GVSB(builder)->uniform_item_types)
3491 /* advance our expected type pointers */
3492 if (GVSB(builder)->expected_type)
3493 GVSB(builder)->expected_type =
3494 g_variant_type_next (GVSB(builder)->expected_type);
3496 if (GVSB(builder)->prev_item_type)
3497 GVSB(builder)->prev_item_type =
3498 g_variant_type_next (GVSB(builder)->prev_item_type);
3501 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3503 g_variant_builder_make_room (GVSB(builder));
3505 GVSB(builder)->children[GVSB(builder)->offset++] =
3506 g_variant_ref_sink (value);
3510 * g_variant_builder_open:
3511 * @builder: a #GVariantBuilder
3512 * @type: a #GVariantType
3514 * Opens a subcontainer inside the given @builder. When done adding
3515 * items to the subcontainer, g_variant_builder_close() must be called.
3517 * It is an error to call this function in any way that would cause an
3518 * inconsistent value to be constructed (ie: adding too many values or
3519 * a value of an incorrect type).
3524 g_variant_builder_open (GVariantBuilder *builder,
3525 const GVariantType *type)
3527 GVariantBuilder *parent;
3529 g_return_if_fail (is_valid_builder (builder));
3530 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3531 g_return_if_fail (!GVSB(builder)->expected_type ||
3532 g_variant_type_is_subtype_of (type,
3533 GVSB(builder)->expected_type));
3534 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3535 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3538 parent = g_slice_dup (GVariantBuilder, builder);
3539 g_variant_builder_init (builder, type);
3540 GVSB(builder)->parent = parent;
3542 /* push the prev_item_type down into the subcontainer */
3543 if (GVSB(parent)->prev_item_type)
3545 if (!GVSB(builder)->uniform_item_types)
3546 /* tuples and dict entries */
3547 GVSB(builder)->prev_item_type =
3548 g_variant_type_first (GVSB(parent)->prev_item_type);
3550 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3551 /* maybes and arrays */
3552 GVSB(builder)->prev_item_type =
3553 g_variant_type_element (GVSB(parent)->prev_item_type);
3558 * g_variant_builder_close:
3559 * @builder: a #GVariantBuilder
3561 * Closes the subcontainer inside the given @builder that was opened by
3562 * the most recent call to g_variant_builder_open().
3564 * It is an error to call this function in any way that would create an
3565 * inconsistent value to be constructed (ie: too few values added to the
3571 g_variant_builder_close (GVariantBuilder *builder)
3573 GVariantBuilder *parent;
3575 g_return_if_fail (is_valid_builder (builder));
3576 g_return_if_fail (GVSB(builder)->parent != NULL);
3578 parent = GVSB(builder)->parent;
3579 GVSB(builder)->parent = NULL;
3581 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3584 g_slice_free (GVariantBuilder, parent);
3588 * g_variant_make_maybe_type:
3589 * @element: a #GVariant
3591 * Return the type of a maybe containing @element.
3593 static GVariantType *
3594 g_variant_make_maybe_type (GVariant *element)
3596 return g_variant_type_new_maybe (g_variant_get_type (element));
3600 * g_variant_make_array_type:
3601 * @element: a #GVariant
3603 * Return the type of an array containing @element.
3605 static GVariantType *
3606 g_variant_make_array_type (GVariant *element)
3608 return g_variant_type_new_array (g_variant_get_type (element));
3612 * g_variant_builder_end:
3613 * @builder: a #GVariantBuilder
3615 * Ends the builder process and returns the constructed value.
3617 * It is not permissible to use @builder in any way after this call
3618 * except for reference counting operations (in the case of a
3619 * heap-allocated #GVariantBuilder) or by reinitialising it with
3620 * g_variant_builder_init() (in the case of stack-allocated).
3622 * It is an error to call this function in any way that would create an
3623 * inconsistent value to be constructed (ie: insufficient number of
3624 * items added to a container with a specific number of children
3625 * required). It is also an error to call this function if the builder
3626 * was created with an indefinite array or maybe type and no children
3627 * have been added; in this case it is impossible to infer the type of
3630 * Returns: (transfer none): a new, floating, #GVariant
3635 g_variant_builder_end (GVariantBuilder *builder)
3637 GVariantType *my_type;
3640 g_return_val_if_fail (is_valid_builder (builder), NULL);
3641 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3643 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3644 GVSB(builder)->prev_item_type != NULL ||
3645 g_variant_type_is_definite (GVSB(builder)->type),
3648 if (g_variant_type_is_definite (GVSB(builder)->type))
3649 my_type = g_variant_type_copy (GVSB(builder)->type);
3651 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3652 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3654 else if (g_variant_type_is_array (GVSB(builder)->type))
3655 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3657 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3658 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3659 GVSB(builder)->offset);
3661 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3662 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3663 GVSB(builder)->children[1]);
3665 g_assert_not_reached ();
3667 value = g_variant_new_from_children (g_variant_type_info_get (my_type),
3668 g_renew (GVariant *,
3669 GVSB(builder)->children,
3670 GVSB(builder)->offset),
3671 GVSB(builder)->offset,
3672 GVSB(builder)->trusted);
3673 GVSB(builder)->children = NULL;
3674 GVSB(builder)->offset = 0;
3676 g_variant_builder_clear (builder);
3677 g_variant_type_free (my_type);
3682 /* GVariantDict {{{1 */
3687 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3689 * It can be used for doing a sequence of dictionary lookups in an
3690 * efficient way on an existing #GVariant dictionary or it can be used
3691 * to construct new dictionaries with a hashtable-like interface. It
3692 * can also be used for taking existing dictionaries and modifying them
3693 * in order to create new ones.
3695 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3698 * It is possible to use #GVariantDict allocated on the stack or on the
3699 * heap. When using a stack-allocated #GVariantDict, you begin with a
3700 * call to g_variant_dict_init() and free the resources with a call to
3701 * g_variant_dict_clear().
3703 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3704 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3705 * and g_variant_dict_unref().
3707 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3708 * dictionary-type #GVariant. When used with stack-allocated instances,
3709 * this also implicitly frees all associated memory, but for
3710 * heap-allocated instances, you must still call g_variant_dict_unref()
3713 * You will typically want to use a heap-allocated #GVariantDict when
3714 * you expose it as part of an API. For most other uses, the
3715 * stack-allocated form will be more convenient.
3717 * Consider the following two examples that do the same thing in each
3718 * style: take an existing dictionary and look up the "count" uint32
3719 * key, adding 1 to it if it is found, or returning an error if the
3720 * key is not found. Each returns the new dictionary as a floating
3723 * ## Using a stack-allocated GVariantDict
3725 * |[<!-- language="C" -->
3727 * add_to_count (GVariant *orig,
3730 * GVariantDict dict;
3733 * g_variant_dict_init (&dict, orig);
3734 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3736 * g_set_error (...);
3737 * g_variant_dict_clear (&dict);
3741 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3743 * return g_variant_dict_end (&dict);
3747 * ## Using heap-allocated GVariantDict
3749 * |[<!-- language="C" -->
3751 * add_to_count (GVariant *orig,
3754 * GVariantDict *dict;
3758 * dict = g_variant_dict_new (orig);
3760 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3762 * g_variant_dict_insert (dict, "count", "u", count + 1);
3763 * result = g_variant_dict_end (dict);
3767 * g_set_error (...);
3771 * g_variant_dict_unref (dict);
3785 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3789 struct stack_dict dict;
3794 #define GVSD(d) ((struct stack_dict *) (d))
3795 #define GVHD(d) ((struct heap_dict *) (d))
3796 #define GVSD_MAGIC ((gsize) 2579507750u)
3797 #define GVHD_MAGIC ((gsize) 2450270775u)
3798 #define is_valid_dict(d) (d != NULL && \
3799 GVSD(d)->magic == GVSD_MAGIC)
3800 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3803 * g_variant_dict_new:
3804 * @from_asv: (allow-none): the #GVariant with which to initialise the
3807 * Allocates and initialises a new #GVariantDict.
3809 * You should call g_variant_dict_unref() on the return value when it
3810 * is no longer needed. The memory will not be automatically freed by
3813 * In some cases it may be easier to place a #GVariantDict directly on
3814 * the stack of the calling function and initialise it with
3815 * g_variant_dict_init(). This is particularly useful when you are
3816 * using #GVariantDict to construct a #GVariant.
3818 * Returns: (transfer full): a #GVariantDict
3823 g_variant_dict_new (GVariant *from_asv)
3827 dict = g_slice_alloc (sizeof (struct heap_dict));
3828 g_variant_dict_init (dict, from_asv);
3829 GVHD(dict)->magic = GVHD_MAGIC;
3830 GVHD(dict)->ref_count = 1;
3836 * g_variant_dict_init: (skip)
3837 * @dict: a #GVariantDict
3838 * @from_asv: (allow-none): the initial value for @dict
3840 * Initialises a #GVariantDict structure.
3842 * If @from_asv is given, it is used to initialise the dictionary.
3844 * This function completely ignores the previous contents of @dict. On
3845 * one hand this means that it is valid to pass in completely
3846 * uninitialised memory. On the other hand, this means that if you are
3847 * initialising over top of an existing #GVariantDict you need to first
3848 * call g_variant_dict_clear() in order to avoid leaking memory.
3850 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3851 * #GVariantDict that was initialised with this function. If you ever
3852 * pass a reference to a #GVariantDict outside of the control of your
3853 * own code then you should assume that the person receiving that
3854 * reference may try to use reference counting; you should use
3855 * g_variant_dict_new() instead of this function.
3860 g_variant_dict_init (GVariantDict *dict,
3867 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3868 GVSD(dict)->magic = GVSD_MAGIC;
3872 g_variant_iter_init (&iter, from_asv);
3873 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3874 g_hash_table_insert (GVSD(dict)->values, key, value);
3879 * g_variant_dict_lookup:
3880 * @dict: a #GVariantDict
3881 * @key: the key to lookup in the dictionary
3882 * @format_string: a GVariant format string
3883 * @...: the arguments to unpack the value into
3885 * Looks up a value in a #GVariantDict.
3887 * This function is a wrapper around g_variant_dict_lookup_value() and
3888 * g_variant_get(). In the case that %NULL would have been returned,
3889 * this function returns %FALSE. Otherwise, it unpacks the returned
3890 * value and returns %TRUE.
3892 * @format_string determines the C types that are used for unpacking the
3893 * values and also determines if the values are copied or borrowed, see the
3894 * section on [GVariant format strings][gvariant-format-strings-pointers].
3896 * Returns: %TRUE if a value was unpacked
3901 g_variant_dict_lookup (GVariantDict *dict,
3903 const gchar *format_string,
3909 g_return_val_if_fail (is_valid_dict (dict), FALSE);
3910 g_return_val_if_fail (key != NULL, FALSE);
3911 g_return_val_if_fail (format_string != NULL, FALSE);
3913 value = g_hash_table_lookup (GVSD(dict)->values, key);
3915 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3918 va_start (ap, format_string);
3919 g_variant_get_va (value, format_string, NULL, &ap);
3926 * g_variant_dict_lookup_value:
3927 * @dict: a #GVariantDict
3928 * @key: the key to lookup in the dictionary
3929 * @expected_type: (allow-none): a #GVariantType, or %NULL
3931 * Looks up a value in a #GVariantDict.
3933 * If @key is not found in @dictionary, %NULL is returned.
3935 * The @expected_type string specifies what type of value is expected.
3936 * If the value associated with @key has a different type then %NULL is
3939 * If the key is found and the value has the correct type, it is
3940 * returned. If @expected_type was specified then any non-%NULL return
3941 * value will have this type.
3943 * Returns: (transfer full): the value of the dictionary key, or %NULL
3948 g_variant_dict_lookup_value (GVariantDict *dict,
3950 const GVariantType *expected_type)
3954 g_return_val_if_fail (is_valid_dict (dict), NULL);
3955 g_return_val_if_fail (key != NULL, NULL);
3957 result = g_hash_table_lookup (GVSD(dict)->values, key);
3959 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
3960 return g_variant_ref (result);
3966 * g_variant_dict_contains:
3967 * @dict: a #GVariantDict
3968 * @key: the key to lookup in the dictionary
3970 * Checks if @key exists in @dict.
3972 * Returns: %TRUE if @key is in @dict
3977 g_variant_dict_contains (GVariantDict *dict,
3980 g_return_val_if_fail (is_valid_dict (dict), FALSE);
3981 g_return_val_if_fail (key != NULL, FALSE);
3983 return g_hash_table_contains (GVSD(dict)->values, key);
3987 * g_variant_dict_insert:
3988 * @dict: a #GVariantDict
3989 * @key: the key to insert a value for
3990 * @format_string: a #GVariant varargs format string
3991 * @...: arguments, as per @format_string
3993 * Inserts a value into a #GVariantDict.
3995 * This call is a convenience wrapper that is exactly equivalent to
3996 * calling g_variant_new() followed by g_variant_dict_insert_value().
4001 g_variant_dict_insert (GVariantDict *dict,
4003 const gchar *format_string,
4008 g_return_if_fail (is_valid_dict (dict));
4009 g_return_if_fail (key != NULL);
4010 g_return_if_fail (format_string != NULL);
4012 va_start (ap, format_string);
4013 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4018 * g_variant_dict_insert_value:
4019 * @dict: a #GVariantDict
4020 * @key: the key to insert a value for
4021 * @value: the value to insert
4023 * Inserts (or replaces) a key in a #GVariantDict.
4025 * @value is consumed if it is floating.
4030 g_variant_dict_insert_value (GVariantDict *dict,
4034 g_return_if_fail (is_valid_dict (dict));
4035 g_return_if_fail (key != NULL);
4036 g_return_if_fail (value != NULL);
4038 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4042 * g_variant_dict_remove:
4043 * @dict: a #GVariantDict
4044 * @key: the key to remove
4046 * Removes a key and its associated value from a #GVariantDict.
4048 * Returns: %TRUE if the key was found and removed
4053 g_variant_dict_remove (GVariantDict *dict,
4056 g_return_val_if_fail (is_valid_dict (dict), FALSE);
4057 g_return_val_if_fail (key != NULL, FALSE);
4059 return g_hash_table_remove (GVSD(dict)->values, key);
4063 * g_variant_dict_clear:
4064 * @dict: a #GVariantDict
4066 * Releases all memory associated with a #GVariantDict without freeing
4067 * the #GVariantDict structure itself.
4069 * It typically only makes sense to do this on a stack-allocated
4070 * #GVariantDict if you want to abort building the value part-way
4071 * through. This function need not be called if you call
4072 * g_variant_dict_end() and it also doesn't need to be called on dicts
4073 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4076 * It is valid to call this function on either an initialised
4077 * #GVariantDict or one that was previously cleared by an earlier call
4078 * to g_variant_dict_clear() but it is not valid to call this function
4079 * on uninitialised memory.
4084 g_variant_dict_clear (GVariantDict *dict)
4086 if (GVSD(dict)->magic == 0)
4087 /* all-zeros case */
4090 g_return_if_fail (is_valid_dict (dict));
4092 g_hash_table_unref (GVSD(dict)->values);
4093 GVSD(dict)->values = NULL;
4095 GVSD(dict)->magic = 0;
4099 * g_variant_dict_end:
4100 * @dict: a #GVariantDict
4102 * Returns the current value of @dict as a #GVariant of type
4103 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4105 * It is not permissible to use @dict in any way after this call except
4106 * for reference counting operations (in the case of a heap-allocated
4107 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4108 * the case of stack-allocated).
4110 * Returns: (transfer none): a new, floating, #GVariant
4115 g_variant_dict_end (GVariantDict *dict)
4117 GVariantBuilder builder;
4118 GHashTableIter iter;
4119 gpointer key, value;
4121 g_return_val_if_fail (is_valid_dict (dict), NULL);
4123 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4125 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4126 while (g_hash_table_iter_next (&iter, &key, &value))
4127 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4129 g_variant_dict_clear (dict);
4131 return g_variant_builder_end (&builder);
4135 * g_variant_dict_ref:
4136 * @dict: a heap-allocated #GVariantDict
4138 * Increases the reference count on @dict.
4140 * Don't call this on stack-allocated #GVariantDict instances or bad
4141 * things will happen.
4143 * Returns: (transfer full): a new reference to @dict
4148 g_variant_dict_ref (GVariantDict *dict)
4150 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4152 GVHD(dict)->ref_count++;
4158 * g_variant_dict_unref:
4159 * @dict: (transfer full): a heap-allocated #GVariantDict
4161 * Decreases the reference count on @dict.
4163 * In the event that there are no more references, releases all memory
4164 * associated with the #GVariantDict.
4166 * Don't call this on stack-allocated #GVariantDict instances or bad
4167 * things will happen.
4172 g_variant_dict_unref (GVariantDict *dict)
4174 g_return_if_fail (is_valid_heap_dict (dict));
4176 if (--GVHD(dict)->ref_count == 0)
4178 g_variant_dict_clear (dict);
4179 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4184 /* Format strings {{{1 */
4186 * g_variant_format_string_scan:
4187 * @string: a string that may be prefixed with a format string
4188 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
4190 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4193 * Checks the string pointed to by @string for starting with a properly
4194 * formed #GVariant varargs format string. If no valid format string is
4195 * found then %FALSE is returned.
4197 * If @string does start with a valid format string then %TRUE is
4198 * returned. If @endptr is non-%NULL then it is updated to point to the
4199 * first character after the format string.
4201 * If @limit is non-%NULL then @limit (and any charater after it) will
4202 * not be accessed and the effect is otherwise equivalent to if the
4203 * character at @limit were nul.
4205 * See the section on [GVariant format strings][gvariant-format-strings].
4207 * Returns: %TRUE if there was a valid format string
4212 g_variant_format_string_scan (const gchar *string,
4214 const gchar **endptr)
4216 #define next_char() (string == limit ? '\0' : *string++)
4217 #define peek_char() (string == limit ? '\0' : *string)
4220 switch (next_char())
4222 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4223 case 'x': case 't': case 'h': case 'f': case 'd': case 's':
4224 case 'o': case 'g': case 'v': case '*': case '?': case 'r':
4228 return g_variant_format_string_scan (string, limit, endptr);
4232 return g_variant_type_string_scan (string, limit, endptr);
4235 while (peek_char() != ')')
4236 if (!g_variant_format_string_scan (string, limit, &string))
4239 next_char(); /* consume ')' */
4249 if (c != 's' && c != 'o' && c != 'g')
4257 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4258 * The terminating null character is considered to be
4259 * part of the string.
4261 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4265 if (!g_variant_format_string_scan (string, limit, &string))
4268 if (next_char() != '}')
4274 if ((c = next_char()) == 'a')
4276 if ((c = next_char()) == '&')
4278 if ((c = next_char()) == 'a')
4280 if ((c = next_char()) == 'y')
4281 break; /* '^a&ay' */
4284 else if (c == 's' || c == 'o')
4285 break; /* '^a&s', '^a&o' */
4290 if ((c = next_char()) == 'y')
4294 else if (c == 's' || c == 'o')
4295 break; /* '^as', '^ao' */
4302 if ((c = next_char()) == 'a')
4304 if ((c = next_char()) == 'y')
4314 if (c != 's' && c != 'o' && c != 'g')
4333 * g_variant_check_format_string:
4334 * @value: a #GVariant
4335 * @format_string: a valid #GVariant format string
4336 * @copy_only: %TRUE to ensure the format string makes deep copies
4338 * Checks if calling g_variant_get() with @format_string on @value would
4339 * be valid from a type-compatibility standpoint. @format_string is
4340 * assumed to be a valid format string (from a syntactic standpoint).
4342 * If @copy_only is %TRUE then this function additionally checks that it
4343 * would be safe to call g_variant_unref() on @value immediately after
4344 * the call to g_variant_get() without invalidating the result. This is
4345 * only possible if deep copies are made (ie: there are no pointers to
4346 * the data inside of the soon-to-be-freed #GVariant instance). If this
4347 * check fails then a g_critical() is printed and %FALSE is returned.
4349 * This function is meant to be used by functions that wish to provide
4350 * varargs accessors to #GVariant values of uncertain values (eg:
4351 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4353 * Returns: %TRUE if @format_string is safe to use
4358 g_variant_check_format_string (GVariant *value,
4359 const gchar *format_string,
4362 const gchar *original_format = format_string;
4363 const gchar *type_string;
4365 /* Interesting factoid: assuming a format string is valid, it can be
4366 * converted to a type string by removing all '@' '&' and '^'
4369 * Instead of doing that, we can just skip those characters when
4370 * comparing it to the type string of @value.
4372 * For the copy-only case we can just drop the '&' from the list of
4373 * characters to skip over. A '&' will never appear in a type string
4374 * so we know that it won't be possible to return %TRUE if it is in a
4377 type_string = g_variant_get_type_string (value);
4379 while (*type_string || *format_string)
4381 gchar format = *format_string++;
4386 if G_UNLIKELY (copy_only)
4388 /* for the love of all that is good, please don't mark this string for translation... */
4389 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4390 "interface to validate the passed format string for type safety. The passed format "
4391 "(%s) contains a '&' character which would result in a pointer being returned to the "
4392 "data inside of a GVariant instance that may no longer exist by the time the function "
4393 "returns. Modify your code to use a format string without '&'.", original_format);
4400 /* ignore these 2 (or 3) */
4404 /* attempt to consume one of 'bynqiuxthdsog' */
4406 char s = *type_string++;
4408 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4414 /* ensure it's a tuple */
4415 if (*type_string != '(')
4420 /* consume a full type string for the '*' or 'r' */
4421 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4427 /* attempt to consume exactly one character equal to the format */
4428 if (format != *type_string++)
4437 * g_variant_format_string_scan_type:
4438 * @string: a string that may be prefixed with a format string
4439 * @limit: (allow-none) (default NULL): a pointer to the end of @string,
4441 * @endptr: (allow-none) (default NULL): location to store the end pointer,
4444 * If @string starts with a valid format string then this function will
4445 * return the type that the format string corresponds to. Otherwise
4446 * this function returns %NULL.
4448 * Use g_variant_type_free() to free the return value when you no longer
4451 * This function is otherwise exactly like
4452 * g_variant_format_string_scan().
4454 * Returns: (allow-none): a #GVariantType if there was a valid format string
4459 g_variant_format_string_scan_type (const gchar *string,
4461 const gchar **endptr)
4463 const gchar *my_end;
4470 if (!g_variant_format_string_scan (string, limit, endptr))
4473 dest = new = g_malloc (*endptr - string + 1);
4474 while (string != *endptr)
4476 if (*string != '@' && *string != '&' && *string != '^')
4482 return (GVariantType *) G_VARIANT_TYPE (new);
4486 valid_format_string (const gchar *format_string,
4490 const gchar *endptr;
4493 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4495 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4498 g_critical ("'%s' is not a valid GVariant format string",
4501 g_critical ("'%s' does not have a valid GVariant format "
4502 "string as a prefix", format_string);
4505 g_variant_type_free (type);
4510 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4515 fragment = g_strndup (format_string, endptr - format_string);
4516 typestr = g_variant_type_dup_string (type);
4518 g_critical ("the GVariant format string '%s' has a type of "
4519 "'%s' but the given value has a type of '%s'",
4520 fragment, typestr, g_variant_get_type_string (value));
4522 g_variant_type_free (type);
4529 g_variant_type_free (type);
4534 /* Variable Arguments {{{1 */
4535 /* We consider 2 main classes of format strings:
4537 * - recursive format strings
4538 * these are ones that result in recursion and the collection of
4539 * possibly more than one argument. Maybe types, tuples,
4540 * dictionary entries.
4542 * - leaf format string
4543 * these result in the collection of a single argument.
4545 * Leaf format strings are further subdivided into two categories:
4547 * - single non-null pointer ("nnp")
4548 * these either collect or return a single non-null pointer.
4551 * these collect or return something else (bool, number, etc).
4553 * Based on the above, the varargs handling code is split into 4 main parts:
4555 * - nnp handling code
4556 * - leaf handling code (which may invoke nnp code)
4557 * - generic handling code (may be recursive, may invoke leaf code)
4558 * - user-facing API (which invokes the generic code)
4560 * Each section implements some of the following functions:
4563 * collect the arguments for the format string as if
4564 * g_variant_new() had been called, but do nothing with them. used
4565 * for skipping over arguments when constructing a Nothing maybe
4569 * create a GVariant *
4572 * unpack a GVariant *
4574 * - free (nnp only):
4575 * free a previously allocated item
4579 g_variant_format_string_is_leaf (const gchar *str)
4581 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4585 g_variant_format_string_is_nnp (const gchar *str)
4587 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4588 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4589 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4592 /* Single non-null pointer ("nnp") {{{2 */
4594 g_variant_valist_free_nnp (const gchar *str,
4600 g_variant_iter_free (ptr);
4604 if (str[2] != '&') /* '^as', '^ao' */
4606 else /* '^a&s', '^a&o' */
4620 g_variant_unref (ptr);
4627 g_assert_not_reached ();
4632 g_variant_scan_convenience (const gchar **str,
4655 g_variant_valist_new_nnp (const gchar **str,
4666 const GVariantType *type;
4669 value = g_variant_builder_end (ptr);
4670 type = g_variant_get_type (value);
4672 if G_UNLIKELY (!g_variant_type_is_array (type))
4673 g_error ("g_variant_new: expected array GVariantBuilder but "
4674 "the built value has type '%s'",
4675 g_variant_get_type_string (value));
4677 type = g_variant_type_element (type);
4679 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4680 g_error ("g_variant_new: expected GVariantBuilder array element "
4681 "type '%s' but the built value has element type '%s'",
4682 g_variant_type_dup_string ((GVariantType *) *str),
4683 g_variant_get_type_string (value) + 1);
4685 g_variant_type_string_scan (*str, NULL, str);
4691 /* special case: NULL pointer for empty array */
4693 const GVariantType *type = (GVariantType *) *str;
4695 g_variant_type_string_scan (*str, NULL, str);
4697 if G_UNLIKELY (!g_variant_type_is_definite (type))
4698 g_error ("g_variant_new: NULL pointer given with indefinite "
4699 "array type; unable to determine which type of empty "
4700 "array to construct.");
4702 return g_variant_new_array (type, NULL, 0);
4709 value = g_variant_new_string (ptr);
4712 value = g_variant_new_string ("[Invalid UTF-8]");
4718 return g_variant_new_object_path (ptr);
4721 return g_variant_new_signature (ptr);
4729 type = g_variant_scan_convenience (str, &constant, &arrays);
4732 return g_variant_new_strv (ptr, -1);
4735 return g_variant_new_objv (ptr, -1);
4738 return g_variant_new_bytestring_array (ptr, -1);
4740 return g_variant_new_bytestring (ptr);
4744 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4745 g_error ("g_variant_new: expected GVariant of type '%s' but "
4746 "received value has type '%s'",
4747 g_variant_type_dup_string ((GVariantType *) *str),
4748 g_variant_get_type_string (ptr));
4750 g_variant_type_string_scan (*str, NULL, str);
4758 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4759 g_error ("g_variant_new: format string '?' expects basic-typed "
4760 "GVariant, but received value has type '%s'",
4761 g_variant_get_type_string (ptr));
4766 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4767 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4768 "GVariant, but received value has type '%s'",
4769 g_variant_get_type_string (ptr));
4774 return g_variant_new_variant (ptr);
4777 g_assert_not_reached ();
4782 g_variant_valist_get_nnp (const gchar **str,
4788 g_variant_type_string_scan (*str, NULL, str);
4789 return g_variant_iter_new (value);
4793 return (gchar *) g_variant_get_string (value, NULL);
4798 return g_variant_dup_string (value, NULL);
4806 type = g_variant_scan_convenience (str, &constant, &arrays);
4811 return g_variant_get_strv (value, NULL);
4813 return g_variant_dup_strv (value, NULL);
4816 else if (type == 'o')
4819 return g_variant_get_objv (value, NULL);
4821 return g_variant_dup_objv (value, NULL);
4824 else if (arrays > 1)
4827 return g_variant_get_bytestring_array (value, NULL);
4829 return g_variant_dup_bytestring_array (value, NULL);
4835 return (gchar *) g_variant_get_bytestring (value);
4837 return g_variant_dup_bytestring (value, NULL);
4842 g_variant_type_string_scan (*str, NULL, str);
4848 return g_variant_ref (value);
4851 return g_variant_get_variant (value);
4854 g_assert_not_reached ();
4860 g_variant_valist_skip_leaf (const gchar **str,
4863 if (g_variant_format_string_is_nnp (*str))
4865 g_variant_format_string_scan (*str, NULL, str);
4866 va_arg (*app, gpointer);
4884 va_arg (*app, guint64);
4889 va_arg (*app, gdouble);
4893 g_assert_not_reached ();
4898 g_variant_valist_new_leaf (const gchar **str,
4901 if (g_variant_format_string_is_nnp (*str))
4902 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4907 return g_variant_new_boolean (va_arg (*app, gboolean));
4910 return g_variant_new_byte (va_arg (*app, guint));
4913 return g_variant_new_int16 (va_arg (*app, gint));
4916 return g_variant_new_uint16 (va_arg (*app, guint));
4919 return g_variant_new_int32 (va_arg (*app, gint));
4922 return g_variant_new_uint32 (va_arg (*app, guint));
4925 return g_variant_new_int64 (va_arg (*app, gint64));
4928 return g_variant_new_uint64 (va_arg (*app, guint64));
4931 return g_variant_new_handle (va_arg (*app, gint));
4934 return g_variant_new_float (va_arg (*app, gdouble));
4937 return g_variant_new_double (va_arg (*app, gdouble));
4940 g_assert_not_reached ();
4944 /* The code below assumes this */
4945 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
4946 G_STATIC_ASSERT (sizeof (gfloat) == sizeof (guint32));
4947 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
4950 g_variant_valist_get_leaf (const gchar **str,
4955 gpointer ptr = va_arg (*app, gpointer);
4959 g_variant_format_string_scan (*str, NULL, str);
4963 if (g_variant_format_string_is_nnp (*str))
4965 gpointer *nnp = (gpointer *) ptr;
4967 if (free && *nnp != NULL)
4968 g_variant_valist_free_nnp (*str, *nnp);
4973 *nnp = g_variant_valist_get_nnp (str, value);
4975 g_variant_format_string_scan (*str, NULL, str);
4985 *(gboolean *) ptr = g_variant_get_boolean (value);
4989 *(guchar *) ptr = g_variant_get_byte (value);
4993 *(gint16 *) ptr = g_variant_get_int16 (value);
4997 *(guint16 *) ptr = g_variant_get_uint16 (value);
5001 *(gint32 *) ptr = g_variant_get_int32 (value);
5005 *(guint32 *) ptr = g_variant_get_uint32 (value);
5009 *(gint64 *) ptr = g_variant_get_int64 (value);
5013 *(guint64 *) ptr = g_variant_get_uint64 (value);
5017 *(gint32 *) ptr = g_variant_get_handle (value);
5021 *(gfloat *) ptr = g_variant_get_float (value);
5025 *(gdouble *) ptr = g_variant_get_double (value);
5034 *(guchar *) ptr = 0;
5039 *(guint16 *) ptr = 0;
5047 *(guint32 *) ptr = 0;
5053 *(guint64 *) ptr = 0;
5058 g_assert_not_reached ();
5061 /* Generic (recursive) {{{2 */
5063 g_variant_valist_skip (const gchar **str,
5066 if (g_variant_format_string_is_leaf (*str))
5067 g_variant_valist_skip_leaf (str, app);
5069 else if (**str == 'm') /* maybe */
5073 if (!g_variant_format_string_is_nnp (*str))
5074 va_arg (*app, gboolean);
5076 g_variant_valist_skip (str, app);
5078 else /* tuple, dictionary entry */
5080 g_assert (**str == '(' || **str == '{');
5082 while (**str != ')' && **str != '}')
5083 g_variant_valist_skip (str, app);
5089 g_variant_valist_new (const gchar **str,
5092 if (g_variant_format_string_is_leaf (*str))
5093 return g_variant_valist_new_leaf (str, app);
5095 if (**str == 'm') /* maybe */
5097 GVariantType *type = NULL;
5098 GVariant *value = NULL;
5102 if (g_variant_format_string_is_nnp (*str))
5104 gpointer nnp = va_arg (*app, gpointer);
5107 value = g_variant_valist_new_nnp (str, nnp);
5109 type = g_variant_format_string_scan_type (*str, NULL, str);
5113 gboolean just = va_arg (*app, gboolean);
5116 value = g_variant_valist_new (str, app);
5119 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5120 g_variant_valist_skip (str, app);
5124 value = g_variant_new_maybe (type, value);
5127 g_variant_type_free (type);
5131 else /* tuple, dictionary entry */
5136 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5139 g_assert (**str == '{');
5140 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5144 while (**str != ')' && **str != '}')
5145 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5148 return g_variant_builder_end (&b);
5153 g_variant_valist_get (const gchar **str,
5158 if (g_variant_format_string_is_leaf (*str))
5159 g_variant_valist_get_leaf (str, value, free, app);
5161 else if (**str == 'm')
5166 value = g_variant_get_maybe (value);
5168 if (!g_variant_format_string_is_nnp (*str))
5170 gboolean *ptr = va_arg (*app, gboolean *);
5173 *ptr = value != NULL;
5176 g_variant_valist_get (str, value, free, app);
5179 g_variant_unref (value);
5182 else /* tuple, dictionary entry */
5186 g_assert (**str == '(' || **str == '{');
5189 while (**str != ')' && **str != '}')
5193 GVariant *child = g_variant_get_child_value (value, index++);
5194 g_variant_valist_get (str, child, free, app);
5195 g_variant_unref (child);
5198 g_variant_valist_get (str, NULL, free, app);
5204 /* User-facing API {{{2 */
5206 * g_variant_new: (skip)
5207 * @format_string: a #GVariant format string
5208 * @...: arguments, as per @format_string
5210 * Creates a new #GVariant instance.
5212 * Think of this function as an analogue to g_strdup_printf().
5214 * The type of the created instance and the arguments that are expected
5215 * by this function are determined by @format_string. See the section on
5216 * [GVariant format strings][gvariant-format-strings]. Please note that
5217 * the syntax of the format string is very likely to be extended in the
5220 * The first character of the format string must not be '*' '?' '@' or
5221 * 'r'; in essence, a new #GVariant must always be constructed by this
5222 * function (and not merely passed through it unmodified).
5224 * Note that the arguments must be of the correct width for their types
5225 * specified in @format_string. This can be achieved by casting them. See
5226 * the [GVariant varargs documentation][gvariant-varargs].
5228 * |[<!-- language="C" -->
5229 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5230 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5231 * GVariant *new_variant;
5233 * new_variant = g_variant_new ("(t^as)",
5234 * /<!-- -->* This cast is required. *<!-- -->/
5235 * (guint64) some_flags,
5239 * Returns: a new floating #GVariant instance
5244 g_variant_new (const gchar *format_string,
5250 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5251 format_string[0] != '?' && format_string[0] != '@' &&
5252 format_string[0] != '*' && format_string[0] != 'r',
5255 va_start (ap, format_string);
5256 value = g_variant_new_va (format_string, NULL, &ap);
5263 * g_variant_new_va: (skip)
5264 * @format_string: a string that is prefixed with a format string
5265 * @endptr: (allow-none) (default NULL): location to store the end pointer,
5267 * @app: a pointer to a #va_list
5269 * This function is intended to be used by libraries based on
5270 * #GVariant that want to provide g_variant_new()-like functionality
5273 * The API is more general than g_variant_new() to allow a wider range
5276 * @format_string must still point to a valid format string, but it only
5277 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5278 * non-%NULL then it is updated to point to the first character past the
5279 * end of the format string.
5281 * @app is a pointer to a #va_list. The arguments, according to
5282 * @format_string, are collected from this #va_list and the list is left
5283 * pointing to the argument following the last.
5285 * Note that the arguments in @app must be of the correct width for their
5286 * types specified in @format_string when collected into the #va_list.
5287 * See the [GVariant varargs documentation][gvariant-varargs.
5289 * These two generalisations allow mixing of multiple calls to
5290 * g_variant_new_va() and g_variant_get_va() within a single actual
5291 * varargs call by the user.
5293 * The return value will be floating if it was a newly created GVariant
5294 * instance (for example, if the format string was "(ii)"). In the case
5295 * that the format_string was '*', '?', 'r', or a format starting with
5296 * '@' then the collected #GVariant pointer will be returned unmodified,
5297 * without adding any additional references.
5299 * In order to behave correctly in all cases it is necessary for the
5300 * calling function to g_variant_ref_sink() the return result before
5301 * returning control to the user that originally provided the pointer.
5302 * At this point, the caller will have their own full reference to the
5303 * result. This can also be done by adding the result to a container,
5304 * or by passing it to another g_variant_new() call.
5306 * Returns: a new, usually floating, #GVariant
5311 g_variant_new_va (const gchar *format_string,
5312 const gchar **endptr,
5317 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5319 g_return_val_if_fail (app != NULL, NULL);
5321 value = g_variant_valist_new (&format_string, app);
5324 *endptr = format_string;
5330 * g_variant_get: (skip)
5331 * @value: a #GVariant instance
5332 * @format_string: a #GVariant format string
5333 * @...: arguments, as per @format_string
5335 * Deconstructs a #GVariant instance.
5337 * Think of this function as an analogue to scanf().
5339 * The arguments that are expected by this function are entirely
5340 * determined by @format_string. @format_string also restricts the
5341 * permissible types of @value. It is an error to give a value with
5342 * an incompatible type. See the section on
5343 * [GVariant format strings][gvariant-format-strings].
5344 * Please note that the syntax of the format string is very likely to be
5345 * extended in the future.
5347 * @format_string determines the C types that are used for unpacking
5348 * the values and also determines if the values are copied or borrowed,
5349 * see the section on
5350 * [GVariant format strings][gvariant-format-strings-pointers].
5355 g_variant_get (GVariant *value,
5356 const gchar *format_string,
5361 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5363 /* if any direct-pointer-access formats are in use, flatten first */
5364 if (strchr (format_string, '&'))
5365 g_variant_get_data (value);
5367 va_start (ap, format_string);
5368 g_variant_get_va (value, format_string, NULL, &ap);
5373 * g_variant_get_va: (skip)
5374 * @value: a #GVariant
5375 * @format_string: a string that is prefixed with a format string
5376 * @endptr: (allow-none) (default NULL): location to store the end pointer,
5378 * @app: a pointer to a #va_list
5380 * This function is intended to be used by libraries based on #GVariant
5381 * that want to provide g_variant_get()-like functionality to their
5384 * The API is more general than g_variant_get() to allow a wider range
5387 * @format_string must still point to a valid format string, but it only
5388 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5389 * non-%NULL then it is updated to point to the first character past the
5390 * end of the format string.
5392 * @app is a pointer to a #va_list. The arguments, according to
5393 * @format_string, are collected from this #va_list and the list is left
5394 * pointing to the argument following the last.
5396 * These two generalisations allow mixing of multiple calls to
5397 * g_variant_new_va() and g_variant_get_va() within a single actual
5398 * varargs call by the user.
5400 * @format_string determines the C types that are used for unpacking
5401 * the values and also determines if the values are copied or borrowed,
5402 * see the section on
5403 * [GVariant format strings][gvariant-format-strings-pointers].
5408 g_variant_get_va (GVariant *value,
5409 const gchar *format_string,
5410 const gchar **endptr,
5413 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5414 g_return_if_fail (value != NULL);
5415 g_return_if_fail (app != NULL);
5417 /* if any direct-pointer-access formats are in use, flatten first */
5418 if (strchr (format_string, '&'))
5419 g_variant_get_data (value);
5421 g_variant_valist_get (&format_string, value, FALSE, app);
5424 *endptr = format_string;
5427 /* Varargs-enabled Utility Functions {{{1 */
5430 * g_variant_builder_add: (skip)
5431 * @builder: a #GVariantBuilder
5432 * @format_string: a #GVariant varargs format string
5433 * @...: arguments, as per @format_string
5435 * Adds to a #GVariantBuilder.
5437 * This call is a convenience wrapper that is exactly equivalent to
5438 * calling g_variant_new() followed by g_variant_builder_add_value().
5440 * Note that the arguments must be of the correct width for their types
5441 * specified in @format_string. This can be achieved by casting them. See
5442 * the [GVariant varargs documentation][gvariant-varargs].
5444 * This function might be used as follows:
5446 * |[<!-- language="C" -->
5448 * make_pointless_dictionary (void)
5450 * GVariantBuilder builder;
5453 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5454 * for (i = 0; i < 16; i++)
5458 * sprintf (buf, "%d", i);
5459 * g_variant_builder_add (&builder, "{is}", i, buf);
5462 * return g_variant_builder_end (&builder);
5469 g_variant_builder_add (GVariantBuilder *builder,
5470 const gchar *format_string,
5476 va_start (ap, format_string);
5477 variant = g_variant_new_va (format_string, NULL, &ap);
5480 g_variant_builder_add_value (builder, variant);
5484 * g_variant_get_child: (skip)
5485 * @value: a container #GVariant
5486 * @index_: the index of the child to deconstruct
5487 * @format_string: a #GVariant format string
5488 * @...: arguments, as per @format_string
5490 * Reads a child item out of a container #GVariant instance and
5491 * deconstructs it according to @format_string. This call is
5492 * essentially a combination of g_variant_get_child_value() and
5495 * @format_string determines the C types that are used for unpacking
5496 * the values and also determines if the values are copied or borrowed,
5497 * see the section on
5498 * [GVariant format strings][gvariant-format-strings-pointers].
5503 g_variant_get_child (GVariant *value,
5505 const gchar *format_string,
5511 child = g_variant_get_child_value (value, index_);
5512 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5514 va_start (ap, format_string);
5515 g_variant_get_va (child, format_string, NULL, &ap);
5518 g_variant_unref (child);
5522 * g_variant_iter_next: (skip)
5523 * @iter: a #GVariantIter
5524 * @format_string: a GVariant format string
5525 * @...: the arguments to unpack the value into
5527 * Gets the next item in the container and unpacks it into the variable
5528 * argument list according to @format_string, returning %TRUE.
5530 * If no more items remain then %FALSE is returned.
5532 * All of the pointers given on the variable arguments list of this
5533 * function are assumed to point at uninitialised memory. It is the
5534 * responsibility of the caller to free all of the values returned by
5535 * the unpacking process.
5537 * Here is an example for memory management with g_variant_iter_next():
5538 * |[<!-- language="C" -->
5539 * // Iterates a dictionary of type 'a{sv}'
5541 * iterate_dictionary (GVariant *dictionary)
5543 * GVariantIter iter;
5547 * g_variant_iter_init (&iter, dictionary);
5548 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5550 * g_print ("Item '%s' has type '%s'\n", key,
5551 * g_variant_get_type_string (value));
5553 * // must free data for ourselves
5554 * g_variant_unref (value);
5560 * For a solution that is likely to be more convenient to C programmers
5561 * when dealing with loops, see g_variant_iter_loop().
5563 * @format_string determines the C types that are used for unpacking
5564 * the values and also determines if the values are copied or borrowed.
5566 * See the section on
5567 * [GVariant format strings][gvariant-format-strings-pointers].
5569 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5574 g_variant_iter_next (GVariantIter *iter,
5575 const gchar *format_string,
5580 value = g_variant_iter_next_value (iter);
5582 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5589 va_start (ap, format_string);
5590 g_variant_valist_get (&format_string, value, FALSE, &ap);
5593 g_variant_unref (value);
5596 return value != NULL;
5600 * g_variant_iter_loop: (skip)
5601 * @iter: a #GVariantIter
5602 * @format_string: a GVariant format string
5603 * @...: the arguments to unpack the value into
5605 * Gets the next item in the container and unpacks it into the variable
5606 * argument list according to @format_string, returning %TRUE.
5608 * If no more items remain then %FALSE is returned.
5610 * On the first call to this function, the pointers appearing on the
5611 * variable argument list are assumed to point at uninitialised memory.
5612 * On the second and later calls, it is assumed that the same pointers
5613 * will be given and that they will point to the memory as set by the
5614 * previous call to this function. This allows the previous values to
5615 * be freed, as appropriate.
5617 * This function is intended to be used with a while loop as
5618 * demonstrated in the following example. This function can only be
5619 * used when iterating over an array. It is only valid to call this
5620 * function with a string constant for the format string and the same
5621 * string constant must be used each time. Mixing calls to this
5622 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5623 * the same iterator causes undefined behavior.
5625 * If you break out of a such a while loop using g_variant_iter_loop() then
5626 * you must free or unreference all the unpacked values as you would with
5627 * g_variant_get(). Failure to do so will cause a memory leak.
5629 * Here is an example for memory management with g_variant_iter_loop():
5630 * |[<!-- language="C" -->
5631 * // Iterates a dictionary of type 'a{sv}'
5633 * iterate_dictionary (GVariant *dictionary)
5635 * GVariantIter iter;
5639 * g_variant_iter_init (&iter, dictionary);
5640 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5642 * g_print ("Item '%s' has type '%s'\n", key,
5643 * g_variant_get_type_string (value));
5645 * // no need to free 'key' and 'value' here
5646 * // unless breaking out of this loop
5651 * For most cases you should use g_variant_iter_next().
5653 * This function is really only useful when unpacking into #GVariant or
5654 * #GVariantIter in order to allow you to skip the call to
5655 * g_variant_unref() or g_variant_iter_free().
5657 * For example, if you are only looping over simple integer and string
5658 * types, g_variant_iter_next() is definitely preferred. For string
5659 * types, use the '&' prefix to avoid allocating any memory at all (and
5660 * thereby avoiding the need to free anything as well).
5662 * @format_string determines the C types that are used for unpacking
5663 * the values and also determines if the values are copied or borrowed.
5665 * See the section on
5666 * [GVariant format strings][gvariant-format-strings-pointers].
5668 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5674 g_variant_iter_loop (GVariantIter *iter,
5675 const gchar *format_string,
5678 gboolean first_time = GVSI(iter)->loop_format == NULL;
5682 g_return_val_if_fail (first_time ||
5683 format_string == GVSI(iter)->loop_format,
5688 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5689 GVSI(iter)->loop_format = format_string;
5691 if (strchr (format_string, '&'))
5692 g_variant_get_data (GVSI(iter)->value);
5695 value = g_variant_iter_next_value (iter);
5697 g_return_val_if_fail (!first_time ||
5698 valid_format_string (format_string, TRUE, value),
5701 va_start (ap, format_string);
5702 g_variant_valist_get (&format_string, value, !first_time, &ap);
5706 g_variant_unref (value);
5708 return value != NULL;
5711 /* Serialised data {{{1 */
5713 g_variant_deep_copy (GVariant *value)
5715 switch (g_variant_classify (value))
5717 case G_VARIANT_CLASS_MAYBE:
5718 case G_VARIANT_CLASS_ARRAY:
5719 case G_VARIANT_CLASS_TUPLE:
5720 case G_VARIANT_CLASS_DICT_ENTRY:
5721 case G_VARIANT_CLASS_VARIANT:
5723 GVariantBuilder builder;
5727 g_variant_builder_init (&builder, g_variant_get_type (value));
5728 g_variant_iter_init (&iter, value);
5730 while ((child = g_variant_iter_next_value (&iter)))
5732 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5733 g_variant_unref (child);
5736 return g_variant_builder_end (&builder);
5739 case G_VARIANT_CLASS_BOOLEAN:
5740 return g_variant_new_boolean (g_variant_get_boolean (value));
5742 case G_VARIANT_CLASS_BYTE:
5743 return g_variant_new_byte (g_variant_get_byte (value));
5745 case G_VARIANT_CLASS_INT16:
5746 return g_variant_new_int16 (g_variant_get_int16 (value));
5748 case G_VARIANT_CLASS_UINT16:
5749 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5751 case G_VARIANT_CLASS_INT32:
5752 return g_variant_new_int32 (g_variant_get_int32 (value));
5754 case G_VARIANT_CLASS_UINT32:
5755 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5757 case G_VARIANT_CLASS_INT64:
5758 return g_variant_new_int64 (g_variant_get_int64 (value));
5760 case G_VARIANT_CLASS_UINT64:
5761 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5763 case G_VARIANT_CLASS_HANDLE:
5764 return g_variant_new_handle (g_variant_get_handle (value));
5766 case G_VARIANT_CLASS_FLOAT:
5767 return g_variant_new_float (g_variant_get_float (value));
5769 case G_VARIANT_CLASS_DOUBLE:
5770 return g_variant_new_double (g_variant_get_double (value));
5772 case G_VARIANT_CLASS_STRING:
5773 return g_variant_new_string (g_variant_get_string (value, NULL));
5775 case G_VARIANT_CLASS_OBJECT_PATH:
5776 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5778 case G_VARIANT_CLASS_SIGNATURE:
5779 return g_variant_new_signature (g_variant_get_string (value, NULL));
5782 g_assert_not_reached ();
5786 * g_variant_get_normal_form:
5787 * @value: a #GVariant
5789 * Gets a #GVariant instance that has the same value as @value and is
5790 * trusted to be in normal form.
5792 * If @value is already trusted to be in normal form then a new
5793 * reference to @value is returned.
5795 * If @value is not already trusted, then it is scanned to check if it
5796 * is in normal form. If it is found to be in normal form then it is
5797 * marked as trusted and a new reference to it is returned.
5799 * If @value is found not to be in normal form then a new trusted
5800 * #GVariant is created with the same value as @value.
5802 * It makes sense to call this function if you've received #GVariant
5803 * data from untrusted sources and you want to ensure your serialised
5804 * output is definitely in normal form.
5806 * Returns: (transfer full): a trusted #GVariant
5811 g_variant_get_normal_form (GVariant *value)
5815 if (g_variant_is_normal_form (value))
5816 return g_variant_ref (value);
5818 trusted = g_variant_deep_copy (value);
5819 g_assert (g_variant_is_trusted (trusted));
5821 return g_variant_ref_sink (trusted);
5825 * g_variant_byteswap:
5826 * @value: a #GVariant
5828 * Performs a byteswapping operation on the contents of @value. The
5829 * result is that all multi-byte numeric data contained in @value is
5830 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5831 * integers as well as file handles and floating point values.
5833 * This function is an identity mapping on any value that does not
5834 * contain multi-byte numeric data. That include strings, booleans,
5835 * bytes and containers containing only these things (recursively).
5837 * The returned value is always in normal form and is marked as trusted.
5839 * Returns: (transfer full): the byteswapped form of @value
5844 g_variant_byteswap (GVariant *value)
5846 GVariantTypeInfo *type_info;
5850 type_info = g_variant_get_type_info (value);
5852 g_variant_type_info_query (type_info, &alignment, NULL);
5855 /* (potentially) contains multi-byte numeric data */
5857 GVariantSerialised serialised;
5861 trusted = g_variant_get_normal_form (value);
5862 serialised.type_info = g_variant_get_type_info (trusted);
5863 serialised.size = g_variant_get_size (trusted);
5864 serialised.data = g_malloc (serialised.size);
5865 g_variant_store (trusted, serialised.data);
5866 g_variant_unref (trusted);
5868 g_variant_serialised_byteswap (serialised);
5870 bytes = g_bytes_new_take (serialised.data, serialised.size);
5871 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5872 g_bytes_unref (bytes);
5875 /* contains no multi-byte data */
5878 return g_variant_ref_sink (new);
5882 * g_variant_new_from_data:
5883 * @type: a definite #GVariantType
5884 * @data: (array length=size) (element-type guint8): the serialised data
5885 * @size: the size of @data
5886 * @trusted: %TRUE if @data is definitely in normal form
5887 * @notify: (scope async): function to call when @data is no longer needed
5888 * @user_data: data for @notify
5890 * Creates a new #GVariant instance from serialised data.
5892 * @type is the type of #GVariant instance that will be constructed.
5893 * The interpretation of @data depends on knowing the type.
5895 * @data is not modified by this function and must remain valid with an
5896 * unchanging value until such a time as @notify is called with
5897 * @user_data. If the contents of @data change before that time then
5898 * the result is undefined.
5900 * If @data is trusted to be serialised data in normal form then
5901 * @trusted should be %TRUE. This applies to serialised data created
5902 * within this process or read from a trusted location on the disk (such
5903 * as a file installed in /usr/lib alongside your application). You
5904 * should set trusted to %FALSE if @data is read from the network, a
5905 * file in the user's home directory, etc.
5907 * If @data was not stored in this machine's native endianness, any multi-byte
5908 * numeric values in the returned variant will also be in non-native
5909 * endianness. g_variant_byteswap() can be used to recover the original values.
5911 * @notify will be called with @user_data when @data is no longer
5912 * needed. The exact time of this call is unspecified and might even be
5913 * before this function returns.
5915 * Returns: (transfer none): a new floating #GVariant of type @type
5920 g_variant_new_from_data (const GVariantType *type,
5924 GDestroyNotify notify,
5929 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5930 g_return_val_if_fail (data != NULL || size == 0, NULL);
5936 (* notify) (user_data);
5944 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5946 bytes = g_bytes_new_static (data, size);
5948 return g_variant_new_serialised (g_variant_type_info_get (type), bytes, data, size, trusted);
5952 * g_variant_new_from_bytes:
5953 * @type: a #GVariantType
5955 * @trusted: if the contents of @bytes are trusted
5957 * Constructs a new serialised-mode #GVariant instance. This is the
5958 * inner interface for creation of new serialised values that gets
5959 * called from various functions in gvariant.c.
5961 * A reference is taken on @bytes.
5963 * Returns: (transfer none): a new #GVariant with a floating reference
5968 g_variant_new_from_bytes (const GVariantType *type,
5975 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5977 data = g_bytes_get_data (bytes, &size);
5979 return g_variant_new_serialised (g_variant_type_info_get (type), g_bytes_ref (bytes), data, size, trusted);
5983 * g_variant_get_data_as_bytes:
5984 * @value: a #GVariant
5986 * Returns a pointer to the serialised form of a #GVariant instance.
5987 * The semantics of this function are exactly the same as
5988 * g_variant_get_data(), except that the returned #GBytes holds
5989 * a reference to the variant data.
5991 * Returns: (transfer full): A new #GBytes representing the variant data
5996 g_variant_get_data_as_bytes (GVariant *value)
6001 gconstpointer bytes_data;
6004 data = g_variant_get_serialised (value, &bytes, &size);
6005 bytes_data = g_bytes_get_data (bytes, &bytes_size);
6007 /* Try to reuse the GBytes held internally by GVariant, if it exists
6008 * and is covering exactly the correct range.
6010 if (data == bytes_data && size == bytes_size)
6011 return g_bytes_ref (bytes);
6013 /* See g_variant_get_data() about why it can return NULL... */
6014 else if (data == NULL)
6015 return g_bytes_new_take (g_malloc0 (size), size);
6017 /* Otherwise, make a new GBytes with reference to the old. */
6019 return g_bytes_new_with_free_func (data, size, (GDestroyNotify) g_bytes_unref, g_bytes_ref (bytes));
6023 /* vim:set foldmethod=marker: */