Add some more cases to the app-id unit tests
[glib.git] / glib / gvariant.c
bloba57b2fb6984a0e303d099943c28f58f26de3172f
1 /*
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>
21 /* Prologue {{{1 */
23 #include "config.h"
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>
34 #include <string.h>
37 /**
38 * SECTION:gvariant
39 * @title: GVariant
40 * @short_description: strongly typed value datatype
41 * @see_also: GVariantType
43 * #GVariant is a variant datatype; it can contain one or more values
44 * along with information about the type of the values.
46 * A #GVariant may contain simple types, like an integer, or a boolean value;
47 * or complex types, like an array of two strings, or a dictionary of key
48 * value pairs. A #GVariant is also immutable: once it's been created neither
49 * its type nor its content can be modified further.
51 * GVariant is useful whenever data needs to be serialized, for example when
52 * sending method parameters in DBus, or when saving settings using GSettings.
54 * When creating a new #GVariant, you pass the data you want to store in it
55 * along with a string representing the type of data you wish to pass to it.
57 * For instance, if you want to create a #GVariant holding an integer value you
58 * can use:
60 * |[<!-- language="C" -->
61 * GVariant *v = g_variant_new ('u', 40);
62 * ]|
64 * The string 'u' in the first argument tells #GVariant that the data passed to
65 * the constructor (40) is going to be an unsigned integer.
67 * More advanced examples of #GVariant in use can be found in documentation for
68 * [GVariant format strings][gvariant-format-strings-pointers].
70 * The range of possible values is determined by the type.
72 * The type system used by #GVariant is #GVariantType.
74 * #GVariant instances always have a type and a value (which are given
75 * at construction time). The type and value of a #GVariant instance
76 * can never change other than by the #GVariant itself being
77 * destroyed. A #GVariant cannot contain a pointer.
79 * #GVariant is reference counted using g_variant_ref() and
80 * g_variant_unref(). #GVariant also has floating reference counts --
81 * see g_variant_ref_sink().
83 * #GVariant is completely threadsafe. A #GVariant instance can be
84 * concurrently accessed in any way from any number of threads without
85 * problems.
87 * #GVariant is heavily optimised for dealing with data in serialised
88 * form. It works particularly well with data located in memory-mapped
89 * files. It can perform nearly all deserialisation operations in a
90 * small constant time, usually touching only a single memory page.
91 * Serialised #GVariant data can also be sent over the network.
93 * #GVariant is largely compatible with D-Bus. Almost all types of
94 * #GVariant instances can be sent over D-Bus. See #GVariantType for
95 * exceptions. (However, #GVariant's serialisation format is not the same
96 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
97 * in the gio library, for those.)
99 * For space-efficiency, the #GVariant serialisation format does not
100 * automatically include the variant's length, type or endianness,
101 * which must either be implied from context (such as knowledge that a
102 * particular file format always contains a little-endian
103 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
104 * or supplied out-of-band (for instance, a length, type and/or endianness
105 * indicator could be placed at the beginning of a file, network message
106 * or network stream).
108 * A #GVariant's size is limited mainly by any lower level operating
109 * system constraints, such as the number of bits in #gsize. For
110 * example, it is reasonable to have a 2GB file mapped into memory
111 * with #GMappedFile, and call g_variant_new_from_data() on it.
113 * For convenience to C programmers, #GVariant features powerful
114 * varargs-based value construction and destruction. This feature is
115 * designed to be embedded in other libraries.
117 * There is a Python-inspired text language for describing #GVariant
118 * values. #GVariant includes a printer for this language and a parser
119 * with type inferencing.
121 * ## Memory Use
123 * #GVariant tries to be quite efficient with respect to memory use.
124 * This section gives a rough idea of how much memory is used by the
125 * current implementation. The information here is subject to change
126 * in the future.
128 * The memory allocated by #GVariant can be grouped into 4 broad
129 * purposes: memory for serialised data, memory for the type
130 * information cache, buffer management memory and memory for the
131 * #GVariant structure itself.
133 * ## Serialised Data Memory
135 * This is the memory that is used for storing GVariant data in
136 * serialised form. This is what would be sent over the network or
137 * what would end up on disk, not counting any indicator of the
138 * endianness, or of the length or type of the top-level variant.
140 * The amount of memory required to store a boolean is 1 byte. 16,
141 * 32 and 64 bit integers and double precision floating point numbers
142 * use their "natural" size. Strings (including object path and
143 * signature strings) are stored with a nul terminator, and as such
144 * use the length of the string plus 1 byte.
146 * Maybe types use no space at all to represent the null value and
147 * use the same amount of space (sometimes plus one byte) as the
148 * equivalent non-maybe-typed value to represent the non-null case.
150 * Arrays use the amount of space required to store each of their
151 * members, concatenated. Additionally, if the items stored in an
152 * array are not of a fixed-size (ie: strings, other arrays, etc)
153 * then an additional framing offset is stored for each item. The
154 * size of this offset is either 1, 2 or 4 bytes depending on the
155 * overall size of the container. Additionally, extra padding bytes
156 * are added as required for alignment of child values.
158 * Tuples (including dictionary entries) use the amount of space
159 * required to store each of their members, concatenated, plus one
160 * framing offset (as per arrays) for each non-fixed-sized item in
161 * the tuple, except for the last one. Additionally, extra padding
162 * bytes are added as required for alignment of child values.
164 * Variants use the same amount of space as the item inside of the
165 * variant, plus 1 byte, plus the length of the type string for the
166 * item inside the variant.
168 * As an example, consider a dictionary mapping strings to variants.
169 * In the case that the dictionary is empty, 0 bytes are required for
170 * the serialisation.
172 * If we add an item "width" that maps to the int32 value of 500 then
173 * we will use 4 byte to store the int32 (so 6 for the variant
174 * containing it) and 6 bytes for the string. The variant must be
175 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
176 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
177 * for the dictionary entry. An additional 1 byte is added to the
178 * array as a framing offset making a total of 15 bytes.
180 * If we add another entry, "title" that maps to a nullable string
181 * that happens to have a value of null, then we use 0 bytes for the
182 * null value (and 3 bytes for the variant to contain it along with
183 * its type string) plus 6 bytes for the string. Again, we need 2
184 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
186 * We now require extra padding between the two items in the array.
187 * After the 14 bytes of the first item, that's 2 bytes required.
188 * We now require 2 framing offsets for an extra two
189 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
190 * dictionary.
192 * ## Type Information Cache
194 * For each GVariant type that currently exists in the program a type
195 * information structure is kept in the type information cache. The
196 * type information structure is required for rapid deserialisation.
198 * Continuing with the above example, if a #GVariant exists with the
199 * type "a{sv}" then a type information struct will exist for
200 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
201 * will share the same type information. Additionally, all
202 * single-digit types are stored in read-only static memory and do
203 * not contribute to the writable memory footprint of a program using
204 * #GVariant.
206 * Aside from the type information structures stored in read-only
207 * memory, there are two forms of type information. One is used for
208 * container types where there is a single element type: arrays and
209 * maybe types. The other is used for container types where there
210 * are multiple element types: tuples and dictionary entries.
212 * Array type info structures are 6 * sizeof (void *), plus the
213 * memory required to store the type string itself. This means that
214 * on 32-bit systems, the cache entry for "a{sv}" would require 30
215 * bytes of memory (plus malloc overhead).
217 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
218 * sizeof (void *) for each item in the tuple, plus the memory
219 * required to store the type string itself. A 2-item tuple, for
220 * example, would have a type information structure that consumed
221 * writable memory in the size of 14 * sizeof (void *) (plus type
222 * string) This means that on 32-bit systems, the cache entry for
223 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
225 * This means that in total, for our "a{sv}" example, 91 bytes of
226 * type information would be allocated.
228 * The type information cache, additionally, uses a #GHashTable to
229 * store and lookup the cached items and stores a pointer to this
230 * hash table in static storage. The hash table is freed when there
231 * are zero items in the type cache.
233 * Although these sizes may seem large it is important to remember
234 * that a program will probably only have a very small number of
235 * different types of values in it and that only one type information
236 * structure is required for many different values of the same type.
238 * ## Buffer Management Memory
240 * #GVariant uses an internal buffer management structure to deal
241 * with the various different possible sources of serialised data
242 * that it uses. The buffer is responsible for ensuring that the
243 * correct call is made when the data is no longer in use by
244 * #GVariant. This may involve a g_free() or a g_slice_free() or
245 * even g_mapped_file_unref().
247 * One buffer management structure is used for each chunk of
248 * serialised data. The size of the buffer management structure
249 * is 4 * (void *). On 32-bit systems, that's 16 bytes.
251 * ## GVariant structure
253 * The size of a #GVariant structure is 6 * (void *). On 32-bit
254 * systems, that's 24 bytes.
256 * #GVariant structures only exist if they are explicitly created
257 * with API calls. For example, if a #GVariant is constructed out of
258 * serialised data for the example given above (with the dictionary)
259 * then although there are 9 individual values that comprise the
260 * entire dictionary (two keys, two values, two variants containing
261 * the values, two dictionary entries, plus the dictionary itself),
262 * only 1 #GVariant instance exists -- the one referring to the
263 * dictionary.
265 * If calls are made to start accessing the other values then
266 * #GVariant instances will exist for those values only for as long
267 * as they are in use (ie: until you call g_variant_unref()). The
268 * type information is shared. The serialised data and the buffer
269 * management structure for that serialised data is shared by the
270 * child.
272 * ## Summary
274 * To put the entire example together, for our dictionary mapping
275 * strings to variants (with two entries, as given above), we are
276 * using 91 bytes of memory for type information, 29 byes of memory
277 * for the serialised data, 16 bytes for buffer management and 24
278 * bytes for the #GVariant instance, or a total of 160 bytes, plus
279 * malloc overhead. If we were to use g_variant_get_child_value() to
280 * access the two dictionary entries, we would use an additional 48
281 * bytes. If we were to have other dictionaries of the same type, we
282 * would use more memory for the serialised data and buffer
283 * management for those dictionaries, but the type information would
284 * be shared.
287 /* definition of GVariant structure is in gvariant-core.c */
289 /* this is a g_return_val_if_fail() for making
290 * sure a (GVariant *) has the required type.
292 #define TYPE_CHECK(value, TYPE, val) \
293 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
294 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
295 "g_variant_is_of_type (" #value \
296 ", " #TYPE ")"); \
297 return val; \
300 /* Numeric Type Constructor/Getters {{{1 */
301 /* < private >
302 * g_variant_new_from_trusted:
303 * @type: the #GVariantType
304 * @data: the data to use
305 * @size: the size of @data
307 * Constructs a new trusted #GVariant instance from the provided data.
308 * This is used to implement g_variant_new_* for all the basic types.
310 * Returns: a new floating #GVariant
312 static GVariant *
313 g_variant_new_from_trusted (const GVariantType *type,
314 gconstpointer data,
315 gsize size)
317 GVariant *value;
318 GBytes *bytes;
320 bytes = g_bytes_new (data, size);
321 value = g_variant_new_from_bytes (type, bytes, TRUE);
322 g_bytes_unref (bytes);
324 return value;
328 * g_variant_new_boolean:
329 * @value: a #gboolean value
331 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
333 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
335 * Since: 2.24
337 GVariant *
338 g_variant_new_boolean (gboolean value)
340 guchar v = value;
342 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
346 * g_variant_get_boolean:
347 * @value: a boolean #GVariant instance
349 * Returns the boolean value of @value.
351 * It is an error to call this function with a @value of any type
352 * other than %G_VARIANT_TYPE_BOOLEAN.
354 * Returns: %TRUE or %FALSE
356 * Since: 2.24
358 gboolean
359 g_variant_get_boolean (GVariant *value)
361 const guchar *data;
363 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
365 data = g_variant_get_data (value);
367 return data != NULL ? *data != 0 : FALSE;
370 /* the constructors and accessors for byte, int{16,32,64}, handles and
371 * doubles all look pretty much exactly the same, so we reduce
372 * copy/pasting here.
374 #define NUMERIC_TYPE(TYPE, type, ctype) \
375 GVariant *g_variant_new_##type (ctype value) { \
376 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
377 &value, sizeof value); \
379 ctype g_variant_get_##type (GVariant *value) { \
380 const ctype *data; \
381 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
382 data = g_variant_get_data (value); \
383 return data != NULL ? *data : 0; \
388 * g_variant_new_byte:
389 * @value: a #guint8 value
391 * Creates a new byte #GVariant instance.
393 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
395 * Since: 2.24
398 * g_variant_get_byte:
399 * @value: a byte #GVariant instance
401 * Returns the byte value of @value.
403 * It is an error to call this function with a @value of any type
404 * other than %G_VARIANT_TYPE_BYTE.
406 * Returns: a #guchar
408 * Since: 2.24
410 NUMERIC_TYPE (BYTE, byte, guchar)
413 * g_variant_new_int16:
414 * @value: a #gint16 value
416 * Creates a new int16 #GVariant instance.
418 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
420 * Since: 2.24
423 * g_variant_get_int16:
424 * @value: a int16 #GVariant instance
426 * Returns the 16-bit signed integer value of @value.
428 * It is an error to call this function with a @value of any type
429 * other than %G_VARIANT_TYPE_INT16.
431 * Returns: a #gint16
433 * Since: 2.24
435 NUMERIC_TYPE (INT16, int16, gint16)
438 * g_variant_new_uint16:
439 * @value: a #guint16 value
441 * Creates a new uint16 #GVariant instance.
443 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
445 * Since: 2.24
448 * g_variant_get_uint16:
449 * @value: a uint16 #GVariant instance
451 * Returns the 16-bit unsigned integer value of @value.
453 * It is an error to call this function with a @value of any type
454 * other than %G_VARIANT_TYPE_UINT16.
456 * Returns: a #guint16
458 * Since: 2.24
460 NUMERIC_TYPE (UINT16, uint16, guint16)
463 * g_variant_new_int32:
464 * @value: a #gint32 value
466 * Creates a new int32 #GVariant instance.
468 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
470 * Since: 2.24
473 * g_variant_get_int32:
474 * @value: a int32 #GVariant instance
476 * Returns the 32-bit signed integer value of @value.
478 * It is an error to call this function with a @value of any type
479 * other than %G_VARIANT_TYPE_INT32.
481 * Returns: a #gint32
483 * Since: 2.24
485 NUMERIC_TYPE (INT32, int32, gint32)
488 * g_variant_new_uint32:
489 * @value: a #guint32 value
491 * Creates a new uint32 #GVariant instance.
493 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
495 * Since: 2.24
498 * g_variant_get_uint32:
499 * @value: a uint32 #GVariant instance
501 * Returns the 32-bit unsigned integer value of @value.
503 * It is an error to call this function with a @value of any type
504 * other than %G_VARIANT_TYPE_UINT32.
506 * Returns: a #guint32
508 * Since: 2.24
510 NUMERIC_TYPE (UINT32, uint32, guint32)
513 * g_variant_new_int64:
514 * @value: a #gint64 value
516 * Creates a new int64 #GVariant instance.
518 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
520 * Since: 2.24
523 * g_variant_get_int64:
524 * @value: a int64 #GVariant instance
526 * Returns the 64-bit signed integer value of @value.
528 * It is an error to call this function with a @value of any type
529 * other than %G_VARIANT_TYPE_INT64.
531 * Returns: a #gint64
533 * Since: 2.24
535 NUMERIC_TYPE (INT64, int64, gint64)
538 * g_variant_new_uint64:
539 * @value: a #guint64 value
541 * Creates a new uint64 #GVariant instance.
543 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
545 * Since: 2.24
548 * g_variant_get_uint64:
549 * @value: a uint64 #GVariant instance
551 * Returns the 64-bit unsigned integer value of @value.
553 * It is an error to call this function with a @value of any type
554 * other than %G_VARIANT_TYPE_UINT64.
556 * Returns: a #guint64
558 * Since: 2.24
560 NUMERIC_TYPE (UINT64, uint64, guint64)
563 * g_variant_new_handle:
564 * @value: a #gint32 value
566 * Creates a new handle #GVariant instance.
568 * By convention, handles are indexes into an array of file descriptors
569 * that are sent alongside a D-Bus message. If you're not interacting
570 * with D-Bus, you probably don't need them.
572 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
574 * Since: 2.24
577 * g_variant_get_handle:
578 * @value: a handle #GVariant instance
580 * Returns the 32-bit signed integer value of @value.
582 * It is an error to call this function with a @value of any type other
583 * than %G_VARIANT_TYPE_HANDLE.
585 * By convention, handles are indexes into an array of file descriptors
586 * that are sent alongside a D-Bus message. If you're not interacting
587 * with D-Bus, you probably don't need them.
589 * Returns: a #gint32
591 * Since: 2.24
593 NUMERIC_TYPE (HANDLE, handle, gint32)
596 * g_variant_new_double:
597 * @value: a #gdouble floating point value
599 * Creates a new double #GVariant instance.
601 * Returns: (transfer none): a floating reference to a new double #GVariant instance
603 * Since: 2.24
606 * g_variant_get_double:
607 * @value: a double #GVariant instance
609 * Returns the double precision floating point value of @value.
611 * It is an error to call this function with a @value of any type
612 * other than %G_VARIANT_TYPE_DOUBLE.
614 * Returns: a #gdouble
616 * Since: 2.24
618 NUMERIC_TYPE (DOUBLE, double, gdouble)
620 /* Container type Constructor / Deconstructors {{{1 */
622 * g_variant_new_maybe:
623 * @child_type: (nullable): the #GVariantType of the child, or %NULL
624 * @child: (nullable): the child value, or %NULL
626 * Depending on if @child is %NULL, either wraps @child inside of a
627 * maybe container or creates a Nothing instance for the given @type.
629 * At least one of @child_type and @child must be non-%NULL.
630 * If @child_type is non-%NULL then it must be a definite type.
631 * If they are both non-%NULL then @child_type must be the type
632 * of @child.
634 * If @child is a floating reference (see g_variant_ref_sink()), the new
635 * instance takes ownership of @child.
637 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
639 * Since: 2.24
641 GVariant *
642 g_variant_new_maybe (const GVariantType *child_type,
643 GVariant *child)
645 GVariantType *maybe_type;
646 GVariant *value;
648 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
649 (child_type), 0);
650 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
651 g_return_val_if_fail (child_type == NULL || child == NULL ||
652 g_variant_is_of_type (child, child_type),
653 NULL);
655 if (child_type == NULL)
656 child_type = g_variant_get_type (child);
658 maybe_type = g_variant_type_new_maybe (child_type);
660 if (child != NULL)
662 GVariant **children;
663 gboolean trusted;
665 children = g_new (GVariant *, 1);
666 children[0] = g_variant_ref_sink (child);
667 trusted = g_variant_is_trusted (children[0]);
669 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
671 else
672 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
674 g_variant_type_free (maybe_type);
676 return value;
680 * g_variant_get_maybe:
681 * @value: a maybe-typed value
683 * Given a maybe-typed #GVariant instance, extract its value. If the
684 * value is Nothing, then this function returns %NULL.
686 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
688 * Since: 2.24
690 GVariant *
691 g_variant_get_maybe (GVariant *value)
693 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
695 if (g_variant_n_children (value))
696 return g_variant_get_child_value (value, 0);
698 return NULL;
702 * g_variant_new_variant: (constructor)
703 * @value: a #GVariant instance
705 * Boxes @value. The result is a #GVariant instance representing a
706 * variant containing the original value.
708 * If @child is a floating reference (see g_variant_ref_sink()), the new
709 * instance takes ownership of @child.
711 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
713 * Since: 2.24
715 GVariant *
716 g_variant_new_variant (GVariant *value)
718 g_return_val_if_fail (value != NULL, NULL);
720 g_variant_ref_sink (value);
722 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
723 g_memdup (&value, sizeof value),
724 1, g_variant_is_trusted (value));
728 * g_variant_get_variant:
729 * @value: a variant #GVariant instance
731 * Unboxes @value. The result is the #GVariant instance that was
732 * contained in @value.
734 * Returns: (transfer full): the item contained in the variant
736 * Since: 2.24
738 GVariant *
739 g_variant_get_variant (GVariant *value)
741 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
743 return g_variant_get_child_value (value, 0);
747 * g_variant_new_array:
748 * @child_type: (nullable): the element type of the new array
749 * @children: (nullable) (array length=n_children): an array of
750 * #GVariant pointers, the children
751 * @n_children: the length of @children
753 * Creates a new #GVariant array from @children.
755 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
756 * child type is determined by inspecting the first element of the
757 * @children array. If @child_type is non-%NULL then it must be a
758 * definite type.
760 * The items of the array are taken from the @children array. No entry
761 * in the @children array may be %NULL.
763 * All items in the array must have the same type, which must be the
764 * same as @child_type, if given.
766 * If the @children are floating references (see g_variant_ref_sink()), the
767 * new instance takes ownership of them as if via g_variant_ref_sink().
769 * Returns: (transfer none): a floating reference to a new #GVariant array
771 * Since: 2.24
773 GVariant *
774 g_variant_new_array (const GVariantType *child_type,
775 GVariant * const *children,
776 gsize n_children)
778 GVariantType *array_type;
779 GVariant **my_children;
780 gboolean trusted;
781 GVariant *value;
782 gsize i;
784 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
785 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
786 g_return_val_if_fail (child_type == NULL ||
787 g_variant_type_is_definite (child_type), NULL);
789 my_children = g_new (GVariant *, n_children);
790 trusted = TRUE;
792 if (child_type == NULL)
793 child_type = g_variant_get_type (children[0]);
794 array_type = g_variant_type_new_array (child_type);
796 for (i = 0; i < n_children; i++)
798 TYPE_CHECK (children[i], child_type, NULL);
799 my_children[i] = g_variant_ref_sink (children[i]);
800 trusted &= g_variant_is_trusted (children[i]);
803 value = g_variant_new_from_children (array_type, my_children,
804 n_children, trusted);
805 g_variant_type_free (array_type);
807 return value;
810 /*< private >
811 * g_variant_make_tuple_type:
812 * @children: (array length=n_children): an array of GVariant *
813 * @n_children: the length of @children
815 * Return the type of a tuple containing @children as its items.
817 static GVariantType *
818 g_variant_make_tuple_type (GVariant * const *children,
819 gsize n_children)
821 const GVariantType **types;
822 GVariantType *type;
823 gsize i;
825 types = g_new (const GVariantType *, n_children);
827 for (i = 0; i < n_children; i++)
828 types[i] = g_variant_get_type (children[i]);
830 type = g_variant_type_new_tuple (types, n_children);
831 g_free (types);
833 return type;
837 * g_variant_new_tuple:
838 * @children: (array length=n_children): the items to make the tuple out of
839 * @n_children: the length of @children
841 * Creates a new tuple #GVariant out of the items in @children. The
842 * type is determined from the types of @children. No entry in the
843 * @children array may be %NULL.
845 * If @n_children is 0 then the unit tuple is constructed.
847 * If the @children are floating references (see g_variant_ref_sink()), the
848 * new instance takes ownership of them as if via g_variant_ref_sink().
850 * Returns: (transfer none): a floating reference to a new #GVariant tuple
852 * Since: 2.24
854 GVariant *
855 g_variant_new_tuple (GVariant * const *children,
856 gsize n_children)
858 GVariantType *tuple_type;
859 GVariant **my_children;
860 gboolean trusted;
861 GVariant *value;
862 gsize i;
864 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
866 my_children = g_new (GVariant *, n_children);
867 trusted = TRUE;
869 for (i = 0; i < n_children; i++)
871 my_children[i] = g_variant_ref_sink (children[i]);
872 trusted &= g_variant_is_trusted (children[i]);
875 tuple_type = g_variant_make_tuple_type (children, n_children);
876 value = g_variant_new_from_children (tuple_type, my_children,
877 n_children, trusted);
878 g_variant_type_free (tuple_type);
880 return value;
883 /*< private >
884 * g_variant_make_dict_entry_type:
885 * @key: a #GVariant, the key
886 * @val: a #GVariant, the value
888 * Return the type of a dictionary entry containing @key and @val as its
889 * children.
891 static GVariantType *
892 g_variant_make_dict_entry_type (GVariant *key,
893 GVariant *val)
895 return g_variant_type_new_dict_entry (g_variant_get_type (key),
896 g_variant_get_type (val));
900 * g_variant_new_dict_entry: (constructor)
901 * @key: a basic #GVariant, the key
902 * @value: a #GVariant, the value
904 * Creates a new dictionary entry #GVariant. @key and @value must be
905 * non-%NULL. @key must be a value of a basic type (ie: not a container).
907 * If the @key or @value are floating references (see g_variant_ref_sink()),
908 * the new instance takes ownership of them as if via g_variant_ref_sink().
910 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
912 * Since: 2.24
914 GVariant *
915 g_variant_new_dict_entry (GVariant *key,
916 GVariant *value)
918 GVariantType *dict_type;
919 GVariant **children;
920 gboolean trusted;
922 g_return_val_if_fail (key != NULL && value != NULL, NULL);
923 g_return_val_if_fail (!g_variant_is_container (key), NULL);
925 children = g_new (GVariant *, 2);
926 children[0] = g_variant_ref_sink (key);
927 children[1] = g_variant_ref_sink (value);
928 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
930 dict_type = g_variant_make_dict_entry_type (key, value);
931 value = g_variant_new_from_children (dict_type, children, 2, trusted);
932 g_variant_type_free (dict_type);
934 return value;
938 * g_variant_lookup: (skip)
939 * @dictionary: a dictionary #GVariant
940 * @key: the key to lookup in the dictionary
941 * @format_string: a GVariant format string
942 * @...: the arguments to unpack the value into
944 * Looks up a value in a dictionary #GVariant.
946 * This function is a wrapper around g_variant_lookup_value() and
947 * g_variant_get(). In the case that %NULL would have been returned,
948 * this function returns %FALSE. Otherwise, it unpacks the returned
949 * value and returns %TRUE.
951 * @format_string determines the C types that are used for unpacking
952 * the values and also determines if the values are copied or borrowed,
953 * see the section on
954 * [GVariant format strings][gvariant-format-strings-pointers].
956 * This function is currently implemented with a linear scan. If you
957 * plan to do many lookups then #GVariantDict may be more efficient.
959 * Returns: %TRUE if a value was unpacked
961 * Since: 2.28
963 gboolean
964 g_variant_lookup (GVariant *dictionary,
965 const gchar *key,
966 const gchar *format_string,
967 ...)
969 GVariantType *type;
970 GVariant *value;
972 /* flatten */
973 g_variant_get_data (dictionary);
975 type = g_variant_format_string_scan_type (format_string, NULL, NULL);
976 value = g_variant_lookup_value (dictionary, key, type);
977 g_variant_type_free (type);
979 if (value)
981 va_list ap;
983 va_start (ap, format_string);
984 g_variant_get_va (value, format_string, NULL, &ap);
985 g_variant_unref (value);
986 va_end (ap);
988 return TRUE;
991 else
992 return FALSE;
996 * g_variant_lookup_value:
997 * @dictionary: a dictionary #GVariant
998 * @key: the key to lookup in the dictionary
999 * @expected_type: (nullable): a #GVariantType, or %NULL
1001 * Looks up a value in a dictionary #GVariant.
1003 * This function works with dictionaries of the type a{s*} (and equally
1004 * well with type a{o*}, but we only further discuss the string case
1005 * for sake of clarity).
1007 * In the event that @dictionary has the type a{sv}, the @expected_type
1008 * string specifies what type of value is expected to be inside of the
1009 * variant. If the value inside the variant has a different type then
1010 * %NULL is returned. In the event that @dictionary has a value type other
1011 * than v then @expected_type must directly match the key type and it is
1012 * used to unpack the value directly or an error occurs.
1014 * In either case, if @key is not found in @dictionary, %NULL is returned.
1016 * If the key is found and the value has the correct type, it is
1017 * returned. If @expected_type was specified then any non-%NULL return
1018 * value will have this type.
1020 * This function is currently implemented with a linear scan. If you
1021 * plan to do many lookups then #GVariantDict may be more efficient.
1023 * Returns: (transfer full): the value of the dictionary key, or %NULL
1025 * Since: 2.28
1027 GVariant *
1028 g_variant_lookup_value (GVariant *dictionary,
1029 const gchar *key,
1030 const GVariantType *expected_type)
1032 GVariantIter iter;
1033 GVariant *entry;
1034 GVariant *value;
1036 g_return_val_if_fail (g_variant_is_of_type (dictionary,
1037 G_VARIANT_TYPE ("a{s*}")) ||
1038 g_variant_is_of_type (dictionary,
1039 G_VARIANT_TYPE ("a{o*}")),
1040 NULL);
1042 g_variant_iter_init (&iter, dictionary);
1044 while ((entry = g_variant_iter_next_value (&iter)))
1046 GVariant *entry_key;
1047 gboolean matches;
1049 entry_key = g_variant_get_child_value (entry, 0);
1050 matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1051 g_variant_unref (entry_key);
1053 if (matches)
1054 break;
1056 g_variant_unref (entry);
1059 if (entry == NULL)
1060 return NULL;
1062 value = g_variant_get_child_value (entry, 1);
1063 g_variant_unref (entry);
1065 if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1067 GVariant *tmp;
1069 tmp = g_variant_get_variant (value);
1070 g_variant_unref (value);
1072 if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1074 g_variant_unref (tmp);
1075 tmp = NULL;
1078 value = tmp;
1081 g_return_val_if_fail (expected_type == NULL || value == NULL ||
1082 g_variant_is_of_type (value, expected_type), NULL);
1084 return value;
1088 * g_variant_get_fixed_array:
1089 * @value: a #GVariant array with fixed-sized elements
1090 * @n_elements: (out): a pointer to the location to store the number of items
1091 * @element_size: the size of each element
1093 * Provides access to the serialised data for an array of fixed-sized
1094 * items.
1096 * @value must be an array with fixed-sized elements. Numeric types are
1097 * fixed-size, as are tuples containing only other fixed-sized types.
1099 * @element_size must be the size of a single element in the array,
1100 * as given by the section on
1101 * [serialized data memory][gvariant-serialised-data-memory].
1103 * In particular, arrays of these fixed-sized types can be interpreted
1104 * as an array of the given C type, with @element_size set to the size
1105 * the appropriate type:
1106 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1107 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1108 * - %G_VARIANT_TYPE_BYTE: #guchar
1109 * - %G_VARIANT_TYPE_HANDLE: #guint32
1110 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1112 * For example, if calling this function for an array of 32-bit integers,
1113 * you might say sizeof(gint32). This value isn't used except for the purpose
1114 * of a double-check that the form of the serialised data matches the caller's
1115 * expectation.
1117 * @n_elements, which must be non-%NULL is set equal to the number of
1118 * items in the array.
1120 * Returns: (array length=n_elements) (transfer none): a pointer to
1121 * the fixed array
1123 * Since: 2.24
1125 gconstpointer
1126 g_variant_get_fixed_array (GVariant *value,
1127 gsize *n_elements,
1128 gsize element_size)
1130 GVariantTypeInfo *array_info;
1131 gsize array_element_size;
1132 gconstpointer data;
1133 gsize size;
1135 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1137 g_return_val_if_fail (n_elements != NULL, NULL);
1138 g_return_val_if_fail (element_size > 0, NULL);
1140 array_info = g_variant_get_type_info (value);
1141 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1143 g_return_val_if_fail (array_element_size, NULL);
1145 if G_UNLIKELY (array_element_size != element_size)
1147 if (array_element_size)
1148 g_critical ("g_variant_get_fixed_array: assertion "
1149 "'g_variant_array_has_fixed_size (value, element_size)' "
1150 "failed: array size %"G_GSIZE_FORMAT" does not match "
1151 "given element_size %"G_GSIZE_FORMAT".",
1152 array_element_size, element_size);
1153 else
1154 g_critical ("g_variant_get_fixed_array: assertion "
1155 "'g_variant_array_has_fixed_size (value, element_size)' "
1156 "failed: array does not have fixed size.");
1159 data = g_variant_get_data (value);
1160 size = g_variant_get_size (value);
1162 if (size % element_size)
1163 *n_elements = 0;
1164 else
1165 *n_elements = size / element_size;
1167 if (*n_elements)
1168 return data;
1170 return NULL;
1174 * g_variant_new_fixed_array:
1175 * @element_type: the #GVariantType of each element
1176 * @elements: a pointer to the fixed array of contiguous elements
1177 * @n_elements: the number of elements
1178 * @element_size: the size of each element
1180 * Provides access to the serialised data for an array of fixed-sized
1181 * items.
1183 * @value must be an array with fixed-sized elements. Numeric types are
1184 * fixed-size as are tuples containing only other fixed-sized types.
1186 * @element_size must be the size of a single element in the array.
1187 * For example, if calling this function for an array of 32-bit integers,
1188 * you might say sizeof(gint32). This value isn't used except for the purpose
1189 * of a double-check that the form of the serialised data matches the caller's
1190 * expectation.
1192 * @n_elements, which must be non-%NULL is set equal to the number of
1193 * items in the array.
1195 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1197 * Since: 2.32
1199 GVariant *
1200 g_variant_new_fixed_array (const GVariantType *element_type,
1201 gconstpointer elements,
1202 gsize n_elements,
1203 gsize element_size)
1205 GVariantType *array_type;
1206 gsize array_element_size;
1207 GVariantTypeInfo *array_info;
1208 GVariant *value;
1209 gpointer data;
1211 g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1212 g_return_val_if_fail (element_size > 0, NULL);
1214 array_type = g_variant_type_new_array (element_type);
1215 array_info = g_variant_type_info_get (array_type);
1216 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1217 if G_UNLIKELY (array_element_size != element_size)
1219 if (array_element_size)
1220 g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1221 " does not match given element_size %" G_GSIZE_FORMAT ".",
1222 array_element_size, element_size);
1223 else
1224 g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1225 return NULL;
1228 data = g_memdup (elements, n_elements * element_size);
1229 value = g_variant_new_from_data (array_type, data,
1230 n_elements * element_size,
1231 FALSE, g_free, data);
1233 g_variant_type_free (array_type);
1234 g_variant_type_info_unref (array_info);
1236 return value;
1239 /* String type constructor/getters/validation {{{1 */
1241 * g_variant_new_string:
1242 * @string: a normal UTF-8 nul-terminated string
1244 * Creates a string #GVariant with the contents of @string.
1246 * @string must be valid UTF-8, and must not be %NULL. To encode
1247 * potentially-%NULL strings, use g_variant_new() with `ms` as the
1248 * [format string][gvariant-format-strings-maybe-types].
1250 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1252 * Since: 2.24
1254 GVariant *
1255 g_variant_new_string (const gchar *string)
1257 g_return_val_if_fail (string != NULL, NULL);
1258 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1260 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1261 string, strlen (string) + 1);
1265 * g_variant_new_take_string: (skip)
1266 * @string: a normal UTF-8 nul-terminated string
1268 * Creates a string #GVariant with the contents of @string.
1270 * @string must be valid UTF-8, and must not be %NULL. To encode
1271 * potentially-%NULL strings, use this with g_variant_new_maybe().
1273 * This function consumes @string. g_free() will be called on @string
1274 * when it is no longer required.
1276 * You must not modify or access @string in any other way after passing
1277 * it to this function. It is even possible that @string is immediately
1278 * freed.
1280 * Returns: (transfer none): a floating reference to a new string
1281 * #GVariant instance
1283 * Since: 2.38
1285 GVariant *
1286 g_variant_new_take_string (gchar *string)
1288 GVariant *value;
1289 GBytes *bytes;
1291 g_return_val_if_fail (string != NULL, NULL);
1292 g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1294 bytes = g_bytes_new_take (string, strlen (string) + 1);
1295 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1296 g_bytes_unref (bytes);
1298 return value;
1302 * g_variant_new_printf: (skip)
1303 * @format_string: a printf-style format string
1304 * @...: arguments for @format_string
1306 * Creates a string-type GVariant using printf formatting.
1308 * This is similar to calling g_strdup_printf() and then
1309 * g_variant_new_string() but it saves a temporary variable and an
1310 * unnecessary copy.
1312 * Returns: (transfer none): a floating reference to a new string
1313 * #GVariant instance
1315 * Since: 2.38
1317 GVariant *
1318 g_variant_new_printf (const gchar *format_string,
1319 ...)
1321 GVariant *value;
1322 GBytes *bytes;
1323 gchar *string;
1324 va_list ap;
1326 g_return_val_if_fail (format_string != NULL, NULL);
1328 va_start (ap, format_string);
1329 string = g_strdup_vprintf (format_string, ap);
1330 va_end (ap);
1332 bytes = g_bytes_new_take (string, strlen (string) + 1);
1333 value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1334 g_bytes_unref (bytes);
1336 return value;
1340 * g_variant_new_object_path:
1341 * @object_path: a normal C nul-terminated string
1343 * Creates a D-Bus object path #GVariant with the contents of @string.
1344 * @string must be a valid D-Bus object path. Use
1345 * g_variant_is_object_path() if you're not sure.
1347 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1349 * Since: 2.24
1351 GVariant *
1352 g_variant_new_object_path (const gchar *object_path)
1354 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1356 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1357 object_path, strlen (object_path) + 1);
1361 * g_variant_is_object_path:
1362 * @string: a normal C nul-terminated string
1364 * Determines if a given string is a valid D-Bus object path. You
1365 * should ensure that a string is a valid D-Bus object path before
1366 * passing it to g_variant_new_object_path().
1368 * A valid object path starts with '/' followed by zero or more
1369 * sequences of characters separated by '/' characters. Each sequence
1370 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1371 * (including the one following the final '/' character) may be empty.
1373 * Returns: %TRUE if @string is a D-Bus object path
1375 * Since: 2.24
1377 gboolean
1378 g_variant_is_object_path (const gchar *string)
1380 g_return_val_if_fail (string != NULL, FALSE);
1382 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1386 * g_variant_new_signature:
1387 * @signature: a normal C nul-terminated string
1389 * Creates a D-Bus type signature #GVariant with the contents of
1390 * @string. @string must be a valid D-Bus type signature. Use
1391 * g_variant_is_signature() if you're not sure.
1393 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1395 * Since: 2.24
1397 GVariant *
1398 g_variant_new_signature (const gchar *signature)
1400 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1402 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1403 signature, strlen (signature) + 1);
1407 * g_variant_is_signature:
1408 * @string: a normal C nul-terminated string
1410 * Determines if a given string is a valid D-Bus type signature. You
1411 * should ensure that a string is a valid D-Bus type signature before
1412 * passing it to g_variant_new_signature().
1414 * D-Bus type signatures consist of zero or more definite #GVariantType
1415 * strings in sequence.
1417 * Returns: %TRUE if @string is a D-Bus type signature
1419 * Since: 2.24
1421 gboolean
1422 g_variant_is_signature (const gchar *string)
1424 g_return_val_if_fail (string != NULL, FALSE);
1426 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1430 * g_variant_get_string:
1431 * @value: a string #GVariant instance
1432 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1433 * to store the length
1435 * Returns the string value of a #GVariant instance with a string
1436 * type. This includes the types %G_VARIANT_TYPE_STRING,
1437 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1439 * The string will always be UTF-8 encoded, and will never be %NULL.
1441 * If @length is non-%NULL then the length of the string (in bytes) is
1442 * returned there. For trusted values, this information is already
1443 * known. For untrusted values, a strlen() will be performed.
1445 * It is an error to call this function with a @value of any type
1446 * other than those three.
1448 * The return value remains valid as long as @value exists.
1450 * Returns: (transfer none): the constant string, UTF-8 encoded
1452 * Since: 2.24
1454 const gchar *
1455 g_variant_get_string (GVariant *value,
1456 gsize *length)
1458 gconstpointer data;
1459 gsize size;
1461 g_return_val_if_fail (value != NULL, NULL);
1462 g_return_val_if_fail (
1463 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1464 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1465 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1467 data = g_variant_get_data (value);
1468 size = g_variant_get_size (value);
1470 if (!g_variant_is_trusted (value))
1472 switch (g_variant_classify (value))
1474 case G_VARIANT_CLASS_STRING:
1475 if (g_variant_serialiser_is_string (data, size))
1476 break;
1478 data = "";
1479 size = 1;
1480 break;
1482 case G_VARIANT_CLASS_OBJECT_PATH:
1483 if (g_variant_serialiser_is_object_path (data, size))
1484 break;
1486 data = "/";
1487 size = 2;
1488 break;
1490 case G_VARIANT_CLASS_SIGNATURE:
1491 if (g_variant_serialiser_is_signature (data, size))
1492 break;
1494 data = "";
1495 size = 1;
1496 break;
1498 default:
1499 g_assert_not_reached ();
1503 if (length)
1504 *length = size - 1;
1506 return data;
1510 * g_variant_dup_string:
1511 * @value: a string #GVariant instance
1512 * @length: (out): a pointer to a #gsize, to store the length
1514 * Similar to g_variant_get_string() except that instead of returning
1515 * a constant string, the string is duplicated.
1517 * The string will always be UTF-8 encoded.
1519 * The return value must be freed using g_free().
1521 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1523 * Since: 2.24
1525 gchar *
1526 g_variant_dup_string (GVariant *value,
1527 gsize *length)
1529 return g_strdup (g_variant_get_string (value, length));
1533 * g_variant_new_strv:
1534 * @strv: (array length=length) (element-type utf8): an array of strings
1535 * @length: the length of @strv, or -1
1537 * Constructs an array of strings #GVariant from the given array of
1538 * strings.
1540 * If @length is -1 then @strv is %NULL-terminated.
1542 * Returns: (transfer none): a new floating #GVariant instance
1544 * Since: 2.24
1546 GVariant *
1547 g_variant_new_strv (const gchar * const *strv,
1548 gssize length)
1550 GVariant **strings;
1551 gsize i;
1553 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1555 if (length < 0)
1556 length = g_strv_length ((gchar **) strv);
1558 strings = g_new (GVariant *, length);
1559 for (i = 0; i < length; i++)
1560 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1562 return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1563 strings, length, TRUE);
1567 * g_variant_get_strv:
1568 * @value: an array of strings #GVariant
1569 * @length: (out) (optional): the length of the result, or %NULL
1571 * Gets the contents of an array of strings #GVariant. This call
1572 * makes a shallow copy; the return result should be released with
1573 * g_free(), but the individual strings must not be modified.
1575 * If @length is non-%NULL then the number of elements in the result
1576 * is stored there. In any case, the resulting array will be
1577 * %NULL-terminated.
1579 * For an empty array, @length will be set to 0 and a pointer to a
1580 * %NULL pointer will be returned.
1582 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1584 * Since: 2.24
1586 const gchar **
1587 g_variant_get_strv (GVariant *value,
1588 gsize *length)
1590 const gchar **strv;
1591 gsize n;
1592 gsize i;
1594 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1596 g_variant_get_data (value);
1597 n = g_variant_n_children (value);
1598 strv = g_new (const gchar *, n + 1);
1600 for (i = 0; i < n; i++)
1602 GVariant *string;
1604 string = g_variant_get_child_value (value, i);
1605 strv[i] = g_variant_get_string (string, NULL);
1606 g_variant_unref (string);
1608 strv[i] = NULL;
1610 if (length)
1611 *length = n;
1613 return strv;
1617 * g_variant_dup_strv:
1618 * @value: an array of strings #GVariant
1619 * @length: (out) (optional): the length of the result, or %NULL
1621 * Gets the contents of an array of strings #GVariant. This call
1622 * makes a deep copy; the return result should be released with
1623 * g_strfreev().
1625 * If @length is non-%NULL then the number of elements in the result
1626 * is stored there. In any case, the resulting array will be
1627 * %NULL-terminated.
1629 * For an empty array, @length will be set to 0 and a pointer to a
1630 * %NULL pointer will be returned.
1632 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1634 * Since: 2.24
1636 gchar **
1637 g_variant_dup_strv (GVariant *value,
1638 gsize *length)
1640 gchar **strv;
1641 gsize n;
1642 gsize i;
1644 TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1646 n = g_variant_n_children (value);
1647 strv = g_new (gchar *, n + 1);
1649 for (i = 0; i < n; i++)
1651 GVariant *string;
1653 string = g_variant_get_child_value (value, i);
1654 strv[i] = g_variant_dup_string (string, NULL);
1655 g_variant_unref (string);
1657 strv[i] = NULL;
1659 if (length)
1660 *length = n;
1662 return strv;
1666 * g_variant_new_objv:
1667 * @strv: (array length=length) (element-type utf8): an array of strings
1668 * @length: the length of @strv, or -1
1670 * Constructs an array of object paths #GVariant from the given array of
1671 * strings.
1673 * Each string must be a valid #GVariant object path; see
1674 * g_variant_is_object_path().
1676 * If @length is -1 then @strv is %NULL-terminated.
1678 * Returns: (transfer none): a new floating #GVariant instance
1680 * Since: 2.30
1682 GVariant *
1683 g_variant_new_objv (const gchar * const *strv,
1684 gssize length)
1686 GVariant **strings;
1687 gsize i;
1689 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1691 if (length < 0)
1692 length = g_strv_length ((gchar **) strv);
1694 strings = g_new (GVariant *, length);
1695 for (i = 0; i < length; i++)
1696 strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1698 return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1699 strings, length, TRUE);
1703 * g_variant_get_objv:
1704 * @value: an array of object paths #GVariant
1705 * @length: (out) (optional): the length of the result, or %NULL
1707 * Gets the contents of an array of object paths #GVariant. This call
1708 * makes a shallow copy; the return result should be released with
1709 * g_free(), but the individual strings must not be modified.
1711 * If @length is non-%NULL then the number of elements in the result
1712 * is stored there. In any case, the resulting array will be
1713 * %NULL-terminated.
1715 * For an empty array, @length will be set to 0 and a pointer to a
1716 * %NULL pointer will be returned.
1718 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1720 * Since: 2.30
1722 const gchar **
1723 g_variant_get_objv (GVariant *value,
1724 gsize *length)
1726 const gchar **strv;
1727 gsize n;
1728 gsize i;
1730 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1732 g_variant_get_data (value);
1733 n = g_variant_n_children (value);
1734 strv = g_new (const gchar *, n + 1);
1736 for (i = 0; i < n; i++)
1738 GVariant *string;
1740 string = g_variant_get_child_value (value, i);
1741 strv[i] = g_variant_get_string (string, NULL);
1742 g_variant_unref (string);
1744 strv[i] = NULL;
1746 if (length)
1747 *length = n;
1749 return strv;
1753 * g_variant_dup_objv:
1754 * @value: an array of object paths #GVariant
1755 * @length: (out) (optional): the length of the result, or %NULL
1757 * Gets the contents of an array of object paths #GVariant. This call
1758 * makes a deep copy; the return result should be released with
1759 * g_strfreev().
1761 * If @length is non-%NULL then the number of elements in the result
1762 * is stored there. In any case, the resulting array will be
1763 * %NULL-terminated.
1765 * For an empty array, @length will be set to 0 and a pointer to a
1766 * %NULL pointer will be returned.
1768 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1770 * Since: 2.30
1772 gchar **
1773 g_variant_dup_objv (GVariant *value,
1774 gsize *length)
1776 gchar **strv;
1777 gsize n;
1778 gsize i;
1780 TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1782 n = g_variant_n_children (value);
1783 strv = g_new (gchar *, n + 1);
1785 for (i = 0; i < n; i++)
1787 GVariant *string;
1789 string = g_variant_get_child_value (value, i);
1790 strv[i] = g_variant_dup_string (string, NULL);
1791 g_variant_unref (string);
1793 strv[i] = NULL;
1795 if (length)
1796 *length = n;
1798 return strv;
1803 * g_variant_new_bytestring:
1804 * @string: (array zero-terminated=1) (element-type guint8): a normal
1805 * nul-terminated string in no particular encoding
1807 * Creates an array-of-bytes #GVariant with the contents of @string.
1808 * This function is just like g_variant_new_string() except that the
1809 * string need not be valid UTF-8.
1811 * The nul terminator character at the end of the string is stored in
1812 * the array.
1814 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1816 * Since: 2.26
1818 GVariant *
1819 g_variant_new_bytestring (const gchar *string)
1821 g_return_val_if_fail (string != NULL, NULL);
1823 return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1824 string, strlen (string) + 1);
1828 * g_variant_get_bytestring:
1829 * @value: an array-of-bytes #GVariant instance
1831 * Returns the string value of a #GVariant instance with an
1832 * array-of-bytes type. The string has no particular encoding.
1834 * If the array does not end with a nul terminator character, the empty
1835 * string is returned. For this reason, you can always trust that a
1836 * non-%NULL nul-terminated string will be returned by this function.
1838 * If the array contains a nul terminator character somewhere other than
1839 * the last byte then the returned string is the string, up to the first
1840 * such nul character.
1842 * g_variant_get_fixed_array() should be used instead if the array contains
1843 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1845 * It is an error to call this function with a @value that is not an
1846 * array of bytes.
1848 * The return value remains valid as long as @value exists.
1850 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1851 * the constant string
1853 * Since: 2.26
1855 const gchar *
1856 g_variant_get_bytestring (GVariant *value)
1858 const gchar *string;
1859 gsize size;
1861 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1863 /* Won't be NULL since this is an array type */
1864 string = g_variant_get_data (value);
1865 size = g_variant_get_size (value);
1867 if (size && string[size - 1] == '\0')
1868 return string;
1869 else
1870 return "";
1874 * g_variant_dup_bytestring:
1875 * @value: an array-of-bytes #GVariant instance
1876 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1877 * the length (not including the nul terminator)
1879 * Similar to g_variant_get_bytestring() except that instead of
1880 * returning a constant string, the string is duplicated.
1882 * The return value must be freed using g_free().
1884 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1885 * a newly allocated string
1887 * Since: 2.26
1889 gchar *
1890 g_variant_dup_bytestring (GVariant *value,
1891 gsize *length)
1893 const gchar *original = g_variant_get_bytestring (value);
1894 gsize size;
1896 /* don't crash in case get_bytestring() had an assert failure */
1897 if (original == NULL)
1898 return NULL;
1900 size = strlen (original);
1902 if (length)
1903 *length = size;
1905 return g_memdup (original, size + 1);
1909 * g_variant_new_bytestring_array:
1910 * @strv: (array length=length): an array of strings
1911 * @length: the length of @strv, or -1
1913 * Constructs an array of bytestring #GVariant from the given array of
1914 * strings.
1916 * If @length is -1 then @strv is %NULL-terminated.
1918 * Returns: (transfer none): a new floating #GVariant instance
1920 * Since: 2.26
1922 GVariant *
1923 g_variant_new_bytestring_array (const gchar * const *strv,
1924 gssize length)
1926 GVariant **strings;
1927 gsize i;
1929 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1931 if (length < 0)
1932 length = g_strv_length ((gchar **) strv);
1934 strings = g_new (GVariant *, length);
1935 for (i = 0; i < length; i++)
1936 strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1938 return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1939 strings, length, TRUE);
1943 * g_variant_get_bytestring_array:
1944 * @value: an array of array of bytes #GVariant ('aay')
1945 * @length: (out) (optional): the length of the result, or %NULL
1947 * Gets the contents of an array of array of bytes #GVariant. This call
1948 * makes a shallow copy; the return result should be released with
1949 * g_free(), but the individual strings must not be modified.
1951 * If @length is non-%NULL then the number of elements in the result is
1952 * stored there. In any case, the resulting array will be
1953 * %NULL-terminated.
1955 * For an empty array, @length will be set to 0 and a pointer to a
1956 * %NULL pointer will be returned.
1958 * Returns: (array length=length) (transfer container): an array of constant strings
1960 * Since: 2.26
1962 const gchar **
1963 g_variant_get_bytestring_array (GVariant *value,
1964 gsize *length)
1966 const gchar **strv;
1967 gsize n;
1968 gsize i;
1970 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1972 g_variant_get_data (value);
1973 n = g_variant_n_children (value);
1974 strv = g_new (const gchar *, n + 1);
1976 for (i = 0; i < n; i++)
1978 GVariant *string;
1980 string = g_variant_get_child_value (value, i);
1981 strv[i] = g_variant_get_bytestring (string);
1982 g_variant_unref (string);
1984 strv[i] = NULL;
1986 if (length)
1987 *length = n;
1989 return strv;
1993 * g_variant_dup_bytestring_array:
1994 * @value: an array of array of bytes #GVariant ('aay')
1995 * @length: (out) (optional): the length of the result, or %NULL
1997 * Gets the contents of an array of array of bytes #GVariant. This call
1998 * makes a deep copy; the return result should be released with
1999 * g_strfreev().
2001 * If @length is non-%NULL then the number of elements in the result is
2002 * stored there. In any case, the resulting array will be
2003 * %NULL-terminated.
2005 * For an empty array, @length will be set to 0 and a pointer to a
2006 * %NULL pointer will be returned.
2008 * Returns: (array length=length) (transfer full): an array of strings
2010 * Since: 2.26
2012 gchar **
2013 g_variant_dup_bytestring_array (GVariant *value,
2014 gsize *length)
2016 gchar **strv;
2017 gsize n;
2018 gsize i;
2020 TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2022 g_variant_get_data (value);
2023 n = g_variant_n_children (value);
2024 strv = g_new (gchar *, n + 1);
2026 for (i = 0; i < n; i++)
2028 GVariant *string;
2030 string = g_variant_get_child_value (value, i);
2031 strv[i] = g_variant_dup_bytestring (string, NULL);
2032 g_variant_unref (string);
2034 strv[i] = NULL;
2036 if (length)
2037 *length = n;
2039 return strv;
2042 /* Type checking and querying {{{1 */
2044 * g_variant_get_type:
2045 * @value: a #GVariant
2047 * Determines the type of @value.
2049 * The return value is valid for the lifetime of @value and must not
2050 * be freed.
2052 * Returns: a #GVariantType
2054 * Since: 2.24
2056 const GVariantType *
2057 g_variant_get_type (GVariant *value)
2059 GVariantTypeInfo *type_info;
2061 g_return_val_if_fail (value != NULL, NULL);
2063 type_info = g_variant_get_type_info (value);
2065 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2069 * g_variant_get_type_string:
2070 * @value: a #GVariant
2072 * Returns the type string of @value. Unlike the result of calling
2073 * g_variant_type_peek_string(), this string is nul-terminated. This
2074 * string belongs to #GVariant and must not be freed.
2076 * Returns: the type string for the type of @value
2078 * Since: 2.24
2080 const gchar *
2081 g_variant_get_type_string (GVariant *value)
2083 GVariantTypeInfo *type_info;
2085 g_return_val_if_fail (value != NULL, NULL);
2087 type_info = g_variant_get_type_info (value);
2089 return g_variant_type_info_get_type_string (type_info);
2093 * g_variant_is_of_type:
2094 * @value: a #GVariant instance
2095 * @type: a #GVariantType
2097 * Checks if a value has a type matching the provided type.
2099 * Returns: %TRUE if the type of @value matches @type
2101 * Since: 2.24
2103 gboolean
2104 g_variant_is_of_type (GVariant *value,
2105 const GVariantType *type)
2107 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2111 * g_variant_is_container:
2112 * @value: a #GVariant instance
2114 * Checks if @value is a container.
2116 * Returns: %TRUE if @value is a container
2118 * Since: 2.24
2120 gboolean
2121 g_variant_is_container (GVariant *value)
2123 return g_variant_type_is_container (g_variant_get_type (value));
2128 * g_variant_classify:
2129 * @value: a #GVariant
2131 * Classifies @value according to its top-level type.
2133 * Returns: the #GVariantClass of @value
2135 * Since: 2.24
2138 * GVariantClass:
2139 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2140 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2141 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2142 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2143 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2144 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2145 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2146 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2147 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2148 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
2149 * point value.
2150 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2151 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
2152 * string.
2153 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2154 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2155 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2156 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2157 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2158 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2160 * The range of possible top-level types of #GVariant instances.
2162 * Since: 2.24
2164 GVariantClass
2165 g_variant_classify (GVariant *value)
2167 g_return_val_if_fail (value != NULL, 0);
2169 return *g_variant_get_type_string (value);
2172 /* Pretty printer {{{1 */
2173 /* This function is not introspectable because if @string is NULL,
2174 @returns is (transfer full), otherwise it is (transfer none), which
2175 is not supported by GObjectIntrospection */
2177 * g_variant_print_string: (skip)
2178 * @value: a #GVariant
2179 * @string: (nullable) (default NULL): a #GString, or %NULL
2180 * @type_annotate: %TRUE if type information should be included in
2181 * the output
2183 * Behaves as g_variant_print(), but operates on a #GString.
2185 * If @string is non-%NULL then it is appended to and returned. Else,
2186 * a new empty #GString is allocated and it is returned.
2188 * Returns: a #GString containing the string
2190 * Since: 2.24
2192 GString *
2193 g_variant_print_string (GVariant *value,
2194 GString *string,
2195 gboolean type_annotate)
2197 if G_UNLIKELY (string == NULL)
2198 string = g_string_new (NULL);
2200 switch (g_variant_classify (value))
2202 case G_VARIANT_CLASS_MAYBE:
2203 if (type_annotate)
2204 g_string_append_printf (string, "@%s ",
2205 g_variant_get_type_string (value));
2207 if (g_variant_n_children (value))
2209 gchar *printed_child;
2210 GVariant *element;
2212 /* Nested maybes:
2214 * Consider the case of the type "mmi". In this case we could
2215 * write "just just 4", but "4" alone is totally unambiguous,
2216 * so we try to drop "just" where possible.
2218 * We have to be careful not to always drop "just", though,
2219 * since "nothing" needs to be distinguishable from "just
2220 * nothing". The case where we need to ensure we keep the
2221 * "just" is actually exactly the case where we have a nested
2222 * Nothing.
2224 * Instead of searching for that nested Nothing, we just print
2225 * the contained value into a separate string and see if we
2226 * end up with "nothing" at the end of it. If so, we need to
2227 * add "just" at our level.
2229 element = g_variant_get_child_value (value, 0);
2230 printed_child = g_variant_print (element, FALSE);
2231 g_variant_unref (element);
2233 if (g_str_has_suffix (printed_child, "nothing"))
2234 g_string_append (string, "just ");
2235 g_string_append (string, printed_child);
2236 g_free (printed_child);
2238 else
2239 g_string_append (string, "nothing");
2241 break;
2243 case G_VARIANT_CLASS_ARRAY:
2244 /* it's an array so the first character of the type string is 'a'
2246 * if the first two characters are 'ay' then it's a bytestring.
2247 * under certain conditions we print those as strings.
2249 if (g_variant_get_type_string (value)[1] == 'y')
2251 const gchar *str;
2252 gsize size;
2253 gsize i;
2255 /* first determine if it is a byte string.
2256 * that's when there's a single nul character: at the end.
2258 str = g_variant_get_data (value);
2259 size = g_variant_get_size (value);
2261 for (i = 0; i < size; i++)
2262 if (str[i] == '\0')
2263 break;
2265 /* first nul byte is the last byte -> it's a byte string. */
2266 if (i == size - 1)
2268 gchar *escaped = g_strescape (str, NULL);
2270 /* use double quotes only if a ' is in the string */
2271 if (strchr (str, '\''))
2272 g_string_append_printf (string, "b\"%s\"", escaped);
2273 else
2274 g_string_append_printf (string, "b'%s'", escaped);
2276 g_free (escaped);
2277 break;
2280 else
2282 /* fall through and handle normally... */
2287 * if the first two characters are 'a{' then it's an array of
2288 * dictionary entries (ie: a dictionary) so we print that
2289 * differently.
2291 if (g_variant_get_type_string (value)[1] == '{')
2292 /* dictionary */
2294 const gchar *comma = "";
2295 gsize n, i;
2297 if ((n = g_variant_n_children (value)) == 0)
2299 if (type_annotate)
2300 g_string_append_printf (string, "@%s ",
2301 g_variant_get_type_string (value));
2302 g_string_append (string, "{}");
2303 break;
2306 g_string_append_c (string, '{');
2307 for (i = 0; i < n; i++)
2309 GVariant *entry, *key, *val;
2311 g_string_append (string, comma);
2312 comma = ", ";
2314 entry = g_variant_get_child_value (value, i);
2315 key = g_variant_get_child_value (entry, 0);
2316 val = g_variant_get_child_value (entry, 1);
2317 g_variant_unref (entry);
2319 g_variant_print_string (key, string, type_annotate);
2320 g_variant_unref (key);
2321 g_string_append (string, ": ");
2322 g_variant_print_string (val, string, type_annotate);
2323 g_variant_unref (val);
2324 type_annotate = FALSE;
2326 g_string_append_c (string, '}');
2328 else
2329 /* normal (non-dictionary) array */
2331 const gchar *comma = "";
2332 gsize n, i;
2334 if ((n = g_variant_n_children (value)) == 0)
2336 if (type_annotate)
2337 g_string_append_printf (string, "@%s ",
2338 g_variant_get_type_string (value));
2339 g_string_append (string, "[]");
2340 break;
2343 g_string_append_c (string, '[');
2344 for (i = 0; i < n; i++)
2346 GVariant *element;
2348 g_string_append (string, comma);
2349 comma = ", ";
2351 element = g_variant_get_child_value (value, i);
2353 g_variant_print_string (element, string, type_annotate);
2354 g_variant_unref (element);
2355 type_annotate = FALSE;
2357 g_string_append_c (string, ']');
2360 break;
2362 case G_VARIANT_CLASS_TUPLE:
2364 gsize n, i;
2366 n = g_variant_n_children (value);
2368 g_string_append_c (string, '(');
2369 for (i = 0; i < n; i++)
2371 GVariant *element;
2373 element = g_variant_get_child_value (value, i);
2374 g_variant_print_string (element, string, type_annotate);
2375 g_string_append (string, ", ");
2376 g_variant_unref (element);
2379 /* for >1 item: remove final ", "
2380 * for 1 item: remove final " ", but leave the ","
2381 * for 0 items: there is only "(", so remove nothing
2383 g_string_truncate (string, string->len - (n > 0) - (n > 1));
2384 g_string_append_c (string, ')');
2386 break;
2388 case G_VARIANT_CLASS_DICT_ENTRY:
2390 GVariant *element;
2392 g_string_append_c (string, '{');
2394 element = g_variant_get_child_value (value, 0);
2395 g_variant_print_string (element, string, type_annotate);
2396 g_variant_unref (element);
2398 g_string_append (string, ", ");
2400 element = g_variant_get_child_value (value, 1);
2401 g_variant_print_string (element, string, type_annotate);
2402 g_variant_unref (element);
2404 g_string_append_c (string, '}');
2406 break;
2408 case G_VARIANT_CLASS_VARIANT:
2410 GVariant *child = g_variant_get_variant (value);
2412 /* Always annotate types in nested variants, because they are
2413 * (by nature) of variable type.
2415 g_string_append_c (string, '<');
2416 g_variant_print_string (child, string, TRUE);
2417 g_string_append_c (string, '>');
2419 g_variant_unref (child);
2421 break;
2423 case G_VARIANT_CLASS_BOOLEAN:
2424 if (g_variant_get_boolean (value))
2425 g_string_append (string, "true");
2426 else
2427 g_string_append (string, "false");
2428 break;
2430 case G_VARIANT_CLASS_STRING:
2432 const gchar *str = g_variant_get_string (value, NULL);
2433 gunichar quote = strchr (str, '\'') ? '"' : '\'';
2435 g_string_append_c (string, quote);
2437 while (*str)
2439 gunichar c = g_utf8_get_char (str);
2441 if (c == quote || c == '\\')
2442 g_string_append_c (string, '\\');
2444 if (g_unichar_isprint (c))
2445 g_string_append_unichar (string, c);
2447 else
2449 g_string_append_c (string, '\\');
2450 if (c < 0x10000)
2451 switch (c)
2453 case '\a':
2454 g_string_append_c (string, 'a');
2455 break;
2457 case '\b':
2458 g_string_append_c (string, 'b');
2459 break;
2461 case '\f':
2462 g_string_append_c (string, 'f');
2463 break;
2465 case '\n':
2466 g_string_append_c (string, 'n');
2467 break;
2469 case '\r':
2470 g_string_append_c (string, 'r');
2471 break;
2473 case '\t':
2474 g_string_append_c (string, 't');
2475 break;
2477 case '\v':
2478 g_string_append_c (string, 'v');
2479 break;
2481 default:
2482 g_string_append_printf (string, "u%04x", c);
2483 break;
2485 else
2486 g_string_append_printf (string, "U%08x", c);
2489 str = g_utf8_next_char (str);
2492 g_string_append_c (string, quote);
2494 break;
2496 case G_VARIANT_CLASS_BYTE:
2497 if (type_annotate)
2498 g_string_append (string, "byte ");
2499 g_string_append_printf (string, "0x%02x",
2500 g_variant_get_byte (value));
2501 break;
2503 case G_VARIANT_CLASS_INT16:
2504 if (type_annotate)
2505 g_string_append (string, "int16 ");
2506 g_string_append_printf (string, "%"G_GINT16_FORMAT,
2507 g_variant_get_int16 (value));
2508 break;
2510 case G_VARIANT_CLASS_UINT16:
2511 if (type_annotate)
2512 g_string_append (string, "uint16 ");
2513 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2514 g_variant_get_uint16 (value));
2515 break;
2517 case G_VARIANT_CLASS_INT32:
2518 /* Never annotate this type because it is the default for numbers
2519 * (and this is a *pretty* printer)
2521 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2522 g_variant_get_int32 (value));
2523 break;
2525 case G_VARIANT_CLASS_HANDLE:
2526 if (type_annotate)
2527 g_string_append (string, "handle ");
2528 g_string_append_printf (string, "%"G_GINT32_FORMAT,
2529 g_variant_get_handle (value));
2530 break;
2532 case G_VARIANT_CLASS_UINT32:
2533 if (type_annotate)
2534 g_string_append (string, "uint32 ");
2535 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2536 g_variant_get_uint32 (value));
2537 break;
2539 case G_VARIANT_CLASS_INT64:
2540 if (type_annotate)
2541 g_string_append (string, "int64 ");
2542 g_string_append_printf (string, "%"G_GINT64_FORMAT,
2543 g_variant_get_int64 (value));
2544 break;
2546 case G_VARIANT_CLASS_UINT64:
2547 if (type_annotate)
2548 g_string_append (string, "uint64 ");
2549 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2550 g_variant_get_uint64 (value));
2551 break;
2553 case G_VARIANT_CLASS_DOUBLE:
2555 gchar buffer[100];
2556 gint i;
2558 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2560 for (i = 0; buffer[i]; i++)
2561 if (buffer[i] == '.' || buffer[i] == 'e' ||
2562 buffer[i] == 'n' || buffer[i] == 'N')
2563 break;
2565 /* if there is no '.' or 'e' in the float then add one */
2566 if (buffer[i] == '\0')
2568 buffer[i++] = '.';
2569 buffer[i++] = '0';
2570 buffer[i++] = '\0';
2573 g_string_append (string, buffer);
2575 break;
2577 case G_VARIANT_CLASS_OBJECT_PATH:
2578 if (type_annotate)
2579 g_string_append (string, "objectpath ");
2580 g_string_append_printf (string, "\'%s\'",
2581 g_variant_get_string (value, NULL));
2582 break;
2584 case G_VARIANT_CLASS_SIGNATURE:
2585 if (type_annotate)
2586 g_string_append (string, "signature ");
2587 g_string_append_printf (string, "\'%s\'",
2588 g_variant_get_string (value, NULL));
2589 break;
2591 default:
2592 g_assert_not_reached ();
2595 return string;
2599 * g_variant_print:
2600 * @value: a #GVariant
2601 * @type_annotate: %TRUE if type information should be included in
2602 * the output
2604 * Pretty-prints @value in the format understood by g_variant_parse().
2606 * The format is described [here][gvariant-text].
2608 * If @type_annotate is %TRUE, then type information is included in
2609 * the output.
2611 * Returns: (transfer full): a newly-allocated string holding the result.
2613 * Since: 2.24
2615 gchar *
2616 g_variant_print (GVariant *value,
2617 gboolean type_annotate)
2619 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2620 FALSE);
2623 /* Hash, Equal, Compare {{{1 */
2625 * g_variant_hash:
2626 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2628 * Generates a hash value for a #GVariant instance.
2630 * The output of this function is guaranteed to be the same for a given
2631 * value only per-process. It may change between different processor
2632 * architectures or even different versions of GLib. Do not use this
2633 * function as a basis for building protocols or file formats.
2635 * The type of @value is #gconstpointer only to allow use of this
2636 * function with #GHashTable. @value must be a #GVariant.
2638 * Returns: a hash value corresponding to @value
2640 * Since: 2.24
2642 guint
2643 g_variant_hash (gconstpointer value_)
2645 GVariant *value = (GVariant *) value_;
2647 switch (g_variant_classify (value))
2649 case G_VARIANT_CLASS_STRING:
2650 case G_VARIANT_CLASS_OBJECT_PATH:
2651 case G_VARIANT_CLASS_SIGNATURE:
2652 return g_str_hash (g_variant_get_string (value, NULL));
2654 case G_VARIANT_CLASS_BOOLEAN:
2655 /* this is a very odd thing to hash... */
2656 return g_variant_get_boolean (value);
2658 case G_VARIANT_CLASS_BYTE:
2659 return g_variant_get_byte (value);
2661 case G_VARIANT_CLASS_INT16:
2662 case G_VARIANT_CLASS_UINT16:
2664 const guint16 *ptr;
2666 ptr = g_variant_get_data (value);
2668 if (ptr)
2669 return *ptr;
2670 else
2671 return 0;
2674 case G_VARIANT_CLASS_INT32:
2675 case G_VARIANT_CLASS_UINT32:
2676 case G_VARIANT_CLASS_HANDLE:
2678 const guint *ptr;
2680 ptr = g_variant_get_data (value);
2682 if (ptr)
2683 return *ptr;
2684 else
2685 return 0;
2688 case G_VARIANT_CLASS_INT64:
2689 case G_VARIANT_CLASS_UINT64:
2690 case G_VARIANT_CLASS_DOUBLE:
2691 /* need a separate case for these guys because otherwise
2692 * performance could be quite bad on big endian systems
2695 const guint *ptr;
2697 ptr = g_variant_get_data (value);
2699 if (ptr)
2700 return ptr[0] + ptr[1];
2701 else
2702 return 0;
2705 default:
2706 g_return_val_if_fail (!g_variant_is_container (value), 0);
2707 g_assert_not_reached ();
2712 * g_variant_equal:
2713 * @one: (type GVariant): a #GVariant instance
2714 * @two: (type GVariant): a #GVariant instance
2716 * Checks if @one and @two have the same type and value.
2718 * The types of @one and @two are #gconstpointer only to allow use of
2719 * this function with #GHashTable. They must each be a #GVariant.
2721 * Returns: %TRUE if @one and @two are equal
2723 * Since: 2.24
2725 gboolean
2726 g_variant_equal (gconstpointer one,
2727 gconstpointer two)
2729 gboolean equal;
2731 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2733 if (g_variant_get_type_info ((GVariant *) one) !=
2734 g_variant_get_type_info ((GVariant *) two))
2735 return FALSE;
2737 /* if both values are trusted to be in their canonical serialised form
2738 * then a simple memcmp() of their serialised data will answer the
2739 * question.
2741 * if not, then this might generate a false negative (since it is
2742 * possible for two different byte sequences to represent the same
2743 * value). for now we solve this by pretty-printing both values and
2744 * comparing the result.
2746 if (g_variant_is_trusted ((GVariant *) one) &&
2747 g_variant_is_trusted ((GVariant *) two))
2749 gconstpointer data_one, data_two;
2750 gsize size_one, size_two;
2752 size_one = g_variant_get_size ((GVariant *) one);
2753 size_two = g_variant_get_size ((GVariant *) two);
2755 if (size_one != size_two)
2756 return FALSE;
2758 data_one = g_variant_get_data ((GVariant *) one);
2759 data_two = g_variant_get_data ((GVariant *) two);
2761 equal = memcmp (data_one, data_two, size_one) == 0;
2763 else
2765 gchar *strone, *strtwo;
2767 strone = g_variant_print ((GVariant *) one, FALSE);
2768 strtwo = g_variant_print ((GVariant *) two, FALSE);
2769 equal = strcmp (strone, strtwo) == 0;
2770 g_free (strone);
2771 g_free (strtwo);
2774 return equal;
2778 * g_variant_compare:
2779 * @one: (type GVariant): a basic-typed #GVariant instance
2780 * @two: (type GVariant): a #GVariant instance of the same type
2782 * Compares @one and @two.
2784 * The types of @one and @two are #gconstpointer only to allow use of
2785 * this function with #GTree, #GPtrArray, etc. They must each be a
2786 * #GVariant.
2788 * Comparison is only defined for basic types (ie: booleans, numbers,
2789 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2790 * ordered in the usual way. Strings are in ASCII lexographical order.
2792 * It is a programmer error to attempt to compare container values or
2793 * two values that have types that are not exactly equal. For example,
2794 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2795 * integer. Also note that this function is not particularly
2796 * well-behaved when it comes to comparison of doubles; in particular,
2797 * the handling of incomparable values (ie: NaN) is undefined.
2799 * If you only require an equality comparison, g_variant_equal() is more
2800 * general.
2802 * Returns: negative value if a < b;
2803 * zero if a = b;
2804 * positive value if a > b.
2806 * Since: 2.26
2808 gint
2809 g_variant_compare (gconstpointer one,
2810 gconstpointer two)
2812 GVariant *a = (GVariant *) one;
2813 GVariant *b = (GVariant *) two;
2815 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2817 switch (g_variant_classify (a))
2819 case G_VARIANT_CLASS_BOOLEAN:
2820 return g_variant_get_boolean (a) -
2821 g_variant_get_boolean (b);
2823 case G_VARIANT_CLASS_BYTE:
2824 return ((gint) g_variant_get_byte (a)) -
2825 ((gint) g_variant_get_byte (b));
2827 case G_VARIANT_CLASS_INT16:
2828 return ((gint) g_variant_get_int16 (a)) -
2829 ((gint) g_variant_get_int16 (b));
2831 case G_VARIANT_CLASS_UINT16:
2832 return ((gint) g_variant_get_uint16 (a)) -
2833 ((gint) g_variant_get_uint16 (b));
2835 case G_VARIANT_CLASS_INT32:
2837 gint32 a_val = g_variant_get_int32 (a);
2838 gint32 b_val = g_variant_get_int32 (b);
2840 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2843 case G_VARIANT_CLASS_UINT32:
2845 guint32 a_val = g_variant_get_uint32 (a);
2846 guint32 b_val = g_variant_get_uint32 (b);
2848 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2851 case G_VARIANT_CLASS_INT64:
2853 gint64 a_val = g_variant_get_int64 (a);
2854 gint64 b_val = g_variant_get_int64 (b);
2856 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2859 case G_VARIANT_CLASS_UINT64:
2861 guint64 a_val = g_variant_get_uint64 (a);
2862 guint64 b_val = g_variant_get_uint64 (b);
2864 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2867 case G_VARIANT_CLASS_DOUBLE:
2869 gdouble a_val = g_variant_get_double (a);
2870 gdouble b_val = g_variant_get_double (b);
2872 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2875 case G_VARIANT_CLASS_STRING:
2876 case G_VARIANT_CLASS_OBJECT_PATH:
2877 case G_VARIANT_CLASS_SIGNATURE:
2878 return strcmp (g_variant_get_string (a, NULL),
2879 g_variant_get_string (b, NULL));
2881 default:
2882 g_return_val_if_fail (!g_variant_is_container (a), 0);
2883 g_assert_not_reached ();
2887 /* GVariantIter {{{1 */
2889 * GVariantIter: (skip)
2891 * #GVariantIter is an opaque data structure and can only be accessed
2892 * using the following functions.
2894 struct stack_iter
2896 GVariant *value;
2897 gssize n, i;
2899 const gchar *loop_format;
2901 gsize padding[3];
2902 gsize magic;
2905 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2907 struct heap_iter
2909 struct stack_iter iter;
2911 GVariant *value_ref;
2912 gsize magic;
2915 #define GVSI(i) ((struct stack_iter *) (i))
2916 #define GVHI(i) ((struct heap_iter *) (i))
2917 #define GVSI_MAGIC ((gsize) 3579507750u)
2918 #define GVHI_MAGIC ((gsize) 1450270775u)
2919 #define is_valid_iter(i) (i != NULL && \
2920 GVSI(i)->magic == GVSI_MAGIC)
2921 #define is_valid_heap_iter(i) (is_valid_iter(i) && \
2922 GVHI(i)->magic == GVHI_MAGIC)
2925 * g_variant_iter_new:
2926 * @value: a container #GVariant
2928 * Creates a heap-allocated #GVariantIter for iterating over the items
2929 * in @value.
2931 * Use g_variant_iter_free() to free the return value when you no longer
2932 * need it.
2934 * A reference is taken to @value and will be released only when
2935 * g_variant_iter_free() is called.
2937 * Returns: (transfer full): a new heap-allocated #GVariantIter
2939 * Since: 2.24
2941 GVariantIter *
2942 g_variant_iter_new (GVariant *value)
2944 GVariantIter *iter;
2946 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2947 GVHI(iter)->value_ref = g_variant_ref (value);
2948 GVHI(iter)->magic = GVHI_MAGIC;
2950 g_variant_iter_init (iter, value);
2952 return iter;
2956 * g_variant_iter_init: (skip)
2957 * @iter: a pointer to a #GVariantIter
2958 * @value: a container #GVariant
2960 * Initialises (without allocating) a #GVariantIter. @iter may be
2961 * completely uninitialised prior to this call; its old value is
2962 * ignored.
2964 * The iterator remains valid for as long as @value exists, and need not
2965 * be freed in any way.
2967 * Returns: the number of items in @value
2969 * Since: 2.24
2971 gsize
2972 g_variant_iter_init (GVariantIter *iter,
2973 GVariant *value)
2975 GVSI(iter)->magic = GVSI_MAGIC;
2976 GVSI(iter)->value = value;
2977 GVSI(iter)->n = g_variant_n_children (value);
2978 GVSI(iter)->i = -1;
2979 GVSI(iter)->loop_format = NULL;
2981 return GVSI(iter)->n;
2985 * g_variant_iter_copy:
2986 * @iter: a #GVariantIter
2988 * Creates a new heap-allocated #GVariantIter to iterate over the
2989 * container that was being iterated over by @iter. Iteration begins on
2990 * the new iterator from the current position of the old iterator but
2991 * the two copies are independent past that point.
2993 * Use g_variant_iter_free() to free the return value when you no longer
2994 * need it.
2996 * A reference is taken to the container that @iter is iterating over
2997 * and will be releated only when g_variant_iter_free() is called.
2999 * Returns: (transfer full): a new heap-allocated #GVariantIter
3001 * Since: 2.24
3003 GVariantIter *
3004 g_variant_iter_copy (GVariantIter *iter)
3006 GVariantIter *copy;
3008 g_return_val_if_fail (is_valid_iter (iter), 0);
3010 copy = g_variant_iter_new (GVSI(iter)->value);
3011 GVSI(copy)->i = GVSI(iter)->i;
3013 return copy;
3017 * g_variant_iter_n_children:
3018 * @iter: a #GVariantIter
3020 * Queries the number of child items in the container that we are
3021 * iterating over. This is the total number of items -- not the number
3022 * of items remaining.
3024 * This function might be useful for preallocation of arrays.
3026 * Returns: the number of children in the container
3028 * Since: 2.24
3030 gsize
3031 g_variant_iter_n_children (GVariantIter *iter)
3033 g_return_val_if_fail (is_valid_iter (iter), 0);
3035 return GVSI(iter)->n;
3039 * g_variant_iter_free:
3040 * @iter: (transfer full): a heap-allocated #GVariantIter
3042 * Frees a heap-allocated #GVariantIter. Only call this function on
3043 * iterators that were returned by g_variant_iter_new() or
3044 * g_variant_iter_copy().
3046 * Since: 2.24
3048 void
3049 g_variant_iter_free (GVariantIter *iter)
3051 g_return_if_fail (is_valid_heap_iter (iter));
3053 g_variant_unref (GVHI(iter)->value_ref);
3054 GVHI(iter)->magic = 0;
3056 g_slice_free (struct heap_iter, GVHI(iter));
3060 * g_variant_iter_next_value:
3061 * @iter: a #GVariantIter
3063 * Gets the next item in the container. If no more items remain then
3064 * %NULL is returned.
3066 * Use g_variant_unref() to drop your reference on the return value when
3067 * you no longer need it.
3069 * Here is an example for iterating with g_variant_iter_next_value():
3070 * |[<!-- language="C" -->
3071 * // recursively iterate a container
3072 * void
3073 * iterate_container_recursive (GVariant *container)
3075 * GVariantIter iter;
3076 * GVariant *child;
3078 * g_variant_iter_init (&iter, container);
3079 * while ((child = g_variant_iter_next_value (&iter)))
3081 * g_print ("type '%s'\n", g_variant_get_type_string (child));
3083 * if (g_variant_is_container (child))
3084 * iterate_container_recursive (child);
3086 * g_variant_unref (child);
3089 * ]|
3091 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3093 * Since: 2.24
3095 GVariant *
3096 g_variant_iter_next_value (GVariantIter *iter)
3098 g_return_val_if_fail (is_valid_iter (iter), FALSE);
3100 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3102 g_critical ("g_variant_iter_next_value: must not be called again "
3103 "after NULL has already been returned.");
3104 return NULL;
3107 GVSI(iter)->i++;
3109 if (GVSI(iter)->i < GVSI(iter)->n)
3110 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3112 return NULL;
3115 /* GVariantBuilder {{{1 */
3117 * GVariantBuilder:
3119 * A utility type for constructing container-type #GVariant instances.
3121 * This is an opaque structure and may only be accessed using the
3122 * following functions.
3124 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
3125 * access it from more than one thread.
3128 struct stack_builder
3130 GVariantBuilder *parent;
3131 GVariantType *type;
3133 /* type constraint explicitly specified by 'type'.
3134 * for tuple types, this moves along as we add more items.
3136 const GVariantType *expected_type;
3138 /* type constraint implied by previous array item.
3140 const GVariantType *prev_item_type;
3142 /* constraints on the number of children. max = -1 for unlimited. */
3143 gsize min_items;
3144 gsize max_items;
3146 /* dynamically-growing pointer array */
3147 GVariant **children;
3148 gsize allocated_children;
3149 gsize offset;
3151 /* set to '1' if all items in the container will have the same type
3152 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3154 guint uniform_item_types : 1;
3156 /* set to '1' initially and changed to '0' if an untrusted value is
3157 * added
3159 guint trusted : 1;
3161 gsize magic;
3164 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3166 struct heap_builder
3168 GVariantBuilder builder;
3169 gsize magic;
3171 gint ref_count;
3174 #define GVSB(b) ((struct stack_builder *) (b))
3175 #define GVHB(b) ((struct heap_builder *) (b))
3176 #define GVSB_MAGIC ((gsize) 1033660112u)
3177 #define GVSB_MAGIC_PARTIAL ((gsize) 2942751021u)
3178 #define GVHB_MAGIC ((gsize) 3087242682u)
3179 #define is_valid_builder(b) (b != NULL && \
3180 GVSB(b)->magic == GVSB_MAGIC)
3181 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3183 /* Just to make sure that by adding a union to GVariantBuilder, we
3184 * didn't accidentally change ABI. */
3185 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3187 static gboolean
3188 ensure_valid_builder (GVariantBuilder *builder)
3190 if (is_valid_builder (builder))
3191 return TRUE;
3192 if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3194 static GVariantBuilder cleared_builder;
3196 /* Make sure that only first two fields were set and the rest is
3197 * zeroed to avoid messing up the builder that had parent
3198 * address equal to GVSB_MAGIC_PARTIAL. */
3199 if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3200 return FALSE;
3202 g_variant_builder_init (builder, builder->u.s.type);
3204 return is_valid_builder (builder);
3208 * g_variant_builder_new:
3209 * @type: a container type
3211 * Allocates and initialises a new #GVariantBuilder.
3213 * You should call g_variant_builder_unref() on the return value when it
3214 * is no longer needed. The memory will not be automatically freed by
3215 * any other call.
3217 * In most cases it is easier to place a #GVariantBuilder directly on
3218 * the stack of the calling function and initialise it with
3219 * g_variant_builder_init().
3221 * Returns: (transfer full): a #GVariantBuilder
3223 * Since: 2.24
3225 GVariantBuilder *
3226 g_variant_builder_new (const GVariantType *type)
3228 GVariantBuilder *builder;
3230 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3231 g_variant_builder_init (builder, type);
3232 GVHB(builder)->magic = GVHB_MAGIC;
3233 GVHB(builder)->ref_count = 1;
3235 return builder;
3239 * g_variant_builder_unref:
3240 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3242 * Decreases the reference count on @builder.
3244 * In the event that there are no more references, releases all memory
3245 * associated with the #GVariantBuilder.
3247 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3248 * things will happen.
3250 * Since: 2.24
3252 void
3253 g_variant_builder_unref (GVariantBuilder *builder)
3255 g_return_if_fail (is_valid_heap_builder (builder));
3257 if (--GVHB(builder)->ref_count)
3258 return;
3260 g_variant_builder_clear (builder);
3261 GVHB(builder)->magic = 0;
3263 g_slice_free (struct heap_builder, GVHB(builder));
3267 * g_variant_builder_ref:
3268 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3270 * Increases the reference count on @builder.
3272 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3273 * things will happen.
3275 * Returns: (transfer full): a new reference to @builder
3277 * Since: 2.24
3279 GVariantBuilder *
3280 g_variant_builder_ref (GVariantBuilder *builder)
3282 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3284 GVHB(builder)->ref_count++;
3286 return builder;
3290 * g_variant_builder_clear: (skip)
3291 * @builder: a #GVariantBuilder
3293 * Releases all memory associated with a #GVariantBuilder without
3294 * freeing the #GVariantBuilder structure itself.
3296 * It typically only makes sense to do this on a stack-allocated
3297 * #GVariantBuilder if you want to abort building the value part-way
3298 * through. This function need not be called if you call
3299 * g_variant_builder_end() and it also doesn't need to be called on
3300 * builders allocated with g_variant_builder_new (see
3301 * g_variant_builder_unref() for that).
3303 * This function leaves the #GVariantBuilder structure set to all-zeros.
3304 * It is valid to call this function on either an initialised
3305 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3306 * to call this function on uninitialised memory.
3308 * Since: 2.24
3310 void
3311 g_variant_builder_clear (GVariantBuilder *builder)
3313 gsize i;
3315 if (GVSB(builder)->magic == 0)
3316 /* all-zeros or partial case */
3317 return;
3319 g_return_if_fail (ensure_valid_builder (builder));
3321 g_variant_type_free (GVSB(builder)->type);
3323 for (i = 0; i < GVSB(builder)->offset; i++)
3324 g_variant_unref (GVSB(builder)->children[i]);
3326 g_free (GVSB(builder)->children);
3328 if (GVSB(builder)->parent)
3330 g_variant_builder_clear (GVSB(builder)->parent);
3331 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3334 memset (builder, 0, sizeof (GVariantBuilder));
3338 * g_variant_builder_init: (skip)
3339 * @builder: a #GVariantBuilder
3340 * @type: a container type
3342 * Initialises a #GVariantBuilder structure.
3344 * @type must be non-%NULL. It specifies the type of container to
3345 * construct. It can be an indefinite type such as
3346 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3347 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3348 * constructed.
3350 * After the builder is initialised, values are added using
3351 * g_variant_builder_add_value() or g_variant_builder_add().
3353 * After all the child values are added, g_variant_builder_end() frees
3354 * the memory associated with the builder and returns the #GVariant that
3355 * was created.
3357 * This function completely ignores the previous contents of @builder.
3358 * On one hand this means that it is valid to pass in completely
3359 * uninitialised memory. On the other hand, this means that if you are
3360 * initialising over top of an existing #GVariantBuilder you need to
3361 * first call g_variant_builder_clear() in order to avoid leaking
3362 * memory.
3364 * You must not call g_variant_builder_ref() or
3365 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3366 * with this function. If you ever pass a reference to a
3367 * #GVariantBuilder outside of the control of your own code then you
3368 * should assume that the person receiving that reference may try to use
3369 * reference counting; you should use g_variant_builder_new() instead of
3370 * this function.
3372 * Since: 2.24
3374 void
3375 g_variant_builder_init (GVariantBuilder *builder,
3376 const GVariantType *type)
3378 g_return_if_fail (type != NULL);
3379 g_return_if_fail (g_variant_type_is_container (type));
3381 memset (builder, 0, sizeof (GVariantBuilder));
3383 GVSB(builder)->type = g_variant_type_copy (type);
3384 GVSB(builder)->magic = GVSB_MAGIC;
3385 GVSB(builder)->trusted = TRUE;
3387 switch (*(const gchar *) type)
3389 case G_VARIANT_CLASS_VARIANT:
3390 GVSB(builder)->uniform_item_types = TRUE;
3391 GVSB(builder)->allocated_children = 1;
3392 GVSB(builder)->expected_type = NULL;
3393 GVSB(builder)->min_items = 1;
3394 GVSB(builder)->max_items = 1;
3395 break;
3397 case G_VARIANT_CLASS_ARRAY:
3398 GVSB(builder)->uniform_item_types = TRUE;
3399 GVSB(builder)->allocated_children = 8;
3400 GVSB(builder)->expected_type =
3401 g_variant_type_element (GVSB(builder)->type);
3402 GVSB(builder)->min_items = 0;
3403 GVSB(builder)->max_items = -1;
3404 break;
3406 case G_VARIANT_CLASS_MAYBE:
3407 GVSB(builder)->uniform_item_types = TRUE;
3408 GVSB(builder)->allocated_children = 1;
3409 GVSB(builder)->expected_type =
3410 g_variant_type_element (GVSB(builder)->type);
3411 GVSB(builder)->min_items = 0;
3412 GVSB(builder)->max_items = 1;
3413 break;
3415 case G_VARIANT_CLASS_DICT_ENTRY:
3416 GVSB(builder)->uniform_item_types = FALSE;
3417 GVSB(builder)->allocated_children = 2;
3418 GVSB(builder)->expected_type =
3419 g_variant_type_key (GVSB(builder)->type);
3420 GVSB(builder)->min_items = 2;
3421 GVSB(builder)->max_items = 2;
3422 break;
3424 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3425 GVSB(builder)->uniform_item_types = FALSE;
3426 GVSB(builder)->allocated_children = 8;
3427 GVSB(builder)->expected_type = NULL;
3428 GVSB(builder)->min_items = 0;
3429 GVSB(builder)->max_items = -1;
3430 break;
3432 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3433 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3434 GVSB(builder)->expected_type =
3435 g_variant_type_first (GVSB(builder)->type);
3436 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3437 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3438 GVSB(builder)->uniform_item_types = FALSE;
3439 break;
3441 default:
3442 g_assert_not_reached ();
3445 GVSB(builder)->children = g_new (GVariant *,
3446 GVSB(builder)->allocated_children);
3449 static void
3450 g_variant_builder_make_room (struct stack_builder *builder)
3452 if (builder->offset == builder->allocated_children)
3454 builder->allocated_children *= 2;
3455 builder->children = g_renew (GVariant *, builder->children,
3456 builder->allocated_children);
3461 * g_variant_builder_add_value:
3462 * @builder: a #GVariantBuilder
3463 * @value: a #GVariant
3465 * Adds @value to @builder.
3467 * It is an error to call this function in any way that would create an
3468 * inconsistent value to be constructed. Some examples of this are
3469 * putting different types of items into an array, putting the wrong
3470 * types or number of items in a tuple, putting more than one value into
3471 * a variant, etc.
3473 * If @value is a floating reference (see g_variant_ref_sink()),
3474 * the @builder instance takes ownership of @value.
3476 * Since: 2.24
3478 void
3479 g_variant_builder_add_value (GVariantBuilder *builder,
3480 GVariant *value)
3482 g_return_if_fail (ensure_valid_builder (builder));
3483 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3484 g_return_if_fail (!GVSB(builder)->expected_type ||
3485 g_variant_is_of_type (value,
3486 GVSB(builder)->expected_type));
3487 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3488 g_variant_is_of_type (value,
3489 GVSB(builder)->prev_item_type));
3491 GVSB(builder)->trusted &= g_variant_is_trusted (value);
3493 if (!GVSB(builder)->uniform_item_types)
3495 /* advance our expected type pointers */
3496 if (GVSB(builder)->expected_type)
3497 GVSB(builder)->expected_type =
3498 g_variant_type_next (GVSB(builder)->expected_type);
3500 if (GVSB(builder)->prev_item_type)
3501 GVSB(builder)->prev_item_type =
3502 g_variant_type_next (GVSB(builder)->prev_item_type);
3504 else
3505 GVSB(builder)->prev_item_type = g_variant_get_type (value);
3507 g_variant_builder_make_room (GVSB(builder));
3509 GVSB(builder)->children[GVSB(builder)->offset++] =
3510 g_variant_ref_sink (value);
3514 * g_variant_builder_open:
3515 * @builder: a #GVariantBuilder
3516 * @type: the #GVariantType of the container
3518 * Opens a subcontainer inside the given @builder. When done adding
3519 * items to the subcontainer, g_variant_builder_close() must be called. @type
3520 * is the type of the container: so to build a tuple of several values, @type
3521 * must include the tuple itself.
3523 * It is an error to call this function in any way that would cause an
3524 * inconsistent value to be constructed (ie: adding too many values or
3525 * a value of an incorrect type).
3527 * Example of building a nested variant:
3528 * |[<!-- language="C" -->
3529 * GVariantBuilder builder;
3530 * guint32 some_number = get_number ();
3531 * g_autoptr (GHashTable) some_dict = get_dict ();
3532 * GHashTableIter iter;
3533 * const gchar *key;
3534 * const GVariant *value;
3535 * g_autoptr (GVariant) output = NULL;
3537 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3538 * g_variant_builder_add (&builder, "u", some_number);
3539 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3541 * g_hash_table_iter_init (&iter, some_dict);
3542 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3544 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3545 * g_variant_builder_add (&builder, "s", key);
3546 * g_variant_builder_add (&builder, "v", value);
3547 * g_variant_builder_close (&builder);
3550 * g_variant_builder_close (&builder);
3552 * output = g_variant_builder_end (&builder);
3553 * ]|
3555 * Since: 2.24
3557 void
3558 g_variant_builder_open (GVariantBuilder *builder,
3559 const GVariantType *type)
3561 GVariantBuilder *parent;
3563 g_return_if_fail (ensure_valid_builder (builder));
3564 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3565 g_return_if_fail (!GVSB(builder)->expected_type ||
3566 g_variant_type_is_subtype_of (type,
3567 GVSB(builder)->expected_type));
3568 g_return_if_fail (!GVSB(builder)->prev_item_type ||
3569 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3570 type));
3572 parent = g_slice_dup (GVariantBuilder, builder);
3573 g_variant_builder_init (builder, type);
3574 GVSB(builder)->parent = parent;
3576 /* push the prev_item_type down into the subcontainer */
3577 if (GVSB(parent)->prev_item_type)
3579 if (!GVSB(builder)->uniform_item_types)
3580 /* tuples and dict entries */
3581 GVSB(builder)->prev_item_type =
3582 g_variant_type_first (GVSB(parent)->prev_item_type);
3584 else if (!g_variant_type_is_variant (GVSB(builder)->type))
3585 /* maybes and arrays */
3586 GVSB(builder)->prev_item_type =
3587 g_variant_type_element (GVSB(parent)->prev_item_type);
3592 * g_variant_builder_close:
3593 * @builder: a #GVariantBuilder
3595 * Closes the subcontainer inside the given @builder that was opened by
3596 * the most recent call to g_variant_builder_open().
3598 * It is an error to call this function in any way that would create an
3599 * inconsistent value to be constructed (ie: too few values added to the
3600 * subcontainer).
3602 * Since: 2.24
3604 void
3605 g_variant_builder_close (GVariantBuilder *builder)
3607 GVariantBuilder *parent;
3609 g_return_if_fail (ensure_valid_builder (builder));
3610 g_return_if_fail (GVSB(builder)->parent != NULL);
3612 parent = GVSB(builder)->parent;
3613 GVSB(builder)->parent = NULL;
3615 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3616 *builder = *parent;
3618 g_slice_free (GVariantBuilder, parent);
3621 /*< private >
3622 * g_variant_make_maybe_type:
3623 * @element: a #GVariant
3625 * Return the type of a maybe containing @element.
3627 static GVariantType *
3628 g_variant_make_maybe_type (GVariant *element)
3630 return g_variant_type_new_maybe (g_variant_get_type (element));
3633 /*< private >
3634 * g_variant_make_array_type:
3635 * @element: a #GVariant
3637 * Return the type of an array containing @element.
3639 static GVariantType *
3640 g_variant_make_array_type (GVariant *element)
3642 return g_variant_type_new_array (g_variant_get_type (element));
3646 * g_variant_builder_end:
3647 * @builder: a #GVariantBuilder
3649 * Ends the builder process and returns the constructed value.
3651 * It is not permissible to use @builder in any way after this call
3652 * except for reference counting operations (in the case of a
3653 * heap-allocated #GVariantBuilder) or by reinitialising it with
3654 * g_variant_builder_init() (in the case of stack-allocated). This
3655 * means that for the stack-allocated builders there is no need to
3656 * call g_variant_builder_clear() after the call to
3657 * g_variant_builder_end().
3659 * It is an error to call this function in any way that would create an
3660 * inconsistent value to be constructed (ie: insufficient number of
3661 * items added to a container with a specific number of children
3662 * required). It is also an error to call this function if the builder
3663 * was created with an indefinite array or maybe type and no children
3664 * have been added; in this case it is impossible to infer the type of
3665 * the empty array.
3667 * Returns: (transfer none): a new, floating, #GVariant
3669 * Since: 2.24
3671 GVariant *
3672 g_variant_builder_end (GVariantBuilder *builder)
3674 GVariantType *my_type;
3675 GVariant *value;
3677 g_return_val_if_fail (ensure_valid_builder (builder), NULL);
3678 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3679 NULL);
3680 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3681 GVSB(builder)->prev_item_type != NULL ||
3682 g_variant_type_is_definite (GVSB(builder)->type),
3683 NULL);
3685 if (g_variant_type_is_definite (GVSB(builder)->type))
3686 my_type = g_variant_type_copy (GVSB(builder)->type);
3688 else if (g_variant_type_is_maybe (GVSB(builder)->type))
3689 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3691 else if (g_variant_type_is_array (GVSB(builder)->type))
3692 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3694 else if (g_variant_type_is_tuple (GVSB(builder)->type))
3695 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3696 GVSB(builder)->offset);
3698 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3699 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3700 GVSB(builder)->children[1]);
3701 else
3702 g_assert_not_reached ();
3704 value = g_variant_new_from_children (my_type,
3705 g_renew (GVariant *,
3706 GVSB(builder)->children,
3707 GVSB(builder)->offset),
3708 GVSB(builder)->offset,
3709 GVSB(builder)->trusted);
3710 GVSB(builder)->children = NULL;
3711 GVSB(builder)->offset = 0;
3713 g_variant_builder_clear (builder);
3714 g_variant_type_free (my_type);
3716 return value;
3719 /* GVariantDict {{{1 */
3722 * GVariantDict:
3724 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3726 * It can be used for doing a sequence of dictionary lookups in an
3727 * efficient way on an existing #GVariant dictionary or it can be used
3728 * to construct new dictionaries with a hashtable-like interface. It
3729 * can also be used for taking existing dictionaries and modifying them
3730 * in order to create new ones.
3732 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3733 * dictionaries.
3735 * It is possible to use #GVariantDict allocated on the stack or on the
3736 * heap. When using a stack-allocated #GVariantDict, you begin with a
3737 * call to g_variant_dict_init() and free the resources with a call to
3738 * g_variant_dict_clear().
3740 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3741 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3742 * and g_variant_dict_unref().
3744 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3745 * dictionary-type #GVariant. When used with stack-allocated instances,
3746 * this also implicitly frees all associated memory, but for
3747 * heap-allocated instances, you must still call g_variant_dict_unref()
3748 * afterwards.
3750 * You will typically want to use a heap-allocated #GVariantDict when
3751 * you expose it as part of an API. For most other uses, the
3752 * stack-allocated form will be more convenient.
3754 * Consider the following two examples that do the same thing in each
3755 * style: take an existing dictionary and look up the "count" uint32
3756 * key, adding 1 to it if it is found, or returning an error if the
3757 * key is not found. Each returns the new dictionary as a floating
3758 * #GVariant.
3760 * ## Using a stack-allocated GVariantDict
3762 * |[<!-- language="C" -->
3763 * GVariant *
3764 * add_to_count (GVariant *orig,
3765 * GError **error)
3767 * GVariantDict dict;
3768 * guint32 count;
3770 * g_variant_dict_init (&dict, orig);
3771 * if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3773 * g_set_error (...);
3774 * g_variant_dict_clear (&dict);
3775 * return NULL;
3778 * g_variant_dict_insert (&dict, "count", "u", count + 1);
3780 * return g_variant_dict_end (&dict);
3782 * ]|
3784 * ## Using heap-allocated GVariantDict
3786 * |[<!-- language="C" -->
3787 * GVariant *
3788 * add_to_count (GVariant *orig,
3789 * GError **error)
3791 * GVariantDict *dict;
3792 * GVariant *result;
3793 * guint32 count;
3795 * dict = g_variant_dict_new (orig);
3797 * if (g_variant_dict_lookup (dict, "count", "u", &count))
3799 * g_variant_dict_insert (dict, "count", "u", count + 1);
3800 * result = g_variant_dict_end (dict);
3802 * else
3804 * g_set_error (...);
3805 * result = NULL;
3808 * g_variant_dict_unref (dict);
3810 * return result;
3812 * ]|
3814 * Since: 2.40
3816 struct stack_dict
3818 GHashTable *values;
3819 gsize magic;
3822 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3824 struct heap_dict
3826 struct stack_dict dict;
3827 gint ref_count;
3828 gsize magic;
3831 #define GVSD(d) ((struct stack_dict *) (d))
3832 #define GVHD(d) ((struct heap_dict *) (d))
3833 #define GVSD_MAGIC ((gsize) 2579507750u)
3834 #define GVSD_MAGIC_PARTIAL ((gsize) 3488698669u)
3835 #define GVHD_MAGIC ((gsize) 2450270775u)
3836 #define is_valid_dict(d) (d != NULL && \
3837 GVSD(d)->magic == GVSD_MAGIC)
3838 #define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
3840 /* Just to make sure that by adding a union to GVariantDict, we didn't
3841 * accidentally change ABI. */
3842 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3844 static gboolean
3845 ensure_valid_dict (GVariantDict *dict)
3847 if (is_valid_dict (dict))
3848 return TRUE;
3849 if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3851 static GVariantDict cleared_dict;
3853 /* Make sure that only first two fields were set and the rest is
3854 * zeroed to avoid messing up the builder that had parent
3855 * address equal to GVSB_MAGIC_PARTIAL. */
3856 if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3857 return FALSE;
3859 g_variant_dict_init (dict, dict->u.s.asv);
3861 return is_valid_dict (dict);
3865 * g_variant_dict_new:
3866 * @from_asv: (nullable): the #GVariant with which to initialise the
3867 * dictionary
3869 * Allocates and initialises a new #GVariantDict.
3871 * You should call g_variant_dict_unref() on the return value when it
3872 * is no longer needed. The memory will not be automatically freed by
3873 * any other call.
3875 * In some cases it may be easier to place a #GVariantDict directly on
3876 * the stack of the calling function and initialise it with
3877 * g_variant_dict_init(). This is particularly useful when you are
3878 * using #GVariantDict to construct a #GVariant.
3880 * Returns: (transfer full): a #GVariantDict
3882 * Since: 2.40
3884 GVariantDict *
3885 g_variant_dict_new (GVariant *from_asv)
3887 GVariantDict *dict;
3889 dict = g_slice_alloc (sizeof (struct heap_dict));
3890 g_variant_dict_init (dict, from_asv);
3891 GVHD(dict)->magic = GVHD_MAGIC;
3892 GVHD(dict)->ref_count = 1;
3894 return dict;
3898 * g_variant_dict_init: (skip)
3899 * @dict: a #GVariantDict
3900 * @from_asv: (nullable): the initial value for @dict
3902 * Initialises a #GVariantDict structure.
3904 * If @from_asv is given, it is used to initialise the dictionary.
3906 * This function completely ignores the previous contents of @dict. On
3907 * one hand this means that it is valid to pass in completely
3908 * uninitialised memory. On the other hand, this means that if you are
3909 * initialising over top of an existing #GVariantDict you need to first
3910 * call g_variant_dict_clear() in order to avoid leaking memory.
3912 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3913 * #GVariantDict that was initialised with this function. If you ever
3914 * pass a reference to a #GVariantDict outside of the control of your
3915 * own code then you should assume that the person receiving that
3916 * reference may try to use reference counting; you should use
3917 * g_variant_dict_new() instead of this function.
3919 * Since: 2.40
3921 void
3922 g_variant_dict_init (GVariantDict *dict,
3923 GVariant *from_asv)
3925 GVariantIter iter;
3926 gchar *key;
3927 GVariant *value;
3929 GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
3930 GVSD(dict)->magic = GVSD_MAGIC;
3932 if (from_asv)
3934 g_variant_iter_init (&iter, from_asv);
3935 while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3936 g_hash_table_insert (GVSD(dict)->values, key, value);
3941 * g_variant_dict_lookup:
3942 * @dict: a #GVariantDict
3943 * @key: the key to lookup in the dictionary
3944 * @format_string: a GVariant format string
3945 * @...: the arguments to unpack the value into
3947 * Looks up a value in a #GVariantDict.
3949 * This function is a wrapper around g_variant_dict_lookup_value() and
3950 * g_variant_get(). In the case that %NULL would have been returned,
3951 * this function returns %FALSE. Otherwise, it unpacks the returned
3952 * value and returns %TRUE.
3954 * @format_string determines the C types that are used for unpacking the
3955 * values and also determines if the values are copied or borrowed, see the
3956 * section on [GVariant format strings][gvariant-format-strings-pointers].
3958 * Returns: %TRUE if a value was unpacked
3960 * Since: 2.40
3962 gboolean
3963 g_variant_dict_lookup (GVariantDict *dict,
3964 const gchar *key,
3965 const gchar *format_string,
3966 ...)
3968 GVariant *value;
3969 va_list ap;
3971 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
3972 g_return_val_if_fail (key != NULL, FALSE);
3973 g_return_val_if_fail (format_string != NULL, FALSE);
3975 value = g_hash_table_lookup (GVSD(dict)->values, key);
3977 if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
3978 return FALSE;
3980 va_start (ap, format_string);
3981 g_variant_get_va (value, format_string, NULL, &ap);
3982 va_end (ap);
3984 return TRUE;
3988 * g_variant_dict_lookup_value:
3989 * @dict: a #GVariantDict
3990 * @key: the key to lookup in the dictionary
3991 * @expected_type: (nullable): a #GVariantType, or %NULL
3993 * Looks up a value in a #GVariantDict.
3995 * If @key is not found in @dictionary, %NULL is returned.
3997 * The @expected_type string specifies what type of value is expected.
3998 * If the value associated with @key has a different type then %NULL is
3999 * returned.
4001 * If the key is found and the value has the correct type, it is
4002 * returned. If @expected_type was specified then any non-%NULL return
4003 * value will have this type.
4005 * Returns: (transfer full): the value of the dictionary key, or %NULL
4007 * Since: 2.40
4009 GVariant *
4010 g_variant_dict_lookup_value (GVariantDict *dict,
4011 const gchar *key,
4012 const GVariantType *expected_type)
4014 GVariant *result;
4016 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4017 g_return_val_if_fail (key != NULL, NULL);
4019 result = g_hash_table_lookup (GVSD(dict)->values, key);
4021 if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4022 return g_variant_ref (result);
4024 return NULL;
4028 * g_variant_dict_contains:
4029 * @dict: a #GVariantDict
4030 * @key: the key to lookup in the dictionary
4032 * Checks if @key exists in @dict.
4034 * Returns: %TRUE if @key is in @dict
4036 * Since: 2.40
4038 gboolean
4039 g_variant_dict_contains (GVariantDict *dict,
4040 const gchar *key)
4042 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4043 g_return_val_if_fail (key != NULL, FALSE);
4045 return g_hash_table_contains (GVSD(dict)->values, key);
4049 * g_variant_dict_insert:
4050 * @dict: a #GVariantDict
4051 * @key: the key to insert a value for
4052 * @format_string: a #GVariant varargs format string
4053 * @...: arguments, as per @format_string
4055 * Inserts a value into a #GVariantDict.
4057 * This call is a convenience wrapper that is exactly equivalent to
4058 * calling g_variant_new() followed by g_variant_dict_insert_value().
4060 * Since: 2.40
4062 void
4063 g_variant_dict_insert (GVariantDict *dict,
4064 const gchar *key,
4065 const gchar *format_string,
4066 ...)
4068 va_list ap;
4070 g_return_if_fail (ensure_valid_dict (dict));
4071 g_return_if_fail (key != NULL);
4072 g_return_if_fail (format_string != NULL);
4074 va_start (ap, format_string);
4075 g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4076 va_end (ap);
4080 * g_variant_dict_insert_value:
4081 * @dict: a #GVariantDict
4082 * @key: the key to insert a value for
4083 * @value: the value to insert
4085 * Inserts (or replaces) a key in a #GVariantDict.
4087 * @value is consumed if it is floating.
4089 * Since: 2.40
4091 void
4092 g_variant_dict_insert_value (GVariantDict *dict,
4093 const gchar *key,
4094 GVariant *value)
4096 g_return_if_fail (ensure_valid_dict (dict));
4097 g_return_if_fail (key != NULL);
4098 g_return_if_fail (value != NULL);
4100 g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4104 * g_variant_dict_remove:
4105 * @dict: a #GVariantDict
4106 * @key: the key to remove
4108 * Removes a key and its associated value from a #GVariantDict.
4110 * Returns: %TRUE if the key was found and removed
4112 * Since: 2.40
4114 gboolean
4115 g_variant_dict_remove (GVariantDict *dict,
4116 const gchar *key)
4118 g_return_val_if_fail (ensure_valid_dict (dict), FALSE);
4119 g_return_val_if_fail (key != NULL, FALSE);
4121 return g_hash_table_remove (GVSD(dict)->values, key);
4125 * g_variant_dict_clear:
4126 * @dict: a #GVariantDict
4128 * Releases all memory associated with a #GVariantDict without freeing
4129 * the #GVariantDict structure itself.
4131 * It typically only makes sense to do this on a stack-allocated
4132 * #GVariantDict if you want to abort building the value part-way
4133 * through. This function need not be called if you call
4134 * g_variant_dict_end() and it also doesn't need to be called on dicts
4135 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4136 * that).
4138 * It is valid to call this function on either an initialised
4139 * #GVariantDict or one that was previously cleared by an earlier call
4140 * to g_variant_dict_clear() but it is not valid to call this function
4141 * on uninitialised memory.
4143 * Since: 2.40
4145 void
4146 g_variant_dict_clear (GVariantDict *dict)
4148 if (GVSD(dict)->magic == 0)
4149 /* all-zeros case */
4150 return;
4152 g_return_if_fail (ensure_valid_dict (dict));
4154 g_hash_table_unref (GVSD(dict)->values);
4155 GVSD(dict)->values = NULL;
4157 GVSD(dict)->magic = 0;
4161 * g_variant_dict_end:
4162 * @dict: a #GVariantDict
4164 * Returns the current value of @dict as a #GVariant of type
4165 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4167 * It is not permissible to use @dict in any way after this call except
4168 * for reference counting operations (in the case of a heap-allocated
4169 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4170 * the case of stack-allocated).
4172 * Returns: (transfer none): a new, floating, #GVariant
4174 * Since: 2.40
4176 GVariant *
4177 g_variant_dict_end (GVariantDict *dict)
4179 GVariantBuilder builder;
4180 GHashTableIter iter;
4181 gpointer key, value;
4183 g_return_val_if_fail (ensure_valid_dict (dict), NULL);
4185 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4187 g_hash_table_iter_init (&iter, GVSD(dict)->values);
4188 while (g_hash_table_iter_next (&iter, &key, &value))
4189 g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4191 g_variant_dict_clear (dict);
4193 return g_variant_builder_end (&builder);
4197 * g_variant_dict_ref:
4198 * @dict: a heap-allocated #GVariantDict
4200 * Increases the reference count on @dict.
4202 * Don't call this on stack-allocated #GVariantDict instances or bad
4203 * things will happen.
4205 * Returns: (transfer full): a new reference to @dict
4207 * Since: 2.40
4209 GVariantDict *
4210 g_variant_dict_ref (GVariantDict *dict)
4212 g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4214 GVHD(dict)->ref_count++;
4216 return dict;
4220 * g_variant_dict_unref:
4221 * @dict: (transfer full): a heap-allocated #GVariantDict
4223 * Decreases the reference count on @dict.
4225 * In the event that there are no more references, releases all memory
4226 * associated with the #GVariantDict.
4228 * Don't call this on stack-allocated #GVariantDict instances or bad
4229 * things will happen.
4231 * Since: 2.40
4233 void
4234 g_variant_dict_unref (GVariantDict *dict)
4236 g_return_if_fail (is_valid_heap_dict (dict));
4238 if (--GVHD(dict)->ref_count == 0)
4240 g_variant_dict_clear (dict);
4241 g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4246 /* Format strings {{{1 */
4247 /*< private >
4248 * g_variant_format_string_scan:
4249 * @string: a string that may be prefixed with a format string
4250 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4251 * or %NULL
4252 * @endptr: (nullable) (default NULL): location to store the end pointer,
4253 * or %NULL
4255 * Checks the string pointed to by @string for starting with a properly
4256 * formed #GVariant varargs format string. If no valid format string is
4257 * found then %FALSE is returned.
4259 * If @string does start with a valid format string then %TRUE is
4260 * returned. If @endptr is non-%NULL then it is updated to point to the
4261 * first character after the format string.
4263 * If @limit is non-%NULL then @limit (and any charater after it) will
4264 * not be accessed and the effect is otherwise equivalent to if the
4265 * character at @limit were nul.
4267 * See the section on [GVariant format strings][gvariant-format-strings].
4269 * Returns: %TRUE if there was a valid format string
4271 * Since: 2.24
4273 gboolean
4274 g_variant_format_string_scan (const gchar *string,
4275 const gchar *limit,
4276 const gchar **endptr)
4278 #define next_char() (string == limit ? '\0' : *string++)
4279 #define peek_char() (string == limit ? '\0' : *string)
4280 char c;
4282 switch (next_char())
4284 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4285 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4286 case 'g': case 'v': case '*': case '?': case 'r':
4287 break;
4289 case 'm':
4290 return g_variant_format_string_scan (string, limit, endptr);
4292 case 'a':
4293 case '@':
4294 return g_variant_type_string_scan (string, limit, endptr);
4296 case '(':
4297 while (peek_char() != ')')
4298 if (!g_variant_format_string_scan (string, limit, &string))
4299 return FALSE;
4301 next_char(); /* consume ')' */
4302 break;
4304 case '{':
4305 c = next_char();
4307 if (c == '&')
4309 c = next_char ();
4311 if (c != 's' && c != 'o' && c != 'g')
4312 return FALSE;
4314 else
4316 if (c == '@')
4317 c = next_char ();
4319 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4320 * The terminating null character is considered to be
4321 * part of the string.
4323 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4324 return FALSE;
4327 if (!g_variant_format_string_scan (string, limit, &string))
4328 return FALSE;
4330 if (next_char() != '}')
4331 return FALSE;
4333 break;
4335 case '^':
4336 if ((c = next_char()) == 'a')
4338 if ((c = next_char()) == '&')
4340 if ((c = next_char()) == 'a')
4342 if ((c = next_char()) == 'y')
4343 break; /* '^a&ay' */
4346 else if (c == 's' || c == 'o')
4347 break; /* '^a&s', '^a&o' */
4350 else if (c == 'a')
4352 if ((c = next_char()) == 'y')
4353 break; /* '^aay' */
4356 else if (c == 's' || c == 'o')
4357 break; /* '^as', '^ao' */
4359 else if (c == 'y')
4360 break; /* '^ay' */
4362 else if (c == '&')
4364 if ((c = next_char()) == 'a')
4366 if ((c = next_char()) == 'y')
4367 break; /* '^&ay' */
4371 return FALSE;
4373 case '&':
4374 c = next_char();
4376 if (c != 's' && c != 'o' && c != 'g')
4377 return FALSE;
4379 break;
4381 default:
4382 return FALSE;
4385 if (endptr != NULL)
4386 *endptr = string;
4388 #undef next_char
4389 #undef peek_char
4391 return TRUE;
4395 * g_variant_check_format_string:
4396 * @value: a #GVariant
4397 * @format_string: a valid #GVariant format string
4398 * @copy_only: %TRUE to ensure the format string makes deep copies
4400 * Checks if calling g_variant_get() with @format_string on @value would
4401 * be valid from a type-compatibility standpoint. @format_string is
4402 * assumed to be a valid format string (from a syntactic standpoint).
4404 * If @copy_only is %TRUE then this function additionally checks that it
4405 * would be safe to call g_variant_unref() on @value immediately after
4406 * the call to g_variant_get() without invalidating the result. This is
4407 * only possible if deep copies are made (ie: there are no pointers to
4408 * the data inside of the soon-to-be-freed #GVariant instance). If this
4409 * check fails then a g_critical() is printed and %FALSE is returned.
4411 * This function is meant to be used by functions that wish to provide
4412 * varargs accessors to #GVariant values of uncertain values (eg:
4413 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4415 * Returns: %TRUE if @format_string is safe to use
4417 * Since: 2.34
4419 gboolean
4420 g_variant_check_format_string (GVariant *value,
4421 const gchar *format_string,
4422 gboolean copy_only)
4424 const gchar *original_format = format_string;
4425 const gchar *type_string;
4427 /* Interesting factoid: assuming a format string is valid, it can be
4428 * converted to a type string by removing all '@' '&' and '^'
4429 * characters.
4431 * Instead of doing that, we can just skip those characters when
4432 * comparing it to the type string of @value.
4434 * For the copy-only case we can just drop the '&' from the list of
4435 * characters to skip over. A '&' will never appear in a type string
4436 * so we know that it won't be possible to return %TRUE if it is in a
4437 * format string.
4439 type_string = g_variant_get_type_string (value);
4441 while (*type_string || *format_string)
4443 gchar format = *format_string++;
4445 switch (format)
4447 case '&':
4448 if G_UNLIKELY (copy_only)
4450 /* for the love of all that is good, please don't mark this string for translation... */
4451 g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4452 "interface to validate the passed format string for type safety. The passed format "
4453 "(%s) contains a '&' character which would result in a pointer being returned to the "
4454 "data inside of a GVariant instance that may no longer exist by the time the function "
4455 "returns. Modify your code to use a format string without '&'.", original_format);
4456 return FALSE;
4459 /* fall through */
4460 case '^':
4461 case '@':
4462 /* ignore these 2 (or 3) */
4463 continue;
4465 case '?':
4466 /* attempt to consume one of 'bynqiuxthdsog' */
4468 char s = *type_string++;
4470 if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4471 return FALSE;
4473 continue;
4475 case 'r':
4476 /* ensure it's a tuple */
4477 if (*type_string != '(')
4478 return FALSE;
4480 /* fall through */
4481 case '*':
4482 /* consume a full type string for the '*' or 'r' */
4483 if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4484 return FALSE;
4486 continue;
4488 default:
4489 /* attempt to consume exactly one character equal to the format */
4490 if (format != *type_string++)
4491 return FALSE;
4495 return TRUE;
4498 /*< private >
4499 * g_variant_format_string_scan_type:
4500 * @string: a string that may be prefixed with a format string
4501 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4502 * or %NULL
4503 * @endptr: (nullable) (default NULL): location to store the end pointer,
4504 * or %NULL
4506 * If @string starts with a valid format string then this function will
4507 * return the type that the format string corresponds to. Otherwise
4508 * this function returns %NULL.
4510 * Use g_variant_type_free() to free the return value when you no longer
4511 * need it.
4513 * This function is otherwise exactly like
4514 * g_variant_format_string_scan().
4516 * Returns: (nullable): a #GVariantType if there was a valid format string
4518 * Since: 2.24
4520 GVariantType *
4521 g_variant_format_string_scan_type (const gchar *string,
4522 const gchar *limit,
4523 const gchar **endptr)
4525 const gchar *my_end;
4526 gchar *dest;
4527 gchar *new;
4529 if (endptr == NULL)
4530 endptr = &my_end;
4532 if (!g_variant_format_string_scan (string, limit, endptr))
4533 return NULL;
4535 dest = new = g_malloc (*endptr - string + 1);
4536 while (string != *endptr)
4538 if (*string != '@' && *string != '&' && *string != '^')
4539 *dest++ = *string;
4540 string++;
4542 *dest = '\0';
4544 return (GVariantType *) G_VARIANT_TYPE (new);
4547 static gboolean
4548 valid_format_string (const gchar *format_string,
4549 gboolean single,
4550 GVariant *value)
4552 const gchar *endptr;
4553 GVariantType *type;
4555 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4557 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4559 if (single)
4560 g_critical ("'%s' is not a valid GVariant format string",
4561 format_string);
4562 else
4563 g_critical ("'%s' does not have a valid GVariant format "
4564 "string as a prefix", format_string);
4566 if (type != NULL)
4567 g_variant_type_free (type);
4569 return FALSE;
4572 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4574 gchar *fragment;
4575 gchar *typestr;
4577 fragment = g_strndup (format_string, endptr - format_string);
4578 typestr = g_variant_type_dup_string (type);
4580 g_critical ("the GVariant format string '%s' has a type of "
4581 "'%s' but the given value has a type of '%s'",
4582 fragment, typestr, g_variant_get_type_string (value));
4584 g_variant_type_free (type);
4585 g_free (fragment);
4586 g_free (typestr);
4588 return FALSE;
4591 g_variant_type_free (type);
4593 return TRUE;
4596 /* Variable Arguments {{{1 */
4597 /* We consider 2 main classes of format strings:
4599 * - recursive format strings
4600 * these are ones that result in recursion and the collection of
4601 * possibly more than one argument. Maybe types, tuples,
4602 * dictionary entries.
4604 * - leaf format string
4605 * these result in the collection of a single argument.
4607 * Leaf format strings are further subdivided into two categories:
4609 * - single non-null pointer ("nnp")
4610 * these either collect or return a single non-null pointer.
4612 * - other
4613 * these collect or return something else (bool, number, etc).
4615 * Based on the above, the varargs handling code is split into 4 main parts:
4617 * - nnp handling code
4618 * - leaf handling code (which may invoke nnp code)
4619 * - generic handling code (may be recursive, may invoke leaf code)
4620 * - user-facing API (which invokes the generic code)
4622 * Each section implements some of the following functions:
4624 * - skip:
4625 * collect the arguments for the format string as if
4626 * g_variant_new() had been called, but do nothing with them. used
4627 * for skipping over arguments when constructing a Nothing maybe
4628 * type.
4630 * - new:
4631 * create a GVariant *
4633 * - get:
4634 * unpack a GVariant *
4636 * - free (nnp only):
4637 * free a previously allocated item
4640 static gboolean
4641 g_variant_format_string_is_leaf (const gchar *str)
4643 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4646 static gboolean
4647 g_variant_format_string_is_nnp (const gchar *str)
4649 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4650 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4651 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4654 /* Single non-null pointer ("nnp") {{{2 */
4655 static void
4656 g_variant_valist_free_nnp (const gchar *str,
4657 gpointer ptr)
4659 switch (*str)
4661 case 'a':
4662 g_variant_iter_free (ptr);
4663 break;
4665 case '^':
4666 if (str[2] != '&') /* '^as', '^ao' */
4667 g_strfreev (ptr);
4668 else /* '^a&s', '^a&o' */
4669 g_free (ptr);
4670 break;
4672 case 's':
4673 case 'o':
4674 case 'g':
4675 g_free (ptr);
4676 break;
4678 case '@':
4679 case '*':
4680 case '?':
4681 case 'v':
4682 g_variant_unref (ptr);
4683 break;
4685 case '&':
4686 break;
4688 default:
4689 g_assert_not_reached ();
4693 static gchar
4694 g_variant_scan_convenience (const gchar **str,
4695 gboolean *constant,
4696 guint *arrays)
4698 *constant = FALSE;
4699 *arrays = 0;
4701 for (;;)
4703 char c = *(*str)++;
4705 if (c == '&')
4706 *constant = TRUE;
4708 else if (c == 'a')
4709 (*arrays)++;
4711 else
4712 return c;
4716 static GVariant *
4717 g_variant_valist_new_nnp (const gchar **str,
4718 gpointer ptr)
4720 if (**str == '&')
4721 (*str)++;
4723 switch (*(*str)++)
4725 case 'a':
4726 if (ptr != NULL)
4728 const GVariantType *type;
4729 GVariant *value;
4731 value = g_variant_builder_end (ptr);
4732 type = g_variant_get_type (value);
4734 if G_UNLIKELY (!g_variant_type_is_array (type))
4735 g_error ("g_variant_new: expected array GVariantBuilder but "
4736 "the built value has type '%s'",
4737 g_variant_get_type_string (value));
4739 type = g_variant_type_element (type);
4741 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4742 g_error ("g_variant_new: expected GVariantBuilder array element "
4743 "type '%s' but the built value has element type '%s'",
4744 g_variant_type_dup_string ((GVariantType *) *str),
4745 g_variant_get_type_string (value) + 1);
4747 g_variant_type_string_scan (*str, NULL, str);
4749 return value;
4751 else
4753 /* special case: NULL pointer for empty array */
4755 const GVariantType *type = (GVariantType *) *str;
4757 g_variant_type_string_scan (*str, NULL, str);
4759 if G_UNLIKELY (!g_variant_type_is_definite (type))
4760 g_error ("g_variant_new: NULL pointer given with indefinite "
4761 "array type; unable to determine which type of empty "
4762 "array to construct.");
4764 return g_variant_new_array (type, NULL, 0);
4767 case 's':
4769 GVariant *value;
4771 value = g_variant_new_string (ptr);
4773 if (value == NULL)
4774 value = g_variant_new_string ("[Invalid UTF-8]");
4776 return value;
4779 case 'o':
4780 return g_variant_new_object_path (ptr);
4782 case 'g':
4783 return g_variant_new_signature (ptr);
4785 case '^':
4787 gboolean constant;
4788 guint arrays;
4789 gchar type;
4791 type = g_variant_scan_convenience (str, &constant, &arrays);
4793 if (type == 's')
4794 return g_variant_new_strv (ptr, -1);
4796 if (type == 'o')
4797 return g_variant_new_objv (ptr, -1);
4799 if (arrays > 1)
4800 return g_variant_new_bytestring_array (ptr, -1);
4802 return g_variant_new_bytestring (ptr);
4805 case '@':
4806 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4807 g_error ("g_variant_new: expected GVariant of type '%s' but "
4808 "received value has type '%s'",
4809 g_variant_type_dup_string ((GVariantType *) *str),
4810 g_variant_get_type_string (ptr));
4812 g_variant_type_string_scan (*str, NULL, str);
4814 return ptr;
4816 case '*':
4817 return ptr;
4819 case '?':
4820 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4821 g_error ("g_variant_new: format string '?' expects basic-typed "
4822 "GVariant, but received value has type '%s'",
4823 g_variant_get_type_string (ptr));
4825 return ptr;
4827 case 'r':
4828 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4829 g_error ("g_variant_new: format string 'r' expects tuple-typed "
4830 "GVariant, but received value has type '%s'",
4831 g_variant_get_type_string (ptr));
4833 return ptr;
4835 case 'v':
4836 return g_variant_new_variant (ptr);
4838 default:
4839 g_assert_not_reached ();
4843 static gpointer
4844 g_variant_valist_get_nnp (const gchar **str,
4845 GVariant *value)
4847 switch (*(*str)++)
4849 case 'a':
4850 g_variant_type_string_scan (*str, NULL, str);
4851 return g_variant_iter_new (value);
4853 case '&':
4854 (*str)++;
4855 return (gchar *) g_variant_get_string (value, NULL);
4857 case 's':
4858 case 'o':
4859 case 'g':
4860 return g_variant_dup_string (value, NULL);
4862 case '^':
4864 gboolean constant;
4865 guint arrays;
4866 gchar type;
4868 type = g_variant_scan_convenience (str, &constant, &arrays);
4870 if (type == 's')
4872 if (constant)
4873 return g_variant_get_strv (value, NULL);
4874 else
4875 return g_variant_dup_strv (value, NULL);
4878 else if (type == 'o')
4880 if (constant)
4881 return g_variant_get_objv (value, NULL);
4882 else
4883 return g_variant_dup_objv (value, NULL);
4886 else if (arrays > 1)
4888 if (constant)
4889 return g_variant_get_bytestring_array (value, NULL);
4890 else
4891 return g_variant_dup_bytestring_array (value, NULL);
4894 else
4896 if (constant)
4897 return (gchar *) g_variant_get_bytestring (value);
4898 else
4899 return g_variant_dup_bytestring (value, NULL);
4903 case '@':
4904 g_variant_type_string_scan (*str, NULL, str);
4905 /* fall through */
4907 case '*':
4908 case '?':
4909 case 'r':
4910 return g_variant_ref (value);
4912 case 'v':
4913 return g_variant_get_variant (value);
4915 default:
4916 g_assert_not_reached ();
4920 /* Leaves {{{2 */
4921 static void
4922 g_variant_valist_skip_leaf (const gchar **str,
4923 va_list *app)
4925 if (g_variant_format_string_is_nnp (*str))
4927 g_variant_format_string_scan (*str, NULL, str);
4928 va_arg (*app, gpointer);
4929 return;
4932 switch (*(*str)++)
4934 case 'b':
4935 case 'y':
4936 case 'n':
4937 case 'q':
4938 case 'i':
4939 case 'u':
4940 case 'h':
4941 va_arg (*app, int);
4942 return;
4944 case 'x':
4945 case 't':
4946 va_arg (*app, guint64);
4947 return;
4949 case 'd':
4950 va_arg (*app, gdouble);
4951 return;
4953 default:
4954 g_assert_not_reached ();
4958 static GVariant *
4959 g_variant_valist_new_leaf (const gchar **str,
4960 va_list *app)
4962 if (g_variant_format_string_is_nnp (*str))
4963 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
4965 switch (*(*str)++)
4967 case 'b':
4968 return g_variant_new_boolean (va_arg (*app, gboolean));
4970 case 'y':
4971 return g_variant_new_byte (va_arg (*app, guint));
4973 case 'n':
4974 return g_variant_new_int16 (va_arg (*app, gint));
4976 case 'q':
4977 return g_variant_new_uint16 (va_arg (*app, guint));
4979 case 'i':
4980 return g_variant_new_int32 (va_arg (*app, gint));
4982 case 'u':
4983 return g_variant_new_uint32 (va_arg (*app, guint));
4985 case 'x':
4986 return g_variant_new_int64 (va_arg (*app, gint64));
4988 case 't':
4989 return g_variant_new_uint64 (va_arg (*app, guint64));
4991 case 'h':
4992 return g_variant_new_handle (va_arg (*app, gint));
4994 case 'd':
4995 return g_variant_new_double (va_arg (*app, gdouble));
4997 default:
4998 g_assert_not_reached ();
5002 /* The code below assumes this */
5003 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5004 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5006 static void
5007 g_variant_valist_get_leaf (const gchar **str,
5008 GVariant *value,
5009 gboolean free,
5010 va_list *app)
5012 gpointer ptr = va_arg (*app, gpointer);
5014 if (ptr == NULL)
5016 g_variant_format_string_scan (*str, NULL, str);
5017 return;
5020 if (g_variant_format_string_is_nnp (*str))
5022 gpointer *nnp = (gpointer *) ptr;
5024 if (free && *nnp != NULL)
5025 g_variant_valist_free_nnp (*str, *nnp);
5027 *nnp = NULL;
5029 if (value != NULL)
5030 *nnp = g_variant_valist_get_nnp (str, value);
5031 else
5032 g_variant_format_string_scan (*str, NULL, str);
5034 return;
5037 if (value != NULL)
5039 switch (*(*str)++)
5041 case 'b':
5042 *(gboolean *) ptr = g_variant_get_boolean (value);
5043 return;
5045 case 'y':
5046 *(guchar *) ptr = g_variant_get_byte (value);
5047 return;
5049 case 'n':
5050 *(gint16 *) ptr = g_variant_get_int16 (value);
5051 return;
5053 case 'q':
5054 *(guint16 *) ptr = g_variant_get_uint16 (value);
5055 return;
5057 case 'i':
5058 *(gint32 *) ptr = g_variant_get_int32 (value);
5059 return;
5061 case 'u':
5062 *(guint32 *) ptr = g_variant_get_uint32 (value);
5063 return;
5065 case 'x':
5066 *(gint64 *) ptr = g_variant_get_int64 (value);
5067 return;
5069 case 't':
5070 *(guint64 *) ptr = g_variant_get_uint64 (value);
5071 return;
5073 case 'h':
5074 *(gint32 *) ptr = g_variant_get_handle (value);
5075 return;
5077 case 'd':
5078 *(gdouble *) ptr = g_variant_get_double (value);
5079 return;
5082 else
5084 switch (*(*str)++)
5086 case 'y':
5087 *(guchar *) ptr = 0;
5088 return;
5090 case 'n':
5091 case 'q':
5092 *(guint16 *) ptr = 0;
5093 return;
5095 case 'i':
5096 case 'u':
5097 case 'h':
5098 case 'b':
5099 *(guint32 *) ptr = 0;
5100 return;
5102 case 'x':
5103 case 't':
5104 case 'd':
5105 *(guint64 *) ptr = 0;
5106 return;
5110 g_assert_not_reached ();
5113 /* Generic (recursive) {{{2 */
5114 static void
5115 g_variant_valist_skip (const gchar **str,
5116 va_list *app)
5118 if (g_variant_format_string_is_leaf (*str))
5119 g_variant_valist_skip_leaf (str, app);
5121 else if (**str == 'm') /* maybe */
5123 (*str)++;
5125 if (!g_variant_format_string_is_nnp (*str))
5126 va_arg (*app, gboolean);
5128 g_variant_valist_skip (str, app);
5130 else /* tuple, dictionary entry */
5132 g_assert (**str == '(' || **str == '{');
5133 (*str)++;
5134 while (**str != ')' && **str != '}')
5135 g_variant_valist_skip (str, app);
5136 (*str)++;
5140 static GVariant *
5141 g_variant_valist_new (const gchar **str,
5142 va_list *app)
5144 if (g_variant_format_string_is_leaf (*str))
5145 return g_variant_valist_new_leaf (str, app);
5147 if (**str == 'm') /* maybe */
5149 GVariantType *type = NULL;
5150 GVariant *value = NULL;
5152 (*str)++;
5154 if (g_variant_format_string_is_nnp (*str))
5156 gpointer nnp = va_arg (*app, gpointer);
5158 if (nnp != NULL)
5159 value = g_variant_valist_new_nnp (str, nnp);
5160 else
5161 type = g_variant_format_string_scan_type (*str, NULL, str);
5163 else
5165 gboolean just = va_arg (*app, gboolean);
5167 if (just)
5168 value = g_variant_valist_new (str, app);
5169 else
5171 type = g_variant_format_string_scan_type (*str, NULL, NULL);
5172 g_variant_valist_skip (str, app);
5176 value = g_variant_new_maybe (type, value);
5178 if (type != NULL)
5179 g_variant_type_free (type);
5181 return value;
5183 else /* tuple, dictionary entry */
5185 GVariantBuilder b;
5187 if (**str == '(')
5188 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5189 else
5191 g_assert (**str == '{');
5192 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5195 (*str)++; /* '(' */
5196 while (**str != ')' && **str != '}')
5197 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5198 (*str)++; /* ')' */
5200 return g_variant_builder_end (&b);
5204 static void
5205 g_variant_valist_get (const gchar **str,
5206 GVariant *value,
5207 gboolean free,
5208 va_list *app)
5210 if (g_variant_format_string_is_leaf (*str))
5211 g_variant_valist_get_leaf (str, value, free, app);
5213 else if (**str == 'm')
5215 (*str)++;
5217 if (value != NULL)
5218 value = g_variant_get_maybe (value);
5220 if (!g_variant_format_string_is_nnp (*str))
5222 gboolean *ptr = va_arg (*app, gboolean *);
5224 if (ptr != NULL)
5225 *ptr = value != NULL;
5228 g_variant_valist_get (str, value, free, app);
5230 if (value != NULL)
5231 g_variant_unref (value);
5234 else /* tuple, dictionary entry */
5236 gint index = 0;
5238 g_assert (**str == '(' || **str == '{');
5240 (*str)++;
5241 while (**str != ')' && **str != '}')
5243 if (value != NULL)
5245 GVariant *child = g_variant_get_child_value (value, index++);
5246 g_variant_valist_get (str, child, free, app);
5247 g_variant_unref (child);
5249 else
5250 g_variant_valist_get (str, NULL, free, app);
5252 (*str)++;
5256 /* User-facing API {{{2 */
5258 * g_variant_new: (skip)
5259 * @format_string: a #GVariant format string
5260 * @...: arguments, as per @format_string
5262 * Creates a new #GVariant instance.
5264 * Think of this function as an analogue to g_strdup_printf().
5266 * The type of the created instance and the arguments that are expected
5267 * by this function are determined by @format_string. See the section on
5268 * [GVariant format strings][gvariant-format-strings]. Please note that
5269 * the syntax of the format string is very likely to be extended in the
5270 * future.
5272 * The first character of the format string must not be '*' '?' '@' or
5273 * 'r'; in essence, a new #GVariant must always be constructed by this
5274 * function (and not merely passed through it unmodified).
5276 * Note that the arguments must be of the correct width for their types
5277 * specified in @format_string. This can be achieved by casting them. See
5278 * the [GVariant varargs documentation][gvariant-varargs].
5280 * |[<!-- language="C" -->
5281 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5282 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5283 * GVariant *new_variant;
5285 * new_variant = g_variant_new ("(t^as)",
5286 * /<!-- -->* This cast is required. *<!-- -->/
5287 * (guint64) some_flags,
5288 * some_strings);
5289 * ]|
5291 * Returns: a new floating #GVariant instance
5293 * Since: 2.24
5295 GVariant *
5296 g_variant_new (const gchar *format_string,
5297 ...)
5299 GVariant *value;
5300 va_list ap;
5302 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5303 format_string[0] != '?' && format_string[0] != '@' &&
5304 format_string[0] != '*' && format_string[0] != 'r',
5305 NULL);
5307 va_start (ap, format_string);
5308 value = g_variant_new_va (format_string, NULL, &ap);
5309 va_end (ap);
5311 return value;
5315 * g_variant_new_va: (skip)
5316 * @format_string: a string that is prefixed with a format string
5317 * @endptr: (nullable) (default NULL): location to store the end pointer,
5318 * or %NULL
5319 * @app: a pointer to a #va_list
5321 * This function is intended to be used by libraries based on
5322 * #GVariant that want to provide g_variant_new()-like functionality
5323 * to their users.
5325 * The API is more general than g_variant_new() to allow a wider range
5326 * of possible uses.
5328 * @format_string must still point to a valid format string, but it only
5329 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
5330 * non-%NULL then it is updated to point to the first character past the
5331 * end of the format string.
5333 * @app is a pointer to a #va_list. The arguments, according to
5334 * @format_string, are collected from this #va_list and the list is left
5335 * pointing to the argument following the last.
5337 * Note that the arguments in @app must be of the correct width for their
5338 * types specified in @format_string when collected into the #va_list.
5339 * See the [GVariant varargs documentation][gvariant-varargs.
5341 * These two generalisations allow mixing of multiple calls to
5342 * g_variant_new_va() and g_variant_get_va() within a single actual
5343 * varargs call by the user.
5345 * The return value will be floating if it was a newly created GVariant
5346 * instance (for example, if the format string was "(ii)"). In the case
5347 * that the format_string was '*', '?', 'r', or a format starting with
5348 * '@' then the collected #GVariant pointer will be returned unmodified,
5349 * without adding any additional references.
5351 * In order to behave correctly in all cases it is necessary for the
5352 * calling function to g_variant_ref_sink() the return result before
5353 * returning control to the user that originally provided the pointer.
5354 * At this point, the caller will have their own full reference to the
5355 * result. This can also be done by adding the result to a container,
5356 * or by passing it to another g_variant_new() call.
5358 * Returns: a new, usually floating, #GVariant
5360 * Since: 2.24
5362 GVariant *
5363 g_variant_new_va (const gchar *format_string,
5364 const gchar **endptr,
5365 va_list *app)
5367 GVariant *value;
5369 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5370 NULL);
5371 g_return_val_if_fail (app != NULL, NULL);
5373 value = g_variant_valist_new (&format_string, app);
5375 if (endptr != NULL)
5376 *endptr = format_string;
5378 return value;
5382 * g_variant_get: (skip)
5383 * @value: a #GVariant instance
5384 * @format_string: a #GVariant format string
5385 * @...: arguments, as per @format_string
5387 * Deconstructs a #GVariant instance.
5389 * Think of this function as an analogue to scanf().
5391 * The arguments that are expected by this function are entirely
5392 * determined by @format_string. @format_string also restricts the
5393 * permissible types of @value. It is an error to give a value with
5394 * an incompatible type. See the section on
5395 * [GVariant format strings][gvariant-format-strings].
5396 * Please note that the syntax of the format string is very likely to be
5397 * extended in the future.
5399 * @format_string determines the C types that are used for unpacking
5400 * the values and also determines if the values are copied or borrowed,
5401 * see the section on
5402 * [GVariant format strings][gvariant-format-strings-pointers].
5404 * Since: 2.24
5406 void
5407 g_variant_get (GVariant *value,
5408 const gchar *format_string,
5409 ...)
5411 va_list ap;
5413 g_return_if_fail (valid_format_string (format_string, TRUE, value));
5415 /* if any direct-pointer-access formats are in use, flatten first */
5416 if (strchr (format_string, '&'))
5417 g_variant_get_data (value);
5419 va_start (ap, format_string);
5420 g_variant_get_va (value, format_string, NULL, &ap);
5421 va_end (ap);
5425 * g_variant_get_va: (skip)
5426 * @value: a #GVariant
5427 * @format_string: a string that is prefixed with a format string
5428 * @endptr: (nullable) (default NULL): location to store the end pointer,
5429 * or %NULL
5430 * @app: a pointer to a #va_list
5432 * This function is intended to be used by libraries based on #GVariant
5433 * that want to provide g_variant_get()-like functionality to their
5434 * users.
5436 * The API is more general than g_variant_get() to allow a wider range
5437 * of possible uses.
5439 * @format_string must still point to a valid format string, but it only
5440 * need to be nul-terminated if @endptr is %NULL. If @endptr is
5441 * non-%NULL then it is updated to point to the first character past the
5442 * end of the format string.
5444 * @app is a pointer to a #va_list. The arguments, according to
5445 * @format_string, are collected from this #va_list and the list is left
5446 * pointing to the argument following the last.
5448 * These two generalisations allow mixing of multiple calls to
5449 * g_variant_new_va() and g_variant_get_va() within a single actual
5450 * varargs call by the user.
5452 * @format_string determines the C types that are used for unpacking
5453 * the values and also determines if the values are copied or borrowed,
5454 * see the section on
5455 * [GVariant format strings][gvariant-format-strings-pointers].
5457 * Since: 2.24
5459 void
5460 g_variant_get_va (GVariant *value,
5461 const gchar *format_string,
5462 const gchar **endptr,
5463 va_list *app)
5465 g_return_if_fail (valid_format_string (format_string, !endptr, value));
5466 g_return_if_fail (value != NULL);
5467 g_return_if_fail (app != NULL);
5469 /* if any direct-pointer-access formats are in use, flatten first */
5470 if (strchr (format_string, '&'))
5471 g_variant_get_data (value);
5473 g_variant_valist_get (&format_string, value, FALSE, app);
5475 if (endptr != NULL)
5476 *endptr = format_string;
5479 /* Varargs-enabled Utility Functions {{{1 */
5482 * g_variant_builder_add: (skip)
5483 * @builder: a #GVariantBuilder
5484 * @format_string: a #GVariant varargs format string
5485 * @...: arguments, as per @format_string
5487 * Adds to a #GVariantBuilder.
5489 * This call is a convenience wrapper that is exactly equivalent to
5490 * calling g_variant_new() followed by g_variant_builder_add_value().
5492 * Note that the arguments must be of the correct width for their types
5493 * specified in @format_string. This can be achieved by casting them. See
5494 * the [GVariant varargs documentation][gvariant-varargs].
5496 * This function might be used as follows:
5498 * |[<!-- language="C" -->
5499 * GVariant *
5500 * make_pointless_dictionary (void)
5502 * GVariantBuilder builder;
5503 * int i;
5505 * g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5506 * for (i = 0; i < 16; i++)
5508 * gchar buf[3];
5510 * sprintf (buf, "%d", i);
5511 * g_variant_builder_add (&builder, "{is}", i, buf);
5514 * return g_variant_builder_end (&builder);
5516 * ]|
5518 * Since: 2.24
5520 void
5521 g_variant_builder_add (GVariantBuilder *builder,
5522 const gchar *format_string,
5523 ...)
5525 GVariant *variant;
5526 va_list ap;
5528 va_start (ap, format_string);
5529 variant = g_variant_new_va (format_string, NULL, &ap);
5530 va_end (ap);
5532 g_variant_builder_add_value (builder, variant);
5536 * g_variant_get_child: (skip)
5537 * @value: a container #GVariant
5538 * @index_: the index of the child to deconstruct
5539 * @format_string: a #GVariant format string
5540 * @...: arguments, as per @format_string
5542 * Reads a child item out of a container #GVariant instance and
5543 * deconstructs it according to @format_string. This call is
5544 * essentially a combination of g_variant_get_child_value() and
5545 * g_variant_get().
5547 * @format_string determines the C types that are used for unpacking
5548 * the values and also determines if the values are copied or borrowed,
5549 * see the section on
5550 * [GVariant format strings][gvariant-format-strings-pointers].
5552 * Since: 2.24
5554 void
5555 g_variant_get_child (GVariant *value,
5556 gsize index_,
5557 const gchar *format_string,
5558 ...)
5560 GVariant *child;
5561 va_list ap;
5563 /* if any direct-pointer-access formats are in use, flatten first */
5564 if (strchr (format_string, '&'))
5565 g_variant_get_data (value);
5567 child = g_variant_get_child_value (value, index_);
5568 g_return_if_fail (valid_format_string (format_string, TRUE, child));
5570 va_start (ap, format_string);
5571 g_variant_get_va (child, format_string, NULL, &ap);
5572 va_end (ap);
5574 g_variant_unref (child);
5578 * g_variant_iter_next: (skip)
5579 * @iter: a #GVariantIter
5580 * @format_string: a GVariant format string
5581 * @...: the arguments to unpack the value into
5583 * Gets the next item in the container and unpacks it into the variable
5584 * argument list according to @format_string, returning %TRUE.
5586 * If no more items remain then %FALSE is returned.
5588 * All of the pointers given on the variable arguments list of this
5589 * function are assumed to point at uninitialised memory. It is the
5590 * responsibility of the caller to free all of the values returned by
5591 * the unpacking process.
5593 * Here is an example for memory management with g_variant_iter_next():
5594 * |[<!-- language="C" -->
5595 * // Iterates a dictionary of type 'a{sv}'
5596 * void
5597 * iterate_dictionary (GVariant *dictionary)
5599 * GVariantIter iter;
5600 * GVariant *value;
5601 * gchar *key;
5603 * g_variant_iter_init (&iter, dictionary);
5604 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5606 * g_print ("Item '%s' has type '%s'\n", key,
5607 * g_variant_get_type_string (value));
5609 * // must free data for ourselves
5610 * g_variant_unref (value);
5611 * g_free (key);
5614 * ]|
5616 * For a solution that is likely to be more convenient to C programmers
5617 * when dealing with loops, see g_variant_iter_loop().
5619 * @format_string determines the C types that are used for unpacking
5620 * the values and also determines if the values are copied or borrowed.
5622 * See the section on
5623 * [GVariant format strings][gvariant-format-strings-pointers].
5625 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5627 * Since: 2.24
5629 gboolean
5630 g_variant_iter_next (GVariantIter *iter,
5631 const gchar *format_string,
5632 ...)
5634 GVariant *value;
5636 value = g_variant_iter_next_value (iter);
5638 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5639 FALSE);
5641 if (value != NULL)
5643 va_list ap;
5645 va_start (ap, format_string);
5646 g_variant_valist_get (&format_string, value, FALSE, &ap);
5647 va_end (ap);
5649 g_variant_unref (value);
5652 return value != NULL;
5656 * g_variant_iter_loop: (skip)
5657 * @iter: a #GVariantIter
5658 * @format_string: a GVariant format string
5659 * @...: the arguments to unpack the value into
5661 * Gets the next item in the container and unpacks it into the variable
5662 * argument list according to @format_string, returning %TRUE.
5664 * If no more items remain then %FALSE is returned.
5666 * On the first call to this function, the pointers appearing on the
5667 * variable argument list are assumed to point at uninitialised memory.
5668 * On the second and later calls, it is assumed that the same pointers
5669 * will be given and that they will point to the memory as set by the
5670 * previous call to this function. This allows the previous values to
5671 * be freed, as appropriate.
5673 * This function is intended to be used with a while loop as
5674 * demonstrated in the following example. This function can only be
5675 * used when iterating over an array. It is only valid to call this
5676 * function with a string constant for the format string and the same
5677 * string constant must be used each time. Mixing calls to this
5678 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5679 * the same iterator causes undefined behavior.
5681 * If you break out of a such a while loop using g_variant_iter_loop() then
5682 * you must free or unreference all the unpacked values as you would with
5683 * g_variant_get(). Failure to do so will cause a memory leak.
5685 * Here is an example for memory management with g_variant_iter_loop():
5686 * |[<!-- language="C" -->
5687 * // Iterates a dictionary of type 'a{sv}'
5688 * void
5689 * iterate_dictionary (GVariant *dictionary)
5691 * GVariantIter iter;
5692 * GVariant *value;
5693 * gchar *key;
5695 * g_variant_iter_init (&iter, dictionary);
5696 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5698 * g_print ("Item '%s' has type '%s'\n", key,
5699 * g_variant_get_type_string (value));
5701 * // no need to free 'key' and 'value' here
5702 * // unless breaking out of this loop
5705 * ]|
5707 * For most cases you should use g_variant_iter_next().
5709 * This function is really only useful when unpacking into #GVariant or
5710 * #GVariantIter in order to allow you to skip the call to
5711 * g_variant_unref() or g_variant_iter_free().
5713 * For example, if you are only looping over simple integer and string
5714 * types, g_variant_iter_next() is definitely preferred. For string
5715 * types, use the '&' prefix to avoid allocating any memory at all (and
5716 * thereby avoiding the need to free anything as well).
5718 * @format_string determines the C types that are used for unpacking
5719 * the values and also determines if the values are copied or borrowed.
5721 * See the section on
5722 * [GVariant format strings][gvariant-format-strings-pointers].
5724 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5725 * value
5727 * Since: 2.24
5729 gboolean
5730 g_variant_iter_loop (GVariantIter *iter,
5731 const gchar *format_string,
5732 ...)
5734 gboolean first_time = GVSI(iter)->loop_format == NULL;
5735 GVariant *value;
5736 va_list ap;
5738 g_return_val_if_fail (first_time ||
5739 format_string == GVSI(iter)->loop_format,
5740 FALSE);
5742 if (first_time)
5744 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5745 GVSI(iter)->loop_format = format_string;
5747 if (strchr (format_string, '&'))
5748 g_variant_get_data (GVSI(iter)->value);
5751 value = g_variant_iter_next_value (iter);
5753 g_return_val_if_fail (!first_time ||
5754 valid_format_string (format_string, TRUE, value),
5755 FALSE);
5757 va_start (ap, format_string);
5758 g_variant_valist_get (&format_string, value, !first_time, &ap);
5759 va_end (ap);
5761 if (value != NULL)
5762 g_variant_unref (value);
5764 return value != NULL;
5767 /* Serialised data {{{1 */
5768 static GVariant *
5769 g_variant_deep_copy (GVariant *value)
5771 switch (g_variant_classify (value))
5773 case G_VARIANT_CLASS_MAYBE:
5774 case G_VARIANT_CLASS_ARRAY:
5775 case G_VARIANT_CLASS_TUPLE:
5776 case G_VARIANT_CLASS_DICT_ENTRY:
5777 case G_VARIANT_CLASS_VARIANT:
5779 GVariantBuilder builder;
5780 GVariantIter iter;
5781 GVariant *child;
5783 g_variant_builder_init (&builder, g_variant_get_type (value));
5784 g_variant_iter_init (&iter, value);
5786 while ((child = g_variant_iter_next_value (&iter)))
5788 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5789 g_variant_unref (child);
5792 return g_variant_builder_end (&builder);
5795 case G_VARIANT_CLASS_BOOLEAN:
5796 return g_variant_new_boolean (g_variant_get_boolean (value));
5798 case G_VARIANT_CLASS_BYTE:
5799 return g_variant_new_byte (g_variant_get_byte (value));
5801 case G_VARIANT_CLASS_INT16:
5802 return g_variant_new_int16 (g_variant_get_int16 (value));
5804 case G_VARIANT_CLASS_UINT16:
5805 return g_variant_new_uint16 (g_variant_get_uint16 (value));
5807 case G_VARIANT_CLASS_INT32:
5808 return g_variant_new_int32 (g_variant_get_int32 (value));
5810 case G_VARIANT_CLASS_UINT32:
5811 return g_variant_new_uint32 (g_variant_get_uint32 (value));
5813 case G_VARIANT_CLASS_INT64:
5814 return g_variant_new_int64 (g_variant_get_int64 (value));
5816 case G_VARIANT_CLASS_UINT64:
5817 return g_variant_new_uint64 (g_variant_get_uint64 (value));
5819 case G_VARIANT_CLASS_HANDLE:
5820 return g_variant_new_handle (g_variant_get_handle (value));
5822 case G_VARIANT_CLASS_DOUBLE:
5823 return g_variant_new_double (g_variant_get_double (value));
5825 case G_VARIANT_CLASS_STRING:
5826 return g_variant_new_string (g_variant_get_string (value, NULL));
5828 case G_VARIANT_CLASS_OBJECT_PATH:
5829 return g_variant_new_object_path (g_variant_get_string (value, NULL));
5831 case G_VARIANT_CLASS_SIGNATURE:
5832 return g_variant_new_signature (g_variant_get_string (value, NULL));
5835 g_assert_not_reached ();
5839 * g_variant_get_normal_form:
5840 * @value: a #GVariant
5842 * Gets a #GVariant instance that has the same value as @value and is
5843 * trusted to be in normal form.
5845 * If @value is already trusted to be in normal form then a new
5846 * reference to @value is returned.
5848 * If @value is not already trusted, then it is scanned to check if it
5849 * is in normal form. If it is found to be in normal form then it is
5850 * marked as trusted and a new reference to it is returned.
5852 * If @value is found not to be in normal form then a new trusted
5853 * #GVariant is created with the same value as @value.
5855 * It makes sense to call this function if you've received #GVariant
5856 * data from untrusted sources and you want to ensure your serialised
5857 * output is definitely in normal form.
5859 * Returns: (transfer full): a trusted #GVariant
5861 * Since: 2.24
5863 GVariant *
5864 g_variant_get_normal_form (GVariant *value)
5866 GVariant *trusted;
5868 if (g_variant_is_normal_form (value))
5869 return g_variant_ref (value);
5871 trusted = g_variant_deep_copy (value);
5872 g_assert (g_variant_is_trusted (trusted));
5874 return g_variant_ref_sink (trusted);
5878 * g_variant_byteswap:
5879 * @value: a #GVariant
5881 * Performs a byteswapping operation on the contents of @value. The
5882 * result is that all multi-byte numeric data contained in @value is
5883 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
5884 * integers as well as file handles and double precision floating point
5885 * values.
5887 * This function is an identity mapping on any value that does not
5888 * contain multi-byte numeric data. That include strings, booleans,
5889 * bytes and containers containing only these things (recursively).
5891 * The returned value is always in normal form and is marked as trusted.
5893 * Returns: (transfer full): the byteswapped form of @value
5895 * Since: 2.24
5897 GVariant *
5898 g_variant_byteswap (GVariant *value)
5900 GVariantTypeInfo *type_info;
5901 guint alignment;
5902 GVariant *new;
5904 type_info = g_variant_get_type_info (value);
5906 g_variant_type_info_query (type_info, &alignment, NULL);
5908 if (alignment)
5909 /* (potentially) contains multi-byte numeric data */
5911 GVariantSerialised serialised;
5912 GVariant *trusted;
5913 GBytes *bytes;
5915 trusted = g_variant_get_normal_form (value);
5916 serialised.type_info = g_variant_get_type_info (trusted);
5917 serialised.size = g_variant_get_size (trusted);
5918 serialised.data = g_malloc (serialised.size);
5919 g_variant_store (trusted, serialised.data);
5920 g_variant_unref (trusted);
5922 g_variant_serialised_byteswap (serialised);
5924 bytes = g_bytes_new_take (serialised.data, serialised.size);
5925 new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
5926 g_bytes_unref (bytes);
5928 else
5929 /* contains no multi-byte data */
5930 new = value;
5932 return g_variant_ref_sink (new);
5936 * g_variant_new_from_data:
5937 * @type: a definite #GVariantType
5938 * @data: (array length=size) (element-type guint8): the serialised data
5939 * @size: the size of @data
5940 * @trusted: %TRUE if @data is definitely in normal form
5941 * @notify: (scope async): function to call when @data is no longer needed
5942 * @user_data: data for @notify
5944 * Creates a new #GVariant instance from serialised data.
5946 * @type is the type of #GVariant instance that will be constructed.
5947 * The interpretation of @data depends on knowing the type.
5949 * @data is not modified by this function and must remain valid with an
5950 * unchanging value until such a time as @notify is called with
5951 * @user_data. If the contents of @data change before that time then
5952 * the result is undefined.
5954 * If @data is trusted to be serialised data in normal form then
5955 * @trusted should be %TRUE. This applies to serialised data created
5956 * within this process or read from a trusted location on the disk (such
5957 * as a file installed in /usr/lib alongside your application). You
5958 * should set trusted to %FALSE if @data is read from the network, a
5959 * file in the user's home directory, etc.
5961 * If @data was not stored in this machine's native endianness, any multi-byte
5962 * numeric values in the returned variant will also be in non-native
5963 * endianness. g_variant_byteswap() can be used to recover the original values.
5965 * @notify will be called with @user_data when @data is no longer
5966 * needed. The exact time of this call is unspecified and might even be
5967 * before this function returns.
5969 * Returns: (transfer none): a new floating #GVariant of type @type
5971 * Since: 2.24
5973 GVariant *
5974 g_variant_new_from_data (const GVariantType *type,
5975 gconstpointer data,
5976 gsize size,
5977 gboolean trusted,
5978 GDestroyNotify notify,
5979 gpointer user_data)
5981 GVariant *value;
5982 GBytes *bytes;
5984 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
5985 g_return_val_if_fail (data != NULL || size == 0, NULL);
5987 if (notify)
5988 bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
5989 else
5990 bytes = g_bytes_new_static (data, size);
5992 value = g_variant_new_from_bytes (type, bytes, trusted);
5993 g_bytes_unref (bytes);
5995 return value;
5998 /* Epilogue {{{1 */
5999 /* vim:set foldmethod=marker: */