Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / gvariant.c
1 /*
2  * Copyright © 2007, 2008 Ryan Lortie
3  * Copyright © 2010 Codethink Limited
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Author: Ryan Lortie <desrt@desrt.ca>
21  */
22
23 /* Prologue {{{1 */
24
25 #include "config.h"
26
27 #include <glib/gvariant-serialiser.h>
28 #include "gvariant-internal.h"
29 #include <glib/gvariant-core.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gstrfuncs.h>
32 #include <glib/gslice.h>
33 #include <glib/ghash.h>
34 #include <glib/gmem.h>
35
36 #include <string.h>
37
38 /**
39  * SECTION:gvariant
40  * @title: GVariant
41  * @short_description: strongly typed value datatype
42  * @see_also: GVariantType
43  *
44  * #GVariant is a variant datatype; it can contain one or more values
45  * along with information about the type of the values.
46  *
47  * A #GVariant may contain simple types, like an integer, or a boolean value;
48  * or complex types, like an array of two strings, or a dictionary of key
49  * value pairs. A #GVariant is also immutable: once it's been created neither
50  * its type nor its content can be modified further.
51  *
52  * GVariant is useful whenever data needs to be serialized, for example when
53  * sending method parameters in D-Bus, or when saving settings using GSettings.
54  *
55  * When creating a new #GVariant, you pass the data you want to store in it
56  * along with a string representing the type of data you wish to pass to it.
57  *
58  * For instance, if you want to create a #GVariant holding an integer value you
59  * can use:
60  *
61  * |[<!-- language="C" -->
62  *   GVariant *v = g_variant_new ("u", 40);
63  * ]|
64  *
65  * The string "u" in the first argument tells #GVariant that the data passed to
66  * the constructor (40) is going to be an unsigned integer.
67  *
68  * More advanced examples of #GVariant in use can be found in documentation for
69  * [GVariant format strings][gvariant-format-strings-pointers].
70  *
71  * The range of possible values is determined by the type.
72  *
73  * The type system used by #GVariant is #GVariantType. 
74  *
75  * #GVariant instances always have a type and a value (which are given
76  * at construction time).  The type and value of a #GVariant instance
77  * can never change other than by the #GVariant itself being
78  * destroyed.  A #GVariant cannot contain a pointer.
79  *
80  * #GVariant is reference counted using g_variant_ref() and
81  * g_variant_unref().  #GVariant also has floating reference counts --
82  * see g_variant_ref_sink().
83  *
84  * #GVariant is completely threadsafe.  A #GVariant instance can be
85  * concurrently accessed in any way from any number of threads without
86  * problems.
87  *
88  * #GVariant is heavily optimised for dealing with data in serialized
89  * form.  It works particularly well with data located in memory-mapped
90  * files.  It can perform nearly all deserialization operations in a
91  * small constant time, usually touching only a single memory page.
92  * Serialized #GVariant data can also be sent over the network.
93  *
94  * #GVariant is largely compatible with D-Bus.  Almost all types of
95  * #GVariant instances can be sent over D-Bus.  See #GVariantType for
96  * exceptions.  (However, #GVariant's serialization format is not the same
97  * as the serialization format of a D-Bus message body: use #GDBusMessage,
98  * in the gio library, for those.)
99  *
100  * For space-efficiency, the #GVariant serialization format does not
101  * automatically include the variant's length, type or endianness,
102  * which must either be implied from context (such as knowledge that a
103  * particular file format always contains a little-endian
104  * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
105  * or supplied out-of-band (for instance, a length, type and/or endianness
106  * indicator could be placed at the beginning of a file, network message
107  * or network stream).
108  *
109  * A #GVariant's size is limited mainly by any lower level operating
110  * system constraints, such as the number of bits in #gsize.  For
111  * example, it is reasonable to have a 2GB file mapped into memory
112  * with #GMappedFile, and call g_variant_new_from_data() on it.
113  *
114  * For convenience to C programmers, #GVariant features powerful
115  * varargs-based value construction and destruction.  This feature is
116  * designed to be embedded in other libraries.
117  *
118  * There is a Python-inspired text language for describing #GVariant
119  * values.  #GVariant includes a printer for this language and a parser
120  * with type inferencing.
121  *
122  * ## Memory Use
123  *
124  * #GVariant tries to be quite efficient with respect to memory use.
125  * This section gives a rough idea of how much memory is used by the
126  * current implementation.  The information here is subject to change
127  * in the future.
128  *
129  * The memory allocated by #GVariant can be grouped into 4 broad
130  * purposes: memory for serialized data, memory for the type
131  * information cache, buffer management memory and memory for the
132  * #GVariant structure itself.
133  *
134  * ## Serialized Data Memory
135  *
136  * This is the memory that is used for storing GVariant data in
137  * serialized form.  This is what would be sent over the network or
138  * what would end up on disk, not counting any indicator of the
139  * endianness, or of the length or type of the top-level variant.
140  *
141  * The amount of memory required to store a boolean is 1 byte. 16,
142  * 32 and 64 bit integers and double precision floating point numbers
143  * use their "natural" size.  Strings (including object path and
144  * signature strings) are stored with a nul terminator, and as such
145  * use the length of the string plus 1 byte.
146  *
147  * Maybe types use no space at all to represent the null value and
148  * use the same amount of space (sometimes plus one byte) as the
149  * equivalent non-maybe-typed value to represent the non-null case.
150  *
151  * Arrays use the amount of space required to store each of their
152  * members, concatenated.  Additionally, if the items stored in an
153  * array are not of a fixed-size (ie: strings, other arrays, etc)
154  * then an additional framing offset is stored for each item.  The
155  * size of this offset is either 1, 2 or 4 bytes depending on the
156  * overall size of the container.  Additionally, extra padding bytes
157  * are added as required for alignment of child values.
158  *
159  * Tuples (including dictionary entries) use the amount of space
160  * required to store each of their members, concatenated, plus one
161  * framing offset (as per arrays) for each non-fixed-sized item in
162  * the tuple, except for the last one.  Additionally, extra padding
163  * bytes are added as required for alignment of child values.
164  *
165  * Variants use the same amount of space as the item inside of the
166  * variant, plus 1 byte, plus the length of the type string for the
167  * item inside the variant.
168  *
169  * As an example, consider a dictionary mapping strings to variants.
170  * In the case that the dictionary is empty, 0 bytes are required for
171  * the serialization.
172  *
173  * If we add an item "width" that maps to the int32 value of 500 then
174  * we will use 4 byte to store the int32 (so 6 for the variant
175  * containing it) and 6 bytes for the string.  The variant must be
176  * aligned to 8 after the 6 bytes of the string, so that's 2 extra
177  * bytes.  6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
178  * for the dictionary entry.  An additional 1 byte is added to the
179  * array as a framing offset making a total of 15 bytes.
180  *
181  * If we add another entry, "title" that maps to a nullable string
182  * that happens to have a value of null, then we use 0 bytes for the
183  * null value (and 3 bytes for the variant to contain it along with
184  * its type string) plus 6 bytes for the string.  Again, we need 2
185  * padding bytes.  That makes a total of 6 + 2 + 3 = 11 bytes.
186  *
187  * We now require extra padding between the two items in the array.
188  * After the 14 bytes of the first item, that's 2 bytes required.
189  * We now require 2 framing offsets for an extra two
190  * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
191  * dictionary.
192  *
193  * ## Type Information Cache
194  *
195  * For each GVariant type that currently exists in the program a type
196  * information structure is kept in the type information cache.  The
197  * type information structure is required for rapid deserialization.
198  *
199  * Continuing with the above example, if a #GVariant exists with the
200  * type "a{sv}" then a type information struct will exist for
201  * "a{sv}", "{sv}", "s", and "v".  Multiple uses of the same type
202  * will share the same type information.  Additionally, all
203  * single-digit types are stored in read-only static memory and do
204  * not contribute to the writable memory footprint of a program using
205  * #GVariant.
206  *
207  * Aside from the type information structures stored in read-only
208  * memory, there are two forms of type information.  One is used for
209  * container types where there is a single element type: arrays and
210  * maybe types.  The other is used for container types where there
211  * are multiple element types: tuples and dictionary entries.
212  *
213  * Array type info structures are 6 * sizeof (void *), plus the
214  * memory required to store the type string itself.  This means that
215  * on 32-bit systems, the cache entry for "a{sv}" would require 30
216  * bytes of memory (plus malloc overhead).
217  *
218  * Tuple type info structures are 6 * sizeof (void *), plus 4 *
219  * sizeof (void *) for each item in the tuple, plus the memory
220  * required to store the type string itself.  A 2-item tuple, for
221  * example, would have a type information structure that consumed
222  * writable memory in the size of 14 * sizeof (void *) (plus type
223  * string)  This means that on 32-bit systems, the cache entry for
224  * "{sv}" would require 61 bytes of memory (plus malloc overhead).
225  *
226  * This means that in total, for our "a{sv}" example, 91 bytes of
227  * type information would be allocated.
228  * 
229  * The type information cache, additionally, uses a #GHashTable to
230  * store and look up the cached items and stores a pointer to this
231  * hash table in static storage.  The hash table is freed when there
232  * are zero items in the type cache.
233  *
234  * Although these sizes may seem large it is important to remember
235  * that a program will probably only have a very small number of
236  * different types of values in it and that only one type information
237  * structure is required for many different values of the same type.
238  *
239  * ## Buffer Management Memory
240  *
241  * #GVariant uses an internal buffer management structure to deal
242  * with the various different possible sources of serialized data
243  * that it uses.  The buffer is responsible for ensuring that the
244  * correct call is made when the data is no longer in use by
245  * #GVariant.  This may involve a g_free() or a g_slice_free() or
246  * even g_mapped_file_unref().
247  *
248  * One buffer management structure is used for each chunk of
249  * serialized data.  The size of the buffer management structure
250  * is 4 * (void *).  On 32-bit systems, that's 16 bytes.
251  *
252  * ## GVariant structure
253  *
254  * The size of a #GVariant structure is 6 * (void *).  On 32-bit
255  * systems, that's 24 bytes.
256  *
257  * #GVariant structures only exist if they are explicitly created
258  * with API calls.  For example, if a #GVariant is constructed out of
259  * serialized data for the example given above (with the dictionary)
260  * then although there are 9 individual values that comprise the
261  * entire dictionary (two keys, two values, two variants containing
262  * the values, two dictionary entries, plus the dictionary itself),
263  * only 1 #GVariant instance exists -- the one referring to the
264  * dictionary.
265  *
266  * If calls are made to start accessing the other values then
267  * #GVariant instances will exist for those values only for as long
268  * as they are in use (ie: until you call g_variant_unref()).  The
269  * type information is shared.  The serialized data and the buffer
270  * management structure for that serialized data is shared by the
271  * child.
272  *
273  * ## Summary
274  *
275  * To put the entire example together, for our dictionary mapping
276  * strings to variants (with two entries, as given above), we are
277  * using 91 bytes of memory for type information, 29 bytes of memory
278  * for the serialized data, 16 bytes for buffer management and 24
279  * bytes for the #GVariant instance, or a total of 160 bytes, plus
280  * malloc overhead.  If we were to use g_variant_get_child_value() to
281  * access the two dictionary entries, we would use an additional 48
282  * bytes.  If we were to have other dictionaries of the same type, we
283  * would use more memory for the serialized data and buffer
284  * management for those dictionaries, but the type information would
285  * be shared.
286  */
287
288 /* definition of GVariant structure is in gvariant-core.c */
289
290 /* this is a g_return_val_if_fail() for making
291  * sure a (GVariant *) has the required type.
292  */
293 #define TYPE_CHECK(value, TYPE, val) \
294   if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) {           \
295     g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC,            \
296                               "g_variant_is_of_type (" #value     \
297                               ", " #TYPE ")");                    \
298     return val;                                                   \
299   }
300
301 /* Numeric Type Constructor/Getters {{{1 */
302 /* < private >
303  * g_variant_new_from_trusted:
304  * @type: the #GVariantType
305  * @data: the data to use
306  * @size: the size of @data
307  *
308  * Constructs a new trusted #GVariant instance from the provided data.
309  * This is used to implement g_variant_new_* for all the basic types.
310  *
311  * Note: @data must be backed by memory that is aligned appropriately for the
312  * @type being loaded. Otherwise this function will internally create a copy of
313  * the memory (since GLib 2.60) or (in older versions) fail and exit the
314  * process.
315  *
316  * Returns: a new floating #GVariant
317  */
318 static GVariant *
319 g_variant_new_from_trusted (const GVariantType *type,
320                             gconstpointer       data,
321                             gsize               size)
322 {
323   GVariant *value;
324   GBytes *bytes;
325
326   bytes = g_bytes_new (data, size);
327   value = g_variant_new_from_bytes (type, bytes, TRUE);
328   g_bytes_unref (bytes);
329
330   return value;
331 }
332
333 /**
334  * g_variant_new_boolean:
335  * @value: a #gboolean value
336  *
337  * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
338  *
339  * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
340  *
341  * Since: 2.24
342  **/
343 GVariant *
344 g_variant_new_boolean (gboolean value)
345 {
346   guchar v = value;
347
348   return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
349 }
350
351 /**
352  * g_variant_get_boolean:
353  * @value: a boolean #GVariant instance
354  *
355  * Returns the boolean value of @value.
356  *
357  * It is an error to call this function with a @value of any type
358  * other than %G_VARIANT_TYPE_BOOLEAN.
359  *
360  * Returns: %TRUE or %FALSE
361  *
362  * Since: 2.24
363  **/
364 gboolean
365 g_variant_get_boolean (GVariant *value)
366 {
367   const guchar *data;
368
369   TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
370
371   data = g_variant_get_data (value);
372
373   return data != NULL ? *data != 0 : FALSE;
374 }
375
376 /* the constructors and accessors for byte, int{16,32,64}, handles and
377  * doubles all look pretty much exactly the same, so we reduce
378  * copy/pasting here.
379  */
380 #define NUMERIC_TYPE(TYPE, type, ctype) \
381   GVariant *g_variant_new_##type (ctype value) {                \
382     return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE,   \
383                                        &value, sizeof value);   \
384   }                                                             \
385   ctype g_variant_get_##type (GVariant *value) {                \
386     const ctype *data;                                          \
387     TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0);             \
388     data = g_variant_get_data (value);                          \
389     return data != NULL ? *data : 0;                            \
390   }
391
392
393 /**
394  * g_variant_new_byte:
395  * @value: a #guint8 value
396  *
397  * Creates a new byte #GVariant instance.
398  *
399  * Returns: (transfer none): a floating reference to a new byte #GVariant instance
400  *
401  * Since: 2.24
402  **/
403 /**
404  * g_variant_get_byte:
405  * @value: a byte #GVariant instance
406  *
407  * Returns the byte value of @value.
408  *
409  * It is an error to call this function with a @value of any type
410  * other than %G_VARIANT_TYPE_BYTE.
411  *
412  * Returns: a #guint8
413  *
414  * Since: 2.24
415  **/
416 NUMERIC_TYPE (BYTE, byte, guint8)
417
418 /**
419  * g_variant_new_int16:
420  * @value: a #gint16 value
421  *
422  * Creates a new int16 #GVariant instance.
423  *
424  * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
425  *
426  * Since: 2.24
427  **/
428 /**
429  * g_variant_get_int16:
430  * @value: an int16 #GVariant instance
431  *
432  * Returns the 16-bit signed integer value of @value.
433  *
434  * It is an error to call this function with a @value of any type
435  * other than %G_VARIANT_TYPE_INT16.
436  *
437  * Returns: a #gint16
438  *
439  * Since: 2.24
440  **/
441 NUMERIC_TYPE (INT16, int16, gint16)
442
443 /**
444  * g_variant_new_uint16:
445  * @value: a #guint16 value
446  *
447  * Creates a new uint16 #GVariant instance.
448  *
449  * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
450  *
451  * Since: 2.24
452  **/
453 /**
454  * g_variant_get_uint16:
455  * @value: a uint16 #GVariant instance
456  *
457  * Returns the 16-bit unsigned integer value of @value.
458  *
459  * It is an error to call this function with a @value of any type
460  * other than %G_VARIANT_TYPE_UINT16.
461  *
462  * Returns: a #guint16
463  *
464  * Since: 2.24
465  **/
466 NUMERIC_TYPE (UINT16, uint16, guint16)
467
468 /**
469  * g_variant_new_int32:
470  * @value: a #gint32 value
471  *
472  * Creates a new int32 #GVariant instance.
473  *
474  * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
475  *
476  * Since: 2.24
477  **/
478 /**
479  * g_variant_get_int32:
480  * @value: an int32 #GVariant instance
481  *
482  * Returns the 32-bit signed integer value of @value.
483  *
484  * It is an error to call this function with a @value of any type
485  * other than %G_VARIANT_TYPE_INT32.
486  *
487  * Returns: a #gint32
488  *
489  * Since: 2.24
490  **/
491 NUMERIC_TYPE (INT32, int32, gint32)
492
493 /**
494  * g_variant_new_uint32:
495  * @value: a #guint32 value
496  *
497  * Creates a new uint32 #GVariant instance.
498  *
499  * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
500  *
501  * Since: 2.24
502  **/
503 /**
504  * g_variant_get_uint32:
505  * @value: a uint32 #GVariant instance
506  *
507  * Returns the 32-bit unsigned integer value of @value.
508  *
509  * It is an error to call this function with a @value of any type
510  * other than %G_VARIANT_TYPE_UINT32.
511  *
512  * Returns: a #guint32
513  *
514  * Since: 2.24
515  **/
516 NUMERIC_TYPE (UINT32, uint32, guint32)
517
518 /**
519  * g_variant_new_int64:
520  * @value: a #gint64 value
521  *
522  * Creates a new int64 #GVariant instance.
523  *
524  * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
525  *
526  * Since: 2.24
527  **/
528 /**
529  * g_variant_get_int64:
530  * @value: an int64 #GVariant instance
531  *
532  * Returns the 64-bit signed integer value of @value.
533  *
534  * It is an error to call this function with a @value of any type
535  * other than %G_VARIANT_TYPE_INT64.
536  *
537  * Returns: a #gint64
538  *
539  * Since: 2.24
540  **/
541 NUMERIC_TYPE (INT64, int64, gint64)
542
543 /**
544  * g_variant_new_uint64:
545  * @value: a #guint64 value
546  *
547  * Creates a new uint64 #GVariant instance.
548  *
549  * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
550  *
551  * Since: 2.24
552  **/
553 /**
554  * g_variant_get_uint64:
555  * @value: a uint64 #GVariant instance
556  *
557  * Returns the 64-bit unsigned integer value of @value.
558  *
559  * It is an error to call this function with a @value of any type
560  * other than %G_VARIANT_TYPE_UINT64.
561  *
562  * Returns: a #guint64
563  *
564  * Since: 2.24
565  **/
566 NUMERIC_TYPE (UINT64, uint64, guint64)
567
568 /**
569  * g_variant_new_handle:
570  * @value: a #gint32 value
571  *
572  * Creates a new handle #GVariant instance.
573  *
574  * By convention, handles are indexes into an array of file descriptors
575  * that are sent alongside a D-Bus message.  If you're not interacting
576  * with D-Bus, you probably don't need them.
577  *
578  * Returns: (transfer none): a floating reference to a new handle #GVariant instance
579  *
580  * Since: 2.24
581  **/
582 /**
583  * g_variant_get_handle:
584  * @value: a handle #GVariant instance
585  *
586  * Returns the 32-bit signed integer value of @value.
587  *
588  * It is an error to call this function with a @value of any type other
589  * than %G_VARIANT_TYPE_HANDLE.
590  *
591  * By convention, handles are indexes into an array of file descriptors
592  * that are sent alongside a D-Bus message.  If you're not interacting
593  * with D-Bus, you probably don't need them.
594  *
595  * Returns: a #gint32
596  *
597  * Since: 2.24
598  **/
599 NUMERIC_TYPE (HANDLE, handle, gint32)
600
601 /**
602  * g_variant_new_double:
603  * @value: a #gdouble floating point value
604  *
605  * Creates a new double #GVariant instance.
606  *
607  * Returns: (transfer none): a floating reference to a new double #GVariant instance
608  *
609  * Since: 2.24
610  **/
611 /**
612  * g_variant_get_double:
613  * @value: a double #GVariant instance
614  *
615  * Returns the double precision floating point value of @value.
616  *
617  * It is an error to call this function with a @value of any type
618  * other than %G_VARIANT_TYPE_DOUBLE.
619  *
620  * Returns: a #gdouble
621  *
622  * Since: 2.24
623  **/
624 NUMERIC_TYPE (DOUBLE, double, gdouble)
625
626 /* Container type Constructor / Deconstructors {{{1 */
627 /**
628  * g_variant_new_maybe:
629  * @child_type: (nullable): the #GVariantType of the child, or %NULL
630  * @child: (nullable): the child value, or %NULL
631  *
632  * Depending on if @child is %NULL, either wraps @child inside of a
633  * maybe container or creates a Nothing instance for the given @type.
634  *
635  * At least one of @child_type and @child must be non-%NULL.
636  * If @child_type is non-%NULL then it must be a definite type.
637  * If they are both non-%NULL then @child_type must be the type
638  * of @child.
639  *
640  * If @child is a floating reference (see g_variant_ref_sink()), the new
641  * instance takes ownership of @child.
642  *
643  * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
644  *
645  * Since: 2.24
646  **/
647 GVariant *
648 g_variant_new_maybe (const GVariantType *child_type,
649                      GVariant           *child)
650 {
651   GVariantType *maybe_type;
652   GVariant *value;
653
654   g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
655                         (child_type), 0);
656   g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
657   g_return_val_if_fail (child_type == NULL || child == NULL ||
658                         g_variant_is_of_type (child, child_type),
659                         NULL);
660
661   if (child_type == NULL)
662     child_type = g_variant_get_type (child);
663
664   maybe_type = g_variant_type_new_maybe (child_type);
665
666   if (child != NULL)
667     {
668       GVariant **children;
669       gboolean trusted;
670
671       children = g_new (GVariant *, 1);
672       children[0] = g_variant_ref_sink (child);
673       trusted = g_variant_is_trusted (children[0]);
674
675       value = g_variant_new_from_children (maybe_type, children, 1, trusted);
676     }
677   else
678     value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
679
680   g_variant_type_free (maybe_type);
681
682   return value;
683 }
684
685 /**
686  * g_variant_get_maybe:
687  * @value: a maybe-typed value
688  *
689  * Given a maybe-typed #GVariant instance, extract its value.  If the
690  * value is Nothing, then this function returns %NULL.
691  *
692  * Returns: (nullable) (transfer full): the contents of @value, or %NULL
693  *
694  * Since: 2.24
695  **/
696 GVariant *
697 g_variant_get_maybe (GVariant *value)
698 {
699   TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
700
701   if (g_variant_n_children (value))
702     return g_variant_get_child_value (value, 0);
703
704   return NULL;
705 }
706
707 /**
708  * g_variant_new_variant: (constructor)
709  * @value: a #GVariant instance
710  *
711  * Boxes @value.  The result is a #GVariant instance representing a
712  * variant containing the original value.
713  *
714  * If @child is a floating reference (see g_variant_ref_sink()), the new
715  * instance takes ownership of @child.
716  *
717  * Returns: (transfer none): a floating reference to a new variant #GVariant instance
718  *
719  * Since: 2.24
720  **/
721 GVariant *
722 g_variant_new_variant (GVariant *value)
723 {
724   g_return_val_if_fail (value != NULL, NULL);
725
726   g_variant_ref_sink (value);
727
728   return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
729                                       g_memdup2 (&value, sizeof value),
730                                       1, g_variant_is_trusted (value));
731 }
732
733 /**
734  * g_variant_get_variant:
735  * @value: a variant #GVariant instance
736  *
737  * Unboxes @value.  The result is the #GVariant instance that was
738  * contained in @value.
739  *
740  * Returns: (transfer full): the item contained in the variant
741  *
742  * Since: 2.24
743  **/
744 GVariant *
745 g_variant_get_variant (GVariant *value)
746 {
747   TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
748
749   return g_variant_get_child_value (value, 0);
750 }
751
752 /**
753  * g_variant_new_array:
754  * @child_type: (nullable): the element type of the new array
755  * @children: (nullable) (array length=n_children): an array of
756  *            #GVariant pointers, the children
757  * @n_children: the length of @children
758  *
759  * Creates a new #GVariant array from @children.
760  *
761  * @child_type must be non-%NULL if @n_children is zero.  Otherwise, the
762  * child type is determined by inspecting the first element of the
763  * @children array.  If @child_type is non-%NULL then it must be a
764  * definite type.
765  *
766  * The items of the array are taken from the @children array.  No entry
767  * in the @children array may be %NULL.
768  *
769  * All items in the array must have the same type, which must be the
770  * same as @child_type, if given.
771  *
772  * If the @children are floating references (see g_variant_ref_sink()), the
773  * new instance takes ownership of them as if via g_variant_ref_sink().
774  *
775  * Returns: (transfer none): a floating reference to a new #GVariant array
776  *
777  * Since: 2.24
778  **/
779 GVariant *
780 g_variant_new_array (const GVariantType *child_type,
781                      GVariant * const   *children,
782                      gsize               n_children)
783 {
784   GVariantType *array_type;
785   GVariant **my_children;
786   gboolean trusted;
787   GVariant *value;
788   gsize i;
789
790   g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
791   g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
792   g_return_val_if_fail (child_type == NULL ||
793                         g_variant_type_is_definite (child_type), NULL);
794
795   my_children = g_new (GVariant *, n_children);
796   trusted = TRUE;
797
798   if (child_type == NULL)
799     child_type = g_variant_get_type (children[0]);
800   array_type = g_variant_type_new_array (child_type);
801
802   for (i = 0; i < n_children; i++)
803     {
804       gboolean is_of_child_type = g_variant_is_of_type (children[i], child_type);
805       if G_UNLIKELY (!is_of_child_type)
806         {
807           while (i != 0)
808             g_variant_unref (my_children[--i]);
809           g_free (my_children);
810           g_return_val_if_fail (is_of_child_type, NULL);
811         }
812       my_children[i] = g_variant_ref_sink (children[i]);
813       trusted &= g_variant_is_trusted (children[i]);
814     }
815
816   value = g_variant_new_from_children (array_type, my_children,
817                                        n_children, trusted);
818   g_variant_type_free (array_type);
819
820   return value;
821 }
822
823 /*< private >
824  * g_variant_make_tuple_type:
825  * @children: (array length=n_children): an array of GVariant *
826  * @n_children: the length of @children
827  *
828  * Return the type of a tuple containing @children as its items.
829  **/
830 static GVariantType *
831 g_variant_make_tuple_type (GVariant * const *children,
832                            gsize             n_children)
833 {
834   const GVariantType **types;
835   GVariantType *type;
836   gsize i;
837
838   types = g_new (const GVariantType *, n_children);
839
840   for (i = 0; i < n_children; i++)
841     types[i] = g_variant_get_type (children[i]);
842
843   type = g_variant_type_new_tuple (types, n_children);
844   g_free (types);
845
846   return type;
847 }
848
849 /**
850  * g_variant_new_tuple:
851  * @children: (array length=n_children): the items to make the tuple out of
852  * @n_children: the length of @children
853  *
854  * Creates a new tuple #GVariant out of the items in @children.  The
855  * type is determined from the types of @children.  No entry in the
856  * @children array may be %NULL.
857  *
858  * If @n_children is 0 then the unit tuple is constructed.
859  *
860  * If the @children are floating references (see g_variant_ref_sink()), the
861  * new instance takes ownership of them as if via g_variant_ref_sink().
862  *
863  * Returns: (transfer none): a floating reference to a new #GVariant tuple
864  *
865  * Since: 2.24
866  **/
867 GVariant *
868 g_variant_new_tuple (GVariant * const *children,
869                      gsize             n_children)
870 {
871   GVariantType *tuple_type;
872   GVariant **my_children;
873   gboolean trusted;
874   GVariant *value;
875   gsize i;
876
877   g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
878
879   my_children = g_new (GVariant *, n_children);
880   trusted = TRUE;
881
882   for (i = 0; i < n_children; i++)
883     {
884       my_children[i] = g_variant_ref_sink (children[i]);
885       trusted &= g_variant_is_trusted (children[i]);
886     }
887
888   tuple_type = g_variant_make_tuple_type (children, n_children);
889   value = g_variant_new_from_children (tuple_type, my_children,
890                                        n_children, trusted);
891   g_variant_type_free (tuple_type);
892
893   return value;
894 }
895
896 /*< private >
897  * g_variant_make_dict_entry_type:
898  * @key: a #GVariant, the key
899  * @val: a #GVariant, the value
900  *
901  * Return the type of a dictionary entry containing @key and @val as its
902  * children.
903  **/
904 static GVariantType *
905 g_variant_make_dict_entry_type (GVariant *key,
906                                 GVariant *val)
907 {
908   return g_variant_type_new_dict_entry (g_variant_get_type (key),
909                                         g_variant_get_type (val));
910 }
911
912 /**
913  * g_variant_new_dict_entry: (constructor)
914  * @key: a basic #GVariant, the key
915  * @value: a #GVariant, the value
916  *
917  * Creates a new dictionary entry #GVariant. @key and @value must be
918  * non-%NULL. @key must be a value of a basic type (ie: not a container).
919  *
920  * If the @key or @value are floating references (see g_variant_ref_sink()),
921  * the new instance takes ownership of them as if via g_variant_ref_sink().
922  *
923  * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
924  *
925  * Since: 2.24
926  **/
927 GVariant *
928 g_variant_new_dict_entry (GVariant *key,
929                           GVariant *value)
930 {
931   GVariantType *dict_type;
932   GVariant **children;
933   gboolean trusted;
934
935   g_return_val_if_fail (key != NULL && value != NULL, NULL);
936   g_return_val_if_fail (!g_variant_is_container (key), NULL);
937
938   children = g_new (GVariant *, 2);
939   children[0] = g_variant_ref_sink (key);
940   children[1] = g_variant_ref_sink (value);
941   trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
942
943   dict_type = g_variant_make_dict_entry_type (key, value);
944   value = g_variant_new_from_children (dict_type, children, 2, trusted);
945   g_variant_type_free (dict_type);
946
947   return value;
948 }
949
950 /**
951  * g_variant_lookup: (skip)
952  * @dictionary: a dictionary #GVariant
953  * @key: the key to look up in the dictionary
954  * @format_string: a GVariant format string
955  * @...: the arguments to unpack the value into
956  *
957  * Looks up a value in a dictionary #GVariant.
958  *
959  * This function is a wrapper around g_variant_lookup_value() and
960  * g_variant_get().  In the case that %NULL would have been returned,
961  * this function returns %FALSE.  Otherwise, it unpacks the returned
962  * value and returns %TRUE.
963  *
964  * @format_string determines the C types that are used for unpacking
965  * the values and also determines if the values are copied or borrowed,
966  * see the section on
967  * [GVariant format strings][gvariant-format-strings-pointers].
968  *
969  * This function is currently implemented with a linear scan.  If you
970  * plan to do many lookups then #GVariantDict may be more efficient.
971  *
972  * Returns: %TRUE if a value was unpacked
973  *
974  * Since: 2.28
975  */
976 gboolean
977 g_variant_lookup (GVariant    *dictionary,
978                   const gchar *key,
979                   const gchar *format_string,
980                   ...)
981 {
982   GVariantType *type;
983   GVariant *value;
984
985   /* flatten */
986   g_variant_get_data (dictionary);
987
988   type = g_variant_format_string_scan_type (format_string, NULL, NULL);
989   value = g_variant_lookup_value (dictionary, key, type);
990   g_variant_type_free (type);
991
992   if (value)
993     {
994       va_list ap;
995
996       va_start (ap, format_string);
997       g_variant_get_va (value, format_string, NULL, &ap);
998       g_variant_unref (value);
999       va_end (ap);
1000
1001       return TRUE;
1002     }
1003
1004   else
1005     return FALSE;
1006 }
1007
1008 /**
1009  * g_variant_lookup_value:
1010  * @dictionary: a dictionary #GVariant
1011  * @key: the key to look up in the dictionary
1012  * @expected_type: (nullable): a #GVariantType, or %NULL
1013  *
1014  * Looks up a value in a dictionary #GVariant.
1015  *
1016  * This function works with dictionaries of the type a{s*} (and equally
1017  * well with type a{o*}, but we only further discuss the string case
1018  * for sake of clarity).
1019  *
1020  * In the event that @dictionary has the type a{sv}, the @expected_type
1021  * string specifies what type of value is expected to be inside of the
1022  * variant. If the value inside the variant has a different type then
1023  * %NULL is returned. In the event that @dictionary has a value type other
1024  * than v then @expected_type must directly match the value type and it is
1025  * used to unpack the value directly or an error occurs.
1026  *
1027  * In either case, if @key is not found in @dictionary, %NULL is returned.
1028  *
1029  * If the key is found and the value has the correct type, it is
1030  * returned.  If @expected_type was specified then any non-%NULL return
1031  * value will have this type.
1032  *
1033  * This function is currently implemented with a linear scan.  If you
1034  * plan to do many lookups then #GVariantDict may be more efficient.
1035  *
1036  * Returns: (transfer full): the value of the dictionary key, or %NULL
1037  *
1038  * Since: 2.28
1039  */
1040 GVariant *
1041 g_variant_lookup_value (GVariant           *dictionary,
1042                         const gchar        *key,
1043                         const GVariantType *expected_type)
1044 {
1045   GVariantIter iter;
1046   GVariant *entry;
1047   GVariant *value;
1048
1049   g_return_val_if_fail (g_variant_is_of_type (dictionary,
1050                                               G_VARIANT_TYPE ("a{s*}")) ||
1051                         g_variant_is_of_type (dictionary,
1052                                               G_VARIANT_TYPE ("a{o*}")),
1053                         NULL);
1054
1055   g_variant_iter_init (&iter, dictionary);
1056
1057   while ((entry = g_variant_iter_next_value (&iter)))
1058     {
1059       GVariant *entry_key;
1060       gboolean matches;
1061
1062       entry_key = g_variant_get_child_value (entry, 0);
1063       matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1064       g_variant_unref (entry_key);
1065
1066       if (matches)
1067         break;
1068
1069       g_variant_unref (entry);
1070     }
1071
1072   if (entry == NULL)
1073     return NULL;
1074
1075   value = g_variant_get_child_value (entry, 1);
1076   g_variant_unref (entry);
1077
1078   if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1079     {
1080       GVariant *tmp;
1081
1082       tmp = g_variant_get_variant (value);
1083       g_variant_unref (value);
1084
1085       if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1086         {
1087           g_variant_unref (tmp);
1088           tmp = NULL;
1089         }
1090
1091       value = tmp;
1092     }
1093
1094   g_return_val_if_fail (expected_type == NULL || value == NULL ||
1095                         g_variant_is_of_type (value, expected_type), NULL);
1096
1097   return value;
1098 }
1099
1100 /**
1101  * g_variant_get_fixed_array:
1102  * @value: a #GVariant array with fixed-sized elements
1103  * @n_elements: (out): a pointer to the location to store the number of items
1104  * @element_size: the size of each element
1105  *
1106  * Provides access to the serialized data for an array of fixed-sized
1107  * items.
1108  *
1109  * @value must be an array with fixed-sized elements.  Numeric types are
1110  * fixed-size, as are tuples containing only other fixed-sized types.
1111  *
1112  * @element_size must be the size of a single element in the array,
1113  * as given by the section on
1114  * [serialized data memory][gvariant-serialized-data-memory].
1115  *
1116  * In particular, arrays of these fixed-sized types can be interpreted
1117  * as an array of the given C type, with @element_size set to the size
1118  * the appropriate type:
1119  * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1120  * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1121  * - %G_VARIANT_TYPE_BYTE: #guint8
1122  * - %G_VARIANT_TYPE_HANDLE: #guint32
1123  * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1124  *
1125  * For example, if calling this function for an array of 32-bit integers,
1126  * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1127  * of a double-check that the form of the serialized data matches the caller's
1128  * expectation.
1129  *
1130  * @n_elements, which must be non-%NULL, is set equal to the number of
1131  * items in the array.
1132  *
1133  * Returns: (array length=n_elements) (transfer none): a pointer to
1134  *     the fixed array
1135  *
1136  * Since: 2.24
1137  **/
1138 gconstpointer
1139 g_variant_get_fixed_array (GVariant *value,
1140                            gsize    *n_elements,
1141                            gsize     element_size)
1142 {
1143   GVariantTypeInfo *array_info;
1144   gsize array_element_size;
1145   gconstpointer data;
1146   gsize size;
1147
1148   TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1149
1150   g_return_val_if_fail (n_elements != NULL, NULL);
1151   g_return_val_if_fail (element_size > 0, NULL);
1152
1153   array_info = g_variant_get_type_info (value);
1154   g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1155
1156   g_return_val_if_fail (array_element_size, NULL);
1157
1158   if G_UNLIKELY (array_element_size != element_size)
1159     {
1160       if (array_element_size)
1161         g_critical ("g_variant_get_fixed_array: assertion "
1162                     "'g_variant_array_has_fixed_size (value, element_size)' "
1163                     "failed: array size %"G_GSIZE_FORMAT" does not match "
1164                     "given element_size %"G_GSIZE_FORMAT".",
1165                     array_element_size, element_size);
1166       else
1167         g_critical ("g_variant_get_fixed_array: assertion "
1168                     "'g_variant_array_has_fixed_size (value, element_size)' "
1169                     "failed: array does not have fixed size.");
1170     }
1171
1172   data = g_variant_get_data (value);
1173   size = g_variant_get_size (value);
1174
1175   if (size % element_size)
1176     *n_elements = 0;
1177   else
1178     *n_elements = size / element_size;
1179
1180   if (*n_elements)
1181     return data;
1182
1183   return NULL;
1184 }
1185
1186 /**
1187  * g_variant_new_fixed_array:
1188  * @element_type: the #GVariantType of each element
1189  * @elements: a pointer to the fixed array of contiguous elements
1190  * @n_elements: the number of elements
1191  * @element_size: the size of each element
1192  *
1193  * Constructs a new array #GVariant instance, where the elements are
1194  * of @element_type type.
1195  *
1196  * @elements must be an array with fixed-sized elements.  Numeric types are
1197  * fixed-size as are tuples containing only other fixed-sized types.
1198  *
1199  * @element_size must be the size of a single element in the array.
1200  * For example, if calling this function for an array of 32-bit integers,
1201  * you might say sizeof(gint32). This value isn't used except for the purpose
1202  * of a double-check that the form of the serialized data matches the caller's
1203  * expectation.
1204  *
1205  * @n_elements must be the length of the @elements array.
1206  *
1207  * Returns: (transfer none): a floating reference to a new array #GVariant instance
1208  *
1209  * Since: 2.32
1210  **/
1211 GVariant *
1212 g_variant_new_fixed_array (const GVariantType  *element_type,
1213                            gconstpointer        elements,
1214                            gsize                n_elements,
1215                            gsize                element_size)
1216 {
1217   GVariantType *array_type;
1218   gsize array_element_size;
1219   GVariantTypeInfo *array_info;
1220   GVariant *value;
1221   gpointer data;
1222
1223   g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1224   g_return_val_if_fail (element_size > 0, NULL);
1225
1226   array_type = g_variant_type_new_array (element_type);
1227   array_info = g_variant_type_info_get (array_type);
1228   g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1229   if G_UNLIKELY (array_element_size != element_size)
1230     {
1231       if (array_element_size)
1232         g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1233                     " does not match given element_size %" G_GSIZE_FORMAT ".",
1234                     array_element_size, element_size);
1235       else
1236         g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1237       return NULL;
1238     }
1239
1240   data = g_memdup2 (elements, n_elements * element_size);
1241   value = g_variant_new_from_data (array_type, data,
1242                                    n_elements * element_size,
1243                                    FALSE, g_free, data);
1244
1245   g_variant_type_free (array_type);
1246   g_variant_type_info_unref (array_info);
1247
1248   return value;
1249 }
1250
1251 /* String type constructor/getters/validation {{{1 */
1252 /**
1253  * g_variant_new_string:
1254  * @string: a normal UTF-8 nul-terminated string
1255  *
1256  * Creates a string #GVariant with the contents of @string.
1257  *
1258  * @string must be valid UTF-8, and must not be %NULL. To encode
1259  * potentially-%NULL strings, use g_variant_new() with `ms` as the
1260  * [format string][gvariant-format-strings-maybe-types].
1261  *
1262  * Returns: (transfer none): a floating reference to a new string #GVariant instance
1263  *
1264  * Since: 2.24
1265  **/
1266 GVariant *
1267 g_variant_new_string (const gchar *string)
1268 {
1269   g_return_val_if_fail (string != NULL, NULL);
1270   g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1271
1272   return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1273                                      string, strlen (string) + 1);
1274 }
1275
1276 /**
1277  * g_variant_new_take_string: (skip)
1278  * @string: a normal UTF-8 nul-terminated string
1279  *
1280  * Creates a string #GVariant with the contents of @string.
1281  *
1282  * @string must be valid UTF-8, and must not be %NULL. To encode
1283  * potentially-%NULL strings, use this with g_variant_new_maybe().
1284  *
1285  * This function consumes @string.  g_free() will be called on @string
1286  * when it is no longer required.
1287  *
1288  * You must not modify or access @string in any other way after passing
1289  * it to this function.  It is even possible that @string is immediately
1290  * freed.
1291  *
1292  * Returns: (transfer none): a floating reference to a new string
1293  *   #GVariant instance
1294  *
1295  * Since: 2.38
1296  **/
1297 GVariant *
1298 g_variant_new_take_string (gchar *string)
1299 {
1300   GVariant *value;
1301   GBytes *bytes;
1302
1303   g_return_val_if_fail (string != NULL, NULL);
1304   g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1305
1306   bytes = g_bytes_new_take (string, strlen (string) + 1);
1307   value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1308   g_bytes_unref (bytes);
1309
1310   return value;
1311 }
1312
1313 /**
1314  * g_variant_new_printf: (skip)
1315  * @format_string: a printf-style format string
1316  * @...: arguments for @format_string
1317  *
1318  * Creates a string-type GVariant using printf formatting.
1319  *
1320  * This is similar to calling g_strdup_printf() and then
1321  * g_variant_new_string() but it saves a temporary variable and an
1322  * unnecessary copy.
1323  *
1324  * Returns: (transfer none): a floating reference to a new string
1325  *   #GVariant instance
1326  *
1327  * Since: 2.38
1328  **/
1329 GVariant *
1330 g_variant_new_printf (const gchar *format_string,
1331                       ...)
1332 {
1333   GVariant *value;
1334   GBytes *bytes;
1335   gchar *string;
1336   va_list ap;
1337
1338   g_return_val_if_fail (format_string != NULL, NULL);
1339
1340   va_start (ap, format_string);
1341   string = g_strdup_vprintf (format_string, ap);
1342   va_end (ap);
1343
1344   bytes = g_bytes_new_take (string, strlen (string) + 1);
1345   value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1346   g_bytes_unref (bytes);
1347
1348   return value;
1349 }
1350
1351 /**
1352  * g_variant_new_object_path:
1353  * @object_path: a normal C nul-terminated string
1354  *
1355  * Creates a D-Bus object path #GVariant with the contents of @string.
1356  * @string must be a valid D-Bus object path.  Use
1357  * g_variant_is_object_path() if you're not sure.
1358  *
1359  * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1360  *
1361  * Since: 2.24
1362  **/
1363 GVariant *
1364 g_variant_new_object_path (const gchar *object_path)
1365 {
1366   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1367
1368   return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1369                                      object_path, strlen (object_path) + 1);
1370 }
1371
1372 /**
1373  * g_variant_is_object_path:
1374  * @string: a normal C nul-terminated string
1375  *
1376  * Determines if a given string is a valid D-Bus object path.  You
1377  * should ensure that a string is a valid D-Bus object path before
1378  * passing it to g_variant_new_object_path().
1379  *
1380  * A valid object path starts with `/` followed by zero or more
1381  * sequences of characters separated by `/` characters.  Each sequence
1382  * must contain only the characters `[A-Z][a-z][0-9]_`.  No sequence
1383  * (including the one following the final `/` character) may be empty.
1384  *
1385  * Returns: %TRUE if @string is a D-Bus object path
1386  *
1387  * Since: 2.24
1388  **/
1389 gboolean
1390 g_variant_is_object_path (const gchar *string)
1391 {
1392   g_return_val_if_fail (string != NULL, FALSE);
1393
1394   return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1395 }
1396
1397 /**
1398  * g_variant_new_signature:
1399  * @signature: a normal C nul-terminated string
1400  *
1401  * Creates a D-Bus type signature #GVariant with the contents of
1402  * @string.  @string must be a valid D-Bus type signature.  Use
1403  * g_variant_is_signature() if you're not sure.
1404  *
1405  * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1406  *
1407  * Since: 2.24
1408  **/
1409 GVariant *
1410 g_variant_new_signature (const gchar *signature)
1411 {
1412   g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1413
1414   return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1415                                      signature, strlen (signature) + 1);
1416 }
1417
1418 /**
1419  * g_variant_is_signature:
1420  * @string: a normal C nul-terminated string
1421  *
1422  * Determines if a given string is a valid D-Bus type signature.  You
1423  * should ensure that a string is a valid D-Bus type signature before
1424  * passing it to g_variant_new_signature().
1425  *
1426  * D-Bus type signatures consist of zero or more definite #GVariantType
1427  * strings in sequence.
1428  *
1429  * Returns: %TRUE if @string is a D-Bus type signature
1430  *
1431  * Since: 2.24
1432  **/
1433 gboolean
1434 g_variant_is_signature (const gchar *string)
1435 {
1436   g_return_val_if_fail (string != NULL, FALSE);
1437
1438   return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1439 }
1440
1441 /**
1442  * g_variant_get_string:
1443  * @value: a string #GVariant instance
1444  * @length: (optional) (default 0) (out): a pointer to a #gsize,
1445  *          to store the length
1446  *
1447  * Returns the string value of a #GVariant instance with a string
1448  * type.  This includes the types %G_VARIANT_TYPE_STRING,
1449  * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1450  *
1451  * The string will always be UTF-8 encoded, will never be %NULL, and will never
1452  * contain nul bytes.
1453  *
1454  * If @length is non-%NULL then the length of the string (in bytes) is
1455  * returned there.  For trusted values, this information is already
1456  * known.  Untrusted values will be validated and, if valid, a strlen() will be
1457  * performed. If invalid, a default value will be returned — for
1458  * %G_VARIANT_TYPE_OBJECT_PATH, this is `"/"`, and for other types it is the
1459  * empty string.
1460  *
1461  * It is an error to call this function with a @value of any type
1462  * other than those three.
1463  *
1464  * The return value remains valid as long as @value exists.
1465  *
1466  * Returns: (transfer none): the constant string, UTF-8 encoded
1467  *
1468  * Since: 2.24
1469  **/
1470 const gchar *
1471 g_variant_get_string (GVariant *value,
1472                       gsize    *length)
1473 {
1474   gconstpointer data;
1475   gsize size;
1476
1477   g_return_val_if_fail (value != NULL, NULL);
1478   g_return_val_if_fail (
1479     g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1480     g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1481     g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1482
1483   data = g_variant_get_data (value);
1484   size = g_variant_get_size (value);
1485
1486   if (!g_variant_is_trusted (value))
1487     {
1488       switch (g_variant_classify (value))
1489         {
1490         case G_VARIANT_CLASS_STRING:
1491           if (g_variant_serialiser_is_string (data, size))
1492             break;
1493
1494           data = "";
1495           size = 1;
1496           break;
1497
1498         case G_VARIANT_CLASS_OBJECT_PATH:
1499           if (g_variant_serialiser_is_object_path (data, size))
1500             break;
1501
1502           data = "/";
1503           size = 2;
1504           break;
1505
1506         case G_VARIANT_CLASS_SIGNATURE:
1507           if (g_variant_serialiser_is_signature (data, size))
1508             break;
1509
1510           data = "";
1511           size = 1;
1512           break;
1513
1514         default:
1515           g_assert_not_reached ();
1516         }
1517     }
1518
1519   if (length)
1520     *length = size - 1;
1521
1522   return data;
1523 }
1524
1525 /**
1526  * g_variant_dup_string:
1527  * @value: a string #GVariant instance
1528  * @length: (out): a pointer to a #gsize, to store the length
1529  *
1530  * Similar to g_variant_get_string() except that instead of returning
1531  * a constant string, the string is duplicated.
1532  *
1533  * The string will always be UTF-8 encoded.
1534  *
1535  * The return value must be freed using g_free().
1536  *
1537  * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1538  *
1539  * Since: 2.24
1540  **/
1541 gchar *
1542 g_variant_dup_string (GVariant *value,
1543                       gsize    *length)
1544 {
1545   return g_strdup (g_variant_get_string (value, length));
1546 }
1547
1548 /**
1549  * g_variant_new_strv:
1550  * @strv: (array length=length) (element-type utf8): an array of strings
1551  * @length: the length of @strv, or -1
1552  *
1553  * Constructs an array of strings #GVariant from the given array of
1554  * strings.
1555  *
1556  * If @length is -1 then @strv is %NULL-terminated.
1557  *
1558  * Returns: (transfer none): a new floating #GVariant instance
1559  *
1560  * Since: 2.24
1561  **/
1562 GVariant *
1563 g_variant_new_strv (const gchar * const *strv,
1564                     gssize               length)
1565 {
1566   GVariant **strings;
1567   gsize i, length_unsigned;
1568
1569   g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1570
1571   if (length < 0)
1572     length = g_strv_length ((gchar **) strv);
1573   length_unsigned = length;
1574
1575   strings = g_new (GVariant *, length_unsigned);
1576   for (i = 0; i < length_unsigned; i++)
1577     strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1578
1579   return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1580                                       strings, length_unsigned, TRUE);
1581 }
1582
1583 /**
1584  * g_variant_get_strv:
1585  * @value: an array of strings #GVariant
1586  * @length: (out) (optional): the length of the result, or %NULL
1587  *
1588  * Gets the contents of an array of strings #GVariant.  This call
1589  * makes a shallow copy; the return result should be released with
1590  * g_free(), but the individual strings must not be modified.
1591  *
1592  * If @length is non-%NULL then the number of elements in the result
1593  * is stored there.  In any case, the resulting array will be
1594  * %NULL-terminated.
1595  *
1596  * For an empty array, @length will be set to 0 and a pointer to a
1597  * %NULL pointer will be returned.
1598  *
1599  * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1600  *
1601  * Since: 2.24
1602  **/
1603 const gchar **
1604 g_variant_get_strv (GVariant *value,
1605                     gsize    *length)
1606 {
1607   const gchar **strv;
1608   gsize n;
1609   gsize i;
1610
1611   TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1612
1613   g_variant_get_data (value);
1614   n = g_variant_n_children (value);
1615   strv = g_new (const gchar *, n + 1);
1616
1617   for (i = 0; i < n; i++)
1618     {
1619       GVariant *string;
1620
1621       string = g_variant_get_child_value (value, i);
1622       strv[i] = g_variant_get_string (string, NULL);
1623       g_variant_unref (string);
1624     }
1625   strv[i] = NULL;
1626
1627   if (length)
1628     *length = n;
1629
1630   return strv;
1631 }
1632
1633 /**
1634  * g_variant_dup_strv:
1635  * @value: an array of strings #GVariant
1636  * @length: (out) (optional): the length of the result, or %NULL
1637  *
1638  * Gets the contents of an array of strings #GVariant.  This call
1639  * makes a deep copy; the return result should be released with
1640  * g_strfreev().
1641  *
1642  * If @length is non-%NULL then the number of elements in the result
1643  * is stored there.  In any case, the resulting array will be
1644  * %NULL-terminated.
1645  *
1646  * For an empty array, @length will be set to 0 and a pointer to a
1647  * %NULL pointer will be returned.
1648  *
1649  * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1650  *
1651  * Since: 2.24
1652  **/
1653 gchar **
1654 g_variant_dup_strv (GVariant *value,
1655                     gsize    *length)
1656 {
1657   gchar **strv;
1658   gsize n;
1659   gsize i;
1660
1661   TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1662
1663   n = g_variant_n_children (value);
1664   strv = g_new (gchar *, n + 1);
1665
1666   for (i = 0; i < n; i++)
1667     {
1668       GVariant *string;
1669
1670       string = g_variant_get_child_value (value, i);
1671       strv[i] = g_variant_dup_string (string, NULL);
1672       g_variant_unref (string);
1673     }
1674   strv[i] = NULL;
1675
1676   if (length)
1677     *length = n;
1678
1679   return strv;
1680 }
1681
1682 /**
1683  * g_variant_new_objv:
1684  * @strv: (array length=length) (element-type utf8): an array of strings
1685  * @length: the length of @strv, or -1
1686  *
1687  * Constructs an array of object paths #GVariant from the given array of
1688  * strings.
1689  *
1690  * Each string must be a valid #GVariant object path; see
1691  * g_variant_is_object_path().
1692  *
1693  * If @length is -1 then @strv is %NULL-terminated.
1694  *
1695  * Returns: (transfer none): a new floating #GVariant instance
1696  *
1697  * Since: 2.30
1698  **/
1699 GVariant *
1700 g_variant_new_objv (const gchar * const *strv,
1701                     gssize               length)
1702 {
1703   GVariant **strings;
1704   gsize i, length_unsigned;
1705
1706   g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1707
1708   if (length < 0)
1709     length = g_strv_length ((gchar **) strv);
1710   length_unsigned = length;
1711
1712   strings = g_new (GVariant *, length_unsigned);
1713   for (i = 0; i < length_unsigned; i++)
1714     strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1715
1716   return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1717                                       strings, length_unsigned, TRUE);
1718 }
1719
1720 /**
1721  * g_variant_get_objv:
1722  * @value: an array of object paths #GVariant
1723  * @length: (out) (optional): the length of the result, or %NULL
1724  *
1725  * Gets the contents of an array of object paths #GVariant.  This call
1726  * makes a shallow copy; the return result should be released with
1727  * g_free(), but the individual strings must not be modified.
1728  *
1729  * If @length is non-%NULL then the number of elements in the result
1730  * is stored there.  In any case, the resulting array will be
1731  * %NULL-terminated.
1732  *
1733  * For an empty array, @length will be set to 0 and a pointer to a
1734  * %NULL pointer will be returned.
1735  *
1736  * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1737  *
1738  * Since: 2.30
1739  **/
1740 const gchar **
1741 g_variant_get_objv (GVariant *value,
1742                     gsize    *length)
1743 {
1744   const gchar **strv;
1745   gsize n;
1746   gsize i;
1747
1748   TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1749
1750   g_variant_get_data (value);
1751   n = g_variant_n_children (value);
1752   strv = g_new (const gchar *, n + 1);
1753
1754   for (i = 0; i < n; i++)
1755     {
1756       GVariant *string;
1757
1758       string = g_variant_get_child_value (value, i);
1759       strv[i] = g_variant_get_string (string, NULL);
1760       g_variant_unref (string);
1761     }
1762   strv[i] = NULL;
1763
1764   if (length)
1765     *length = n;
1766
1767   return strv;
1768 }
1769
1770 /**
1771  * g_variant_dup_objv:
1772  * @value: an array of object paths #GVariant
1773  * @length: (out) (optional): the length of the result, or %NULL
1774  *
1775  * Gets the contents of an array of object paths #GVariant.  This call
1776  * makes a deep copy; the return result should be released with
1777  * g_strfreev().
1778  *
1779  * If @length is non-%NULL then the number of elements in the result
1780  * is stored there.  In any case, the resulting array will be
1781  * %NULL-terminated.
1782  *
1783  * For an empty array, @length will be set to 0 and a pointer to a
1784  * %NULL pointer will be returned.
1785  *
1786  * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1787  *
1788  * Since: 2.30
1789  **/
1790 gchar **
1791 g_variant_dup_objv (GVariant *value,
1792                     gsize    *length)
1793 {
1794   gchar **strv;
1795   gsize n;
1796   gsize i;
1797
1798   TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1799
1800   n = g_variant_n_children (value);
1801   strv = g_new (gchar *, n + 1);
1802
1803   for (i = 0; i < n; i++)
1804     {
1805       GVariant *string;
1806
1807       string = g_variant_get_child_value (value, i);
1808       strv[i] = g_variant_dup_string (string, NULL);
1809       g_variant_unref (string);
1810     }
1811   strv[i] = NULL;
1812
1813   if (length)
1814     *length = n;
1815
1816   return strv;
1817 }
1818
1819
1820 /**
1821  * g_variant_new_bytestring:
1822  * @string: (array zero-terminated=1) (element-type guint8): a normal
1823  *          nul-terminated string in no particular encoding
1824  *
1825  * Creates an array-of-bytes #GVariant with the contents of @string.
1826  * This function is just like g_variant_new_string() except that the
1827  * string need not be valid UTF-8.
1828  *
1829  * The nul terminator character at the end of the string is stored in
1830  * the array.
1831  *
1832  * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1833  *
1834  * Since: 2.26
1835  **/
1836 GVariant *
1837 g_variant_new_bytestring (const gchar *string)
1838 {
1839   g_return_val_if_fail (string != NULL, NULL);
1840
1841   return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1842                                      string, strlen (string) + 1);
1843 }
1844
1845 /**
1846  * g_variant_get_bytestring:
1847  * @value: an array-of-bytes #GVariant instance
1848  *
1849  * Returns the string value of a #GVariant instance with an
1850  * array-of-bytes type.  The string has no particular encoding.
1851  *
1852  * If the array does not end with a nul terminator character, the empty
1853  * string is returned.  For this reason, you can always trust that a
1854  * non-%NULL nul-terminated string will be returned by this function.
1855  *
1856  * If the array contains a nul terminator character somewhere other than
1857  * the last byte then the returned string is the string, up to the first
1858  * such nul character.
1859  *
1860  * g_variant_get_fixed_array() should be used instead if the array contains
1861  * arbitrary data that could not be nul-terminated or could contain nul bytes.
1862  *
1863  * It is an error to call this function with a @value that is not an
1864  * array of bytes.
1865  *
1866  * The return value remains valid as long as @value exists.
1867  *
1868  * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1869  *          the constant string
1870  *
1871  * Since: 2.26
1872  **/
1873 const gchar *
1874 g_variant_get_bytestring (GVariant *value)
1875 {
1876   const gchar *string;
1877   gsize size;
1878
1879   TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1880
1881   /* Won't be NULL since this is an array type */
1882   string = g_variant_get_data (value);
1883   size = g_variant_get_size (value);
1884
1885   if (size && string[size - 1] == '\0')
1886     return string;
1887   else
1888     return "";
1889 }
1890
1891 /**
1892  * g_variant_dup_bytestring:
1893  * @value: an array-of-bytes #GVariant instance
1894  * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1895  *          the length (not including the nul terminator)
1896  *
1897  * Similar to g_variant_get_bytestring() except that instead of
1898  * returning a constant string, the string is duplicated.
1899  *
1900  * The return value must be freed using g_free().
1901  *
1902  * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1903  *          a newly allocated string
1904  *
1905  * Since: 2.26
1906  **/
1907 gchar *
1908 g_variant_dup_bytestring (GVariant *value,
1909                           gsize    *length)
1910 {
1911   const gchar *original = g_variant_get_bytestring (value);
1912   gsize size;
1913
1914   /* don't crash in case get_bytestring() had an assert failure */
1915   if (original == NULL)
1916     return NULL;
1917
1918   size = strlen (original);
1919
1920   if (length)
1921     *length = size;
1922
1923   return g_memdup2 (original, size + 1);
1924 }
1925
1926 /**
1927  * g_variant_new_bytestring_array:
1928  * @strv: (array length=length): an array of strings
1929  * @length: the length of @strv, or -1
1930  *
1931  * Constructs an array of bytestring #GVariant from the given array of
1932  * strings.
1933  *
1934  * If @length is -1 then @strv is %NULL-terminated.
1935  *
1936  * Returns: (transfer none): a new floating #GVariant instance
1937  *
1938  * Since: 2.26
1939  **/
1940 GVariant *
1941 g_variant_new_bytestring_array (const gchar * const *strv,
1942                                 gssize               length)
1943 {
1944   GVariant **strings;
1945   gsize i, length_unsigned;
1946
1947   g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1948
1949   if (length < 0)
1950     length = g_strv_length ((gchar **) strv);
1951   length_unsigned = length;
1952
1953   strings = g_new (GVariant *, length_unsigned);
1954   for (i = 0; i < length_unsigned; i++)
1955     strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1956
1957   return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1958                                       strings, length_unsigned, TRUE);
1959 }
1960
1961 /**
1962  * g_variant_get_bytestring_array:
1963  * @value: an array of array of bytes #GVariant ('aay')
1964  * @length: (out) (optional): the length of the result, or %NULL
1965  *
1966  * Gets the contents of an array of array of bytes #GVariant.  This call
1967  * makes a shallow copy; the return result should be released with
1968  * g_free(), but the individual strings must not be modified.
1969  *
1970  * If @length is non-%NULL then the number of elements in the result is
1971  * stored there.  In any case, the resulting array will be
1972  * %NULL-terminated.
1973  *
1974  * For an empty array, @length will be set to 0 and a pointer to a
1975  * %NULL pointer will be returned.
1976  *
1977  * Returns: (array length=length) (transfer container): an array of constant strings
1978  *
1979  * Since: 2.26
1980  **/
1981 const gchar **
1982 g_variant_get_bytestring_array (GVariant *value,
1983                                 gsize    *length)
1984 {
1985   const gchar **strv;
1986   gsize n;
1987   gsize i;
1988
1989   TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1990
1991   g_variant_get_data (value);
1992   n = g_variant_n_children (value);
1993   strv = g_new (const gchar *, n + 1);
1994
1995   for (i = 0; i < n; i++)
1996     {
1997       GVariant *string;
1998
1999       string = g_variant_get_child_value (value, i);
2000       strv[i] = g_variant_get_bytestring (string);
2001       g_variant_unref (string);
2002     }
2003   strv[i] = NULL;
2004
2005   if (length)
2006     *length = n;
2007
2008   return strv;
2009 }
2010
2011 /**
2012  * g_variant_dup_bytestring_array:
2013  * @value: an array of array of bytes #GVariant ('aay')
2014  * @length: (out) (optional): the length of the result, or %NULL
2015  *
2016  * Gets the contents of an array of array of bytes #GVariant.  This call
2017  * makes a deep copy; the return result should be released with
2018  * g_strfreev().
2019  *
2020  * If @length is non-%NULL then the number of elements in the result is
2021  * stored there.  In any case, the resulting array will be
2022  * %NULL-terminated.
2023  *
2024  * For an empty array, @length will be set to 0 and a pointer to a
2025  * %NULL pointer will be returned.
2026  *
2027  * Returns: (array length=length) (transfer full): an array of strings
2028  *
2029  * Since: 2.26
2030  **/
2031 gchar **
2032 g_variant_dup_bytestring_array (GVariant *value,
2033                                 gsize    *length)
2034 {
2035   gchar **strv;
2036   gsize n;
2037   gsize i;
2038
2039   TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2040
2041   g_variant_get_data (value);
2042   n = g_variant_n_children (value);
2043   strv = g_new (gchar *, n + 1);
2044
2045   for (i = 0; i < n; i++)
2046     {
2047       GVariant *string;
2048
2049       string = g_variant_get_child_value (value, i);
2050       strv[i] = g_variant_dup_bytestring (string, NULL);
2051       g_variant_unref (string);
2052     }
2053   strv[i] = NULL;
2054
2055   if (length)
2056     *length = n;
2057
2058   return strv;
2059 }
2060
2061 /* Type checking and querying {{{1 */
2062 /**
2063  * g_variant_get_type:
2064  * @value: a #GVariant
2065  *
2066  * Determines the type of @value.
2067  *
2068  * The return value is valid for the lifetime of @value and must not
2069  * be freed.
2070  *
2071  * Returns: a #GVariantType
2072  *
2073  * Since: 2.24
2074  **/
2075 const GVariantType *
2076 g_variant_get_type (GVariant *value)
2077 {
2078   GVariantTypeInfo *type_info;
2079
2080   g_return_val_if_fail (value != NULL, NULL);
2081
2082   type_info = g_variant_get_type_info (value);
2083
2084   return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2085 }
2086
2087 /**
2088  * g_variant_get_type_string:
2089  * @value: a #GVariant
2090  *
2091  * Returns the type string of @value.  Unlike the result of calling
2092  * g_variant_type_peek_string(), this string is nul-terminated.  This
2093  * string belongs to #GVariant and must not be freed.
2094  *
2095  * Returns: the type string for the type of @value
2096  *
2097  * Since: 2.24
2098  **/
2099 const gchar *
2100 g_variant_get_type_string (GVariant *value)
2101 {
2102   GVariantTypeInfo *type_info;
2103
2104   g_return_val_if_fail (value != NULL, NULL);
2105
2106   type_info = g_variant_get_type_info (value);
2107
2108   return g_variant_type_info_get_type_string (type_info);
2109 }
2110
2111 /**
2112  * g_variant_is_of_type:
2113  * @value: a #GVariant instance
2114  * @type: a #GVariantType
2115  *
2116  * Checks if a value has a type matching the provided type.
2117  *
2118  * Returns: %TRUE if the type of @value matches @type
2119  *
2120  * Since: 2.24
2121  **/
2122 gboolean
2123 g_variant_is_of_type (GVariant           *value,
2124                       const GVariantType *type)
2125 {
2126   return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2127 }
2128
2129 /**
2130  * g_variant_is_container:
2131  * @value: a #GVariant instance
2132  *
2133  * Checks if @value is a container.
2134  *
2135  * Returns: %TRUE if @value is a container
2136  *
2137  * Since: 2.24
2138  */
2139 gboolean
2140 g_variant_is_container (GVariant *value)
2141 {
2142   return g_variant_type_is_container (g_variant_get_type (value));
2143 }
2144
2145
2146 /**
2147  * g_variant_classify:
2148  * @value: a #GVariant
2149  *
2150  * Classifies @value according to its top-level type.
2151  *
2152  * Returns: the #GVariantClass of @value
2153  *
2154  * Since: 2.24
2155  **/
2156 /**
2157  * GVariantClass:
2158  * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2159  * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2160  * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2161  * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2162  * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2163  * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2164  * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2165  * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2166  * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2167  * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating 
2168  *                          point value.
2169  * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2170  * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path 
2171  *                               string.
2172  * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2173  * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2174  * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2175  * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2176  * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2177  * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2178  *
2179  * The range of possible top-level types of #GVariant instances.
2180  *
2181  * Since: 2.24
2182  **/
2183 GVariantClass
2184 g_variant_classify (GVariant *value)
2185 {
2186   g_return_val_if_fail (value != NULL, 0);
2187
2188   return *g_variant_get_type_string (value);
2189 }
2190
2191 /* Pretty printer {{{1 */
2192 /* This function is not introspectable because if @string is NULL,
2193    @returns is (transfer full), otherwise it is (transfer none), which
2194    is not supported by GObjectIntrospection */
2195 /**
2196  * g_variant_print_string: (skip)
2197  * @value: a #GVariant
2198  * @string: (nullable) (default NULL): a #GString, or %NULL
2199  * @type_annotate: %TRUE if type information should be included in
2200  *                 the output
2201  *
2202  * Behaves as g_variant_print(), but operates on a #GString.
2203  *
2204  * If @string is non-%NULL then it is appended to and returned.  Else,
2205  * a new empty #GString is allocated and it is returned.
2206  *
2207  * Returns: a #GString containing the string
2208  *
2209  * Since: 2.24
2210  **/
2211 GString *
2212 g_variant_print_string (GVariant *value,
2213                         GString  *string,
2214                         gboolean  type_annotate)
2215 {
2216   if G_UNLIKELY (string == NULL)
2217     string = g_string_new (NULL);
2218
2219   switch (g_variant_classify (value))
2220     {
2221     case G_VARIANT_CLASS_MAYBE:
2222       if (type_annotate)
2223         g_string_append_printf (string, "@%s ",
2224                                 g_variant_get_type_string (value));
2225
2226       if (g_variant_n_children (value))
2227         {
2228           gchar *printed_child;
2229           GVariant *element;
2230
2231           /* Nested maybes:
2232            *
2233            * Consider the case of the type "mmi".  In this case we could
2234            * write "just just 4", but "4" alone is totally unambiguous,
2235            * so we try to drop "just" where possible.
2236            *
2237            * We have to be careful not to always drop "just", though,
2238            * since "nothing" needs to be distinguishable from "just
2239            * nothing".  The case where we need to ensure we keep the
2240            * "just" is actually exactly the case where we have a nested
2241            * Nothing.
2242            *
2243            * Instead of searching for that nested Nothing, we just print
2244            * the contained value into a separate string and see if we
2245            * end up with "nothing" at the end of it.  If so, we need to
2246            * add "just" at our level.
2247            */
2248           element = g_variant_get_child_value (value, 0);
2249           printed_child = g_variant_print (element, FALSE);
2250           g_variant_unref (element);
2251
2252           if (g_str_has_suffix (printed_child, "nothing"))
2253             g_string_append (string, "just ");
2254           g_string_append (string, printed_child);
2255           g_free (printed_child);
2256         }
2257       else
2258         g_string_append (string, "nothing");
2259
2260       break;
2261
2262     case G_VARIANT_CLASS_ARRAY:
2263       /* it's an array so the first character of the type string is 'a'
2264        *
2265        * if the first two characters are 'ay' then it's a bytestring.
2266        * under certain conditions we print those as strings.
2267        */
2268       if (g_variant_get_type_string (value)[1] == 'y')
2269         {
2270           const gchar *str;
2271           gsize size;
2272           gsize i;
2273
2274           /* first determine if it is a byte string.
2275            * that's when there's a single nul character: at the end.
2276            */
2277           str = g_variant_get_data (value);
2278           size = g_variant_get_size (value);
2279
2280           for (i = 0; i < size; i++)
2281             if (str[i] == '\0')
2282               break;
2283
2284           /* first nul byte is the last byte -> it's a byte string. */
2285           if (i == size - 1)
2286             {
2287               gchar *escaped = g_strescape (str, NULL);
2288
2289               /* use double quotes only if a ' is in the string */
2290               if (strchr (str, '\''))
2291                 g_string_append_printf (string, "b\"%s\"", escaped);
2292               else
2293                 g_string_append_printf (string, "b'%s'", escaped);
2294
2295               g_free (escaped);
2296               break;
2297             }
2298
2299           else
2300             {
2301               /* fall through and handle normally... */
2302             }
2303         }
2304
2305       /*
2306        * if the first two characters are 'a{' then it's an array of
2307        * dictionary entries (ie: a dictionary) so we print that
2308        * differently.
2309        */
2310       if (g_variant_get_type_string (value)[1] == '{')
2311         /* dictionary */
2312         {
2313           const gchar *comma = "";
2314           gsize n, i;
2315
2316           if ((n = g_variant_n_children (value)) == 0)
2317             {
2318               if (type_annotate)
2319                 g_string_append_printf (string, "@%s ",
2320                                         g_variant_get_type_string (value));
2321               g_string_append (string, "{}");
2322               break;
2323             }
2324
2325           g_string_append_c (string, '{');
2326           for (i = 0; i < n; i++)
2327             {
2328               GVariant *entry, *key, *val;
2329
2330               g_string_append (string, comma);
2331               comma = ", ";
2332
2333               entry = g_variant_get_child_value (value, i);
2334               key = g_variant_get_child_value (entry, 0);
2335               val = g_variant_get_child_value (entry, 1);
2336               g_variant_unref (entry);
2337
2338               g_variant_print_string (key, string, type_annotate);
2339               g_variant_unref (key);
2340               g_string_append (string, ": ");
2341               g_variant_print_string (val, string, type_annotate);
2342               g_variant_unref (val);
2343               type_annotate = FALSE;
2344             }
2345           g_string_append_c (string, '}');
2346         }
2347       else
2348         /* normal (non-dictionary) array */
2349         {
2350           const gchar *comma = "";
2351           gsize n, i;
2352
2353           if ((n = g_variant_n_children (value)) == 0)
2354             {
2355               if (type_annotate)
2356                 g_string_append_printf (string, "@%s ",
2357                                         g_variant_get_type_string (value));
2358               g_string_append (string, "[]");
2359               break;
2360             }
2361
2362           g_string_append_c (string, '[');
2363           for (i = 0; i < n; i++)
2364             {
2365               GVariant *element;
2366
2367               g_string_append (string, comma);
2368               comma = ", ";
2369
2370               element = g_variant_get_child_value (value, i);
2371
2372               g_variant_print_string (element, string, type_annotate);
2373               g_variant_unref (element);
2374               type_annotate = FALSE;
2375             }
2376           g_string_append_c (string, ']');
2377         }
2378
2379       break;
2380
2381     case G_VARIANT_CLASS_TUPLE:
2382       {
2383         gsize n, i;
2384
2385         n = g_variant_n_children (value);
2386
2387         g_string_append_c (string, '(');
2388         for (i = 0; i < n; i++)
2389           {
2390             GVariant *element;
2391
2392             element = g_variant_get_child_value (value, i);
2393             g_variant_print_string (element, string, type_annotate);
2394             g_string_append (string, ", ");
2395             g_variant_unref (element);
2396           }
2397
2398         /* for >1 item:  remove final ", "
2399          * for 1 item:   remove final " ", but leave the ","
2400          * for 0 items:  there is only "(", so remove nothing
2401          */
2402         g_string_truncate (string, string->len - (n > 0) - (n > 1));
2403         g_string_append_c (string, ')');
2404       }
2405       break;
2406
2407     case G_VARIANT_CLASS_DICT_ENTRY:
2408       {
2409         GVariant *element;
2410
2411         g_string_append_c (string, '{');
2412
2413         element = g_variant_get_child_value (value, 0);
2414         g_variant_print_string (element, string, type_annotate);
2415         g_variant_unref (element);
2416
2417         g_string_append (string, ", ");
2418
2419         element = g_variant_get_child_value (value, 1);
2420         g_variant_print_string (element, string, type_annotate);
2421         g_variant_unref (element);
2422
2423         g_string_append_c (string, '}');
2424       }
2425       break;
2426
2427     case G_VARIANT_CLASS_VARIANT:
2428       {
2429         GVariant *child = g_variant_get_variant (value);
2430
2431         /* Always annotate types in nested variants, because they are
2432          * (by nature) of variable type.
2433          */
2434         g_string_append_c (string, '<');
2435         g_variant_print_string (child, string, TRUE);
2436         g_string_append_c (string, '>');
2437
2438         g_variant_unref (child);
2439       }
2440       break;
2441
2442     case G_VARIANT_CLASS_BOOLEAN:
2443       if (g_variant_get_boolean (value))
2444         g_string_append (string, "true");
2445       else
2446         g_string_append (string, "false");
2447       break;
2448
2449     case G_VARIANT_CLASS_STRING:
2450       {
2451         const gchar *str = g_variant_get_string (value, NULL);
2452         gunichar quote = strchr (str, '\'') ? '"' : '\'';
2453
2454         g_string_append_c (string, quote);
2455
2456         while (*str)
2457           {
2458             gunichar c = g_utf8_get_char (str);
2459
2460             if (c == quote || c == '\\')
2461               g_string_append_c (string, '\\');
2462
2463             if (g_unichar_isprint (c))
2464               g_string_append_unichar (string, c);
2465
2466             else
2467               {
2468                 g_string_append_c (string, '\\');
2469                 if (c < 0x10000)
2470                   switch (c)
2471                     {
2472                     case '\a':
2473                       g_string_append_c (string, 'a');
2474                       break;
2475
2476                     case '\b':
2477                       g_string_append_c (string, 'b');
2478                       break;
2479
2480                     case '\f':
2481                       g_string_append_c (string, 'f');
2482                       break;
2483
2484                     case '\n':
2485                       g_string_append_c (string, 'n');
2486                       break;
2487
2488                     case '\r':
2489                       g_string_append_c (string, 'r');
2490                       break;
2491
2492                     case '\t':
2493                       g_string_append_c (string, 't');
2494                       break;
2495
2496                     case '\v':
2497                       g_string_append_c (string, 'v');
2498                       break;
2499
2500                     default:
2501                       g_string_append_printf (string, "u%04x", c);
2502                       break;
2503                     }
2504                  else
2505                    g_string_append_printf (string, "U%08x", c);
2506               }
2507
2508             str = g_utf8_next_char (str);
2509           }
2510
2511         g_string_append_c (string, quote);
2512       }
2513       break;
2514
2515     case G_VARIANT_CLASS_BYTE:
2516       if (type_annotate)
2517         g_string_append (string, "byte ");
2518       g_string_append_printf (string, "0x%02x",
2519                               g_variant_get_byte (value));
2520       break;
2521
2522     case G_VARIANT_CLASS_INT16:
2523       if (type_annotate)
2524         g_string_append (string, "int16 ");
2525       g_string_append_printf (string, "%"G_GINT16_FORMAT,
2526                               g_variant_get_int16 (value));
2527       break;
2528
2529     case G_VARIANT_CLASS_UINT16:
2530       if (type_annotate)
2531         g_string_append (string, "uint16 ");
2532       g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2533                               g_variant_get_uint16 (value));
2534       break;
2535
2536     case G_VARIANT_CLASS_INT32:
2537       /* Never annotate this type because it is the default for numbers
2538        * (and this is a *pretty* printer)
2539        */
2540       g_string_append_printf (string, "%"G_GINT32_FORMAT,
2541                               g_variant_get_int32 (value));
2542       break;
2543
2544     case G_VARIANT_CLASS_HANDLE:
2545       if (type_annotate)
2546         g_string_append (string, "handle ");
2547       g_string_append_printf (string, "%"G_GINT32_FORMAT,
2548                               g_variant_get_handle (value));
2549       break;
2550
2551     case G_VARIANT_CLASS_UINT32:
2552       if (type_annotate)
2553         g_string_append (string, "uint32 ");
2554       g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2555                               g_variant_get_uint32 (value));
2556       break;
2557
2558     case G_VARIANT_CLASS_INT64:
2559       if (type_annotate)
2560         g_string_append (string, "int64 ");
2561       g_string_append_printf (string, "%"G_GINT64_FORMAT,
2562                               g_variant_get_int64 (value));
2563       break;
2564
2565     case G_VARIANT_CLASS_UINT64:
2566       if (type_annotate)
2567         g_string_append (string, "uint64 ");
2568       g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2569                               g_variant_get_uint64 (value));
2570       break;
2571
2572     case G_VARIANT_CLASS_DOUBLE:
2573       {
2574         gchar buffer[100];
2575         gint i;
2576
2577         g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2578
2579         for (i = 0; buffer[i]; i++)
2580           if (buffer[i] == '.' || buffer[i] == 'e' ||
2581               buffer[i] == 'n' || buffer[i] == 'N')
2582             break;
2583
2584         /* if there is no '.' or 'e' in the float then add one */
2585         if (buffer[i] == '\0')
2586           {
2587             buffer[i++] = '.';
2588             buffer[i++] = '0';
2589             buffer[i++] = '\0';
2590           }
2591
2592         g_string_append (string, buffer);
2593       }
2594       break;
2595
2596     case G_VARIANT_CLASS_OBJECT_PATH:
2597       if (type_annotate)
2598         g_string_append (string, "objectpath ");
2599       g_string_append_printf (string, "\'%s\'",
2600                               g_variant_get_string (value, NULL));
2601       break;
2602
2603     case G_VARIANT_CLASS_SIGNATURE:
2604       if (type_annotate)
2605         g_string_append (string, "signature ");
2606       g_string_append_printf (string, "\'%s\'",
2607                               g_variant_get_string (value, NULL));
2608       break;
2609
2610     default:
2611       g_assert_not_reached ();
2612   }
2613
2614   return string;
2615 }
2616
2617 /**
2618  * g_variant_print:
2619  * @value: a #GVariant
2620  * @type_annotate: %TRUE if type information should be included in
2621  *                 the output
2622  *
2623  * Pretty-prints @value in the format understood by g_variant_parse().
2624  *
2625  * The format is described [here][gvariant-text].
2626  *
2627  * If @type_annotate is %TRUE, then type information is included in
2628  * the output.
2629  *
2630  * Returns: (transfer full): a newly-allocated string holding the result.
2631  *
2632  * Since: 2.24
2633  */
2634 gchar *
2635 g_variant_print (GVariant *value,
2636                  gboolean  type_annotate)
2637 {
2638   return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2639                         FALSE);
2640 }
2641
2642 /* Hash, Equal, Compare {{{1 */
2643 /**
2644  * g_variant_hash:
2645  * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2646  *
2647  * Generates a hash value for a #GVariant instance.
2648  *
2649  * The output of this function is guaranteed to be the same for a given
2650  * value only per-process.  It may change between different processor
2651  * architectures or even different versions of GLib.  Do not use this
2652  * function as a basis for building protocols or file formats.
2653  *
2654  * The type of @value is #gconstpointer only to allow use of this
2655  * function with #GHashTable.  @value must be a #GVariant.
2656  *
2657  * Returns: a hash value corresponding to @value
2658  *
2659  * Since: 2.24
2660  **/
2661 guint
2662 g_variant_hash (gconstpointer value_)
2663 {
2664   GVariant *value = (GVariant *) value_;
2665
2666   switch (g_variant_classify (value))
2667     {
2668     case G_VARIANT_CLASS_STRING:
2669     case G_VARIANT_CLASS_OBJECT_PATH:
2670     case G_VARIANT_CLASS_SIGNATURE:
2671       return g_str_hash (g_variant_get_string (value, NULL));
2672
2673     case G_VARIANT_CLASS_BOOLEAN:
2674       /* this is a very odd thing to hash... */
2675       return g_variant_get_boolean (value);
2676
2677     case G_VARIANT_CLASS_BYTE:
2678       return g_variant_get_byte (value);
2679
2680     case G_VARIANT_CLASS_INT16:
2681     case G_VARIANT_CLASS_UINT16:
2682       {
2683         const guint16 *ptr;
2684
2685         ptr = g_variant_get_data (value);
2686
2687         if (ptr)
2688           return *ptr;
2689         else
2690           return 0;
2691       }
2692
2693     case G_VARIANT_CLASS_INT32:
2694     case G_VARIANT_CLASS_UINT32:
2695     case G_VARIANT_CLASS_HANDLE:
2696       {
2697         const guint *ptr;
2698
2699         ptr = g_variant_get_data (value);
2700
2701         if (ptr)
2702           return *ptr;
2703         else
2704           return 0;
2705       }
2706
2707     case G_VARIANT_CLASS_INT64:
2708     case G_VARIANT_CLASS_UINT64:
2709     case G_VARIANT_CLASS_DOUBLE:
2710       /* need a separate case for these guys because otherwise
2711        * performance could be quite bad on big endian systems
2712        */
2713       {
2714         const guint *ptr;
2715
2716         ptr = g_variant_get_data (value);
2717
2718         if (ptr)
2719           return ptr[0] + ptr[1];
2720         else
2721           return 0;
2722       }
2723
2724     default:
2725       g_return_val_if_fail (!g_variant_is_container (value), 0);
2726       g_assert_not_reached ();
2727     }
2728 }
2729
2730 /**
2731  * g_variant_equal:
2732  * @one: (type GVariant): a #GVariant instance
2733  * @two: (type GVariant): a #GVariant instance
2734  *
2735  * Checks if @one and @two have the same type and value.
2736  *
2737  * The types of @one and @two are #gconstpointer only to allow use of
2738  * this function with #GHashTable.  They must each be a #GVariant.
2739  *
2740  * Returns: %TRUE if @one and @two are equal
2741  *
2742  * Since: 2.24
2743  **/
2744 gboolean
2745 g_variant_equal (gconstpointer one,
2746                  gconstpointer two)
2747 {
2748   gboolean equal;
2749
2750   g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2751
2752   if (g_variant_get_type_info ((GVariant *) one) !=
2753       g_variant_get_type_info ((GVariant *) two))
2754     return FALSE;
2755
2756   /* if both values are trusted to be in their canonical serialized form
2757    * then a simple memcmp() of their serialized data will answer the
2758    * question.
2759    *
2760    * if not, then this might generate a false negative (since it is
2761    * possible for two different byte sequences to represent the same
2762    * value).  for now we solve this by pretty-printing both values and
2763    * comparing the result.
2764    */
2765   if (g_variant_is_trusted ((GVariant *) one) &&
2766       g_variant_is_trusted ((GVariant *) two))
2767     {
2768       gconstpointer data_one, data_two;
2769       gsize size_one, size_two;
2770
2771       size_one = g_variant_get_size ((GVariant *) one);
2772       size_two = g_variant_get_size ((GVariant *) two);
2773
2774       if (size_one != size_two)
2775         return FALSE;
2776
2777       data_one = g_variant_get_data ((GVariant *) one);
2778       data_two = g_variant_get_data ((GVariant *) two);
2779
2780       if (size_one)
2781         equal = memcmp (data_one, data_two, size_one) == 0;
2782       else
2783         equal = TRUE;
2784     }
2785   else
2786     {
2787       gchar *strone, *strtwo;
2788
2789       strone = g_variant_print ((GVariant *) one, FALSE);
2790       strtwo = g_variant_print ((GVariant *) two, FALSE);
2791       equal = strcmp (strone, strtwo) == 0;
2792       g_free (strone);
2793       g_free (strtwo);
2794     }
2795
2796   return equal;
2797 }
2798
2799 /**
2800  * g_variant_compare:
2801  * @one: (type GVariant): a basic-typed #GVariant instance
2802  * @two: (type GVariant): a #GVariant instance of the same type
2803  *
2804  * Compares @one and @two.
2805  *
2806  * The types of @one and @two are #gconstpointer only to allow use of
2807  * this function with #GTree, #GPtrArray, etc.  They must each be a
2808  * #GVariant.
2809  *
2810  * Comparison is only defined for basic types (ie: booleans, numbers,
2811  * strings).  For booleans, %FALSE is less than %TRUE.  Numbers are
2812  * ordered in the usual way.  Strings are in ASCII lexographical order.
2813  *
2814  * It is a programmer error to attempt to compare container values or
2815  * two values that have types that are not exactly equal.  For example,
2816  * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2817  * integer.  Also note that this function is not particularly
2818  * well-behaved when it comes to comparison of doubles; in particular,
2819  * the handling of incomparable values (ie: NaN) is undefined.
2820  *
2821  * If you only require an equality comparison, g_variant_equal() is more
2822  * general.
2823  *
2824  * Returns: negative value if a < b;
2825  *          zero if a = b;
2826  *          positive value if a > b.
2827  *
2828  * Since: 2.26
2829  **/
2830 gint
2831 g_variant_compare (gconstpointer one,
2832                    gconstpointer two)
2833 {
2834   GVariant *a = (GVariant *) one;
2835   GVariant *b = (GVariant *) two;
2836
2837   g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2838
2839   switch (g_variant_classify (a))
2840     {
2841     case G_VARIANT_CLASS_BOOLEAN:
2842       return g_variant_get_boolean (a) -
2843              g_variant_get_boolean (b);
2844
2845     case G_VARIANT_CLASS_BYTE:
2846       return ((gint) g_variant_get_byte (a)) -
2847              ((gint) g_variant_get_byte (b));
2848
2849     case G_VARIANT_CLASS_INT16:
2850       return ((gint) g_variant_get_int16 (a)) -
2851              ((gint) g_variant_get_int16 (b));
2852
2853     case G_VARIANT_CLASS_UINT16:
2854       return ((gint) g_variant_get_uint16 (a)) -
2855              ((gint) g_variant_get_uint16 (b));
2856
2857     case G_VARIANT_CLASS_INT32:
2858       {
2859         gint32 a_val = g_variant_get_int32 (a);
2860         gint32 b_val = g_variant_get_int32 (b);
2861
2862         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2863       }
2864
2865     case G_VARIANT_CLASS_UINT32:
2866       {
2867         guint32 a_val = g_variant_get_uint32 (a);
2868         guint32 b_val = g_variant_get_uint32 (b);
2869
2870         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2871       }
2872
2873     case G_VARIANT_CLASS_INT64:
2874       {
2875         gint64 a_val = g_variant_get_int64 (a);
2876         gint64 b_val = g_variant_get_int64 (b);
2877
2878         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2879       }
2880
2881     case G_VARIANT_CLASS_UINT64:
2882       {
2883         guint64 a_val = g_variant_get_uint64 (a);
2884         guint64 b_val = g_variant_get_uint64 (b);
2885
2886         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2887       }
2888
2889     case G_VARIANT_CLASS_DOUBLE:
2890       {
2891         gdouble a_val = g_variant_get_double (a);
2892         gdouble b_val = g_variant_get_double (b);
2893
2894         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2895       }
2896
2897     case G_VARIANT_CLASS_STRING:
2898     case G_VARIANT_CLASS_OBJECT_PATH:
2899     case G_VARIANT_CLASS_SIGNATURE:
2900       return strcmp (g_variant_get_string (a, NULL),
2901                      g_variant_get_string (b, NULL));
2902
2903     default:
2904       g_return_val_if_fail (!g_variant_is_container (a), 0);
2905       g_assert_not_reached ();
2906     }
2907 }
2908
2909 /* GVariantIter {{{1 */
2910 /**
2911  * GVariantIter: (skip)
2912  *
2913  * #GVariantIter is an opaque data structure and can only be accessed
2914  * using the following functions.
2915  **/
2916 struct stack_iter
2917 {
2918   GVariant *value;
2919   gssize n, i;
2920
2921   const gchar *loop_format;
2922
2923   gsize padding[3];
2924   gsize magic;
2925 };
2926
2927 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2928
2929 struct heap_iter
2930 {
2931   struct stack_iter iter;
2932
2933   GVariant *value_ref;
2934   gsize magic;
2935 };
2936
2937 #define GVSI(i)                 ((struct stack_iter *) (i))
2938 #define GVHI(i)                 ((struct heap_iter *) (i))
2939 #define GVSI_MAGIC              ((gsize) 3579507750u)
2940 #define GVHI_MAGIC              ((gsize) 1450270775u)
2941 #define is_valid_iter(i)        (i != NULL && \
2942                                  GVSI(i)->magic == GVSI_MAGIC)
2943 #define is_valid_heap_iter(i)   (is_valid_iter(i) && \
2944                                  GVHI(i)->magic == GVHI_MAGIC)
2945
2946 /**
2947  * g_variant_iter_new:
2948  * @value: a container #GVariant
2949  *
2950  * Creates a heap-allocated #GVariantIter for iterating over the items
2951  * in @value.
2952  *
2953  * Use g_variant_iter_free() to free the return value when you no longer
2954  * need it.
2955  *
2956  * A reference is taken to @value and will be released only when
2957  * g_variant_iter_free() is called.
2958  *
2959  * Returns: (transfer full): a new heap-allocated #GVariantIter
2960  *
2961  * Since: 2.24
2962  **/
2963 GVariantIter *
2964 g_variant_iter_new (GVariant *value)
2965 {
2966   GVariantIter *iter;
2967
2968   iter = (GVariantIter *) g_slice_new (struct heap_iter);
2969   GVHI(iter)->value_ref = g_variant_ref (value);
2970   GVHI(iter)->magic = GVHI_MAGIC;
2971
2972   g_variant_iter_init (iter, value);
2973
2974   return iter;
2975 }
2976
2977 /**
2978  * g_variant_iter_init: (skip)
2979  * @iter: a pointer to a #GVariantIter
2980  * @value: a container #GVariant
2981  *
2982  * Initialises (without allocating) a #GVariantIter.  @iter may be
2983  * completely uninitialised prior to this call; its old value is
2984  * ignored.
2985  *
2986  * The iterator remains valid for as long as @value exists, and need not
2987  * be freed in any way.
2988  *
2989  * Returns: the number of items in @value
2990  *
2991  * Since: 2.24
2992  **/
2993 gsize
2994 g_variant_iter_init (GVariantIter *iter,
2995                      GVariant     *value)
2996 {
2997   GVSI(iter)->magic = GVSI_MAGIC;
2998   GVSI(iter)->value = value;
2999   GVSI(iter)->n = g_variant_n_children (value);
3000   GVSI(iter)->i = -1;
3001   GVSI(iter)->loop_format = NULL;
3002
3003   return GVSI(iter)->n;
3004 }
3005
3006 /**
3007  * g_variant_iter_copy:
3008  * @iter: a #GVariantIter
3009  *
3010  * Creates a new heap-allocated #GVariantIter to iterate over the
3011  * container that was being iterated over by @iter.  Iteration begins on
3012  * the new iterator from the current position of the old iterator but
3013  * the two copies are independent past that point.
3014  *
3015  * Use g_variant_iter_free() to free the return value when you no longer
3016  * need it.
3017  *
3018  * A reference is taken to the container that @iter is iterating over
3019  * and will be related only when g_variant_iter_free() is called.
3020  *
3021  * Returns: (transfer full): a new heap-allocated #GVariantIter
3022  *
3023  * Since: 2.24
3024  **/
3025 GVariantIter *
3026 g_variant_iter_copy (GVariantIter *iter)
3027 {
3028   GVariantIter *copy;
3029
3030   g_return_val_if_fail (is_valid_iter (iter), 0);
3031
3032   copy = g_variant_iter_new (GVSI(iter)->value);
3033   GVSI(copy)->i = GVSI(iter)->i;
3034
3035   return copy;
3036 }
3037
3038 /**
3039  * g_variant_iter_n_children:
3040  * @iter: a #GVariantIter
3041  *
3042  * Queries the number of child items in the container that we are
3043  * iterating over.  This is the total number of items -- not the number
3044  * of items remaining.
3045  *
3046  * This function might be useful for preallocation of arrays.
3047  *
3048  * Returns: the number of children in the container
3049  *
3050  * Since: 2.24
3051  **/
3052 gsize
3053 g_variant_iter_n_children (GVariantIter *iter)
3054 {
3055   g_return_val_if_fail (is_valid_iter (iter), 0);
3056
3057   return GVSI(iter)->n;
3058 }
3059
3060 /**
3061  * g_variant_iter_free:
3062  * @iter: (transfer full): a heap-allocated #GVariantIter
3063  *
3064  * Frees a heap-allocated #GVariantIter.  Only call this function on
3065  * iterators that were returned by g_variant_iter_new() or
3066  * g_variant_iter_copy().
3067  *
3068  * Since: 2.24
3069  **/
3070 void
3071 g_variant_iter_free (GVariantIter *iter)
3072 {
3073   g_return_if_fail (is_valid_heap_iter (iter));
3074
3075   g_variant_unref (GVHI(iter)->value_ref);
3076   GVHI(iter)->magic = 0;
3077
3078   g_slice_free (struct heap_iter, GVHI(iter));
3079 }
3080
3081 /**
3082  * g_variant_iter_next_value:
3083  * @iter: a #GVariantIter
3084  *
3085  * Gets the next item in the container.  If no more items remain then
3086  * %NULL is returned.
3087  *
3088  * Use g_variant_unref() to drop your reference on the return value when
3089  * you no longer need it.
3090  *
3091  * Here is an example for iterating with g_variant_iter_next_value():
3092  * |[<!-- language="C" --> 
3093  *   // recursively iterate a container
3094  *   void
3095  *   iterate_container_recursive (GVariant *container)
3096  *   {
3097  *     GVariantIter iter;
3098  *     GVariant *child;
3099  *
3100  *     g_variant_iter_init (&iter, container);
3101  *     while ((child = g_variant_iter_next_value (&iter)))
3102  *       {
3103  *         g_print ("type '%s'\n", g_variant_get_type_string (child));
3104  *
3105  *         if (g_variant_is_container (child))
3106  *           iterate_container_recursive (child);
3107  *
3108  *         g_variant_unref (child);
3109  *       }
3110  *   }
3111  * ]|
3112  *
3113  * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3114  *
3115  * Since: 2.24
3116  **/
3117 GVariant *
3118 g_variant_iter_next_value (GVariantIter *iter)
3119 {
3120   g_return_val_if_fail (is_valid_iter (iter), FALSE);
3121
3122   if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3123     {
3124       g_critical ("g_variant_iter_next_value: must not be called again "
3125                   "after NULL has already been returned.");
3126       return NULL;
3127     }
3128
3129   GVSI(iter)->i++;
3130
3131   if (GVSI(iter)->i < GVSI(iter)->n)
3132     return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3133
3134   return NULL;
3135 }
3136
3137 /* GVariantBuilder {{{1 */
3138 /**
3139  * GVariantBuilder:
3140  *
3141  * A utility type for constructing container-type #GVariant instances.
3142  *
3143  * This is an opaque structure and may only be accessed using the
3144  * following functions.
3145  *
3146  * #GVariantBuilder is not threadsafe in any way.  Do not attempt to
3147  * access it from more than one thread.
3148  **/
3149
3150 struct stack_builder
3151 {
3152   GVariantBuilder *parent;
3153   GVariantType *type;
3154
3155   /* type constraint explicitly specified by 'type'.
3156    * for tuple types, this moves along as we add more items.
3157    */
3158   const GVariantType *expected_type;
3159
3160   /* type constraint implied by previous array item.
3161    */
3162   const GVariantType *prev_item_type;
3163
3164   /* constraints on the number of children.  max = -1 for unlimited. */
3165   gsize min_items;
3166   gsize max_items;
3167
3168   /* dynamically-growing pointer array */
3169   GVariant **children;
3170   gsize allocated_children;
3171   gsize offset;
3172
3173   /* set to '1' if all items in the container will have the same type
3174    * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3175    */
3176   guint uniform_item_types : 1;
3177
3178   /* set to '1' initially and changed to '0' if an untrusted value is
3179    * added
3180    */
3181   guint trusted : 1;
3182
3183   gsize magic;
3184 };
3185
3186 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3187
3188 struct heap_builder
3189 {
3190   GVariantBuilder builder;
3191   gsize magic;
3192
3193   gint ref_count;
3194 };
3195
3196 #define GVSB(b)                  ((struct stack_builder *) (b))
3197 #define GVHB(b)                  ((struct heap_builder *) (b))
3198 #define GVSB_MAGIC               ((gsize) 1033660112u)
3199 #define GVSB_MAGIC_PARTIAL       ((gsize) 2942751021u)
3200 #define GVHB_MAGIC               ((gsize) 3087242682u)
3201 #define is_valid_builder(b)      (GVSB(b)->magic == GVSB_MAGIC)
3202 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3203
3204 /* Just to make sure that by adding a union to GVariantBuilder, we
3205  * didn't accidentally change ABI. */
3206 G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (gsize[16]));
3207
3208 static gboolean
3209 ensure_valid_builder (GVariantBuilder *builder)
3210 {
3211   if (builder == NULL)
3212     return FALSE;
3213   else if (is_valid_builder (builder))
3214     return TRUE;
3215   if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3216     {
3217       static GVariantBuilder cleared_builder;
3218
3219       /* Make sure that only first two fields were set and the rest is
3220        * zeroed to avoid messing up the builder that had parent
3221        * address equal to GVSB_MAGIC_PARTIAL. */
3222       if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3223         return FALSE;
3224
3225       g_variant_builder_init (builder, builder->u.s.type);
3226     }
3227   return is_valid_builder (builder);
3228 }
3229
3230 /* return_if_invalid_builder (b) is like
3231  * g_return_if_fail (ensure_valid_builder (b)), except that
3232  * the side effects of ensure_valid_builder are evaluated
3233  * regardless of whether G_DISABLE_CHECKS is defined or not. */
3234 #define return_if_invalid_builder(b) G_STMT_START {                \
3235   gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3236   g_return_if_fail (valid_builder);                                \
3237 } G_STMT_END
3238
3239 /* return_val_if_invalid_builder (b, val) is like
3240  * g_return_val_if_fail (ensure_valid_builder (b), val), except that
3241  * the side effects of ensure_valid_builder are evaluated
3242  * regardless of whether G_DISABLE_CHECKS is defined or not. */
3243 #define return_val_if_invalid_builder(b, val) G_STMT_START {       \
3244   gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3245   g_return_val_if_fail (valid_builder, val);                       \
3246 } G_STMT_END
3247
3248 /**
3249  * g_variant_builder_new:
3250  * @type: a container type
3251  *
3252  * Allocates and initialises a new #GVariantBuilder.
3253  *
3254  * You should call g_variant_builder_unref() on the return value when it
3255  * is no longer needed.  The memory will not be automatically freed by
3256  * any other call.
3257  *
3258  * In most cases it is easier to place a #GVariantBuilder directly on
3259  * the stack of the calling function and initialise it with
3260  * g_variant_builder_init().
3261  *
3262  * Returns: (transfer full): a #GVariantBuilder
3263  *
3264  * Since: 2.24
3265  **/
3266 GVariantBuilder *
3267 g_variant_builder_new (const GVariantType *type)
3268 {
3269   GVariantBuilder *builder;
3270
3271   builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3272   g_variant_builder_init (builder, type);
3273   GVHB(builder)->magic = GVHB_MAGIC;
3274   GVHB(builder)->ref_count = 1;
3275
3276   return builder;
3277 }
3278
3279 /**
3280  * g_variant_builder_unref:
3281  * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3282  *
3283  * Decreases the reference count on @builder.
3284  *
3285  * In the event that there are no more references, releases all memory
3286  * associated with the #GVariantBuilder.
3287  *
3288  * Don't call this on stack-allocated #GVariantBuilder instances or bad
3289  * things will happen.
3290  *
3291  * Since: 2.24
3292  **/
3293 void
3294 g_variant_builder_unref (GVariantBuilder *builder)
3295 {
3296   g_return_if_fail (is_valid_heap_builder (builder));
3297
3298   if (--GVHB(builder)->ref_count)
3299     return;
3300
3301   g_variant_builder_clear (builder);
3302   GVHB(builder)->magic = 0;
3303
3304   g_slice_free (struct heap_builder, GVHB(builder));
3305 }
3306
3307 /**
3308  * g_variant_builder_ref:
3309  * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3310  *
3311  * Increases the reference count on @builder.
3312  *
3313  * Don't call this on stack-allocated #GVariantBuilder instances or bad
3314  * things will happen.
3315  *
3316  * Returns: (transfer full): a new reference to @builder
3317  *
3318  * Since: 2.24
3319  **/
3320 GVariantBuilder *
3321 g_variant_builder_ref (GVariantBuilder *builder)
3322 {
3323   g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3324
3325   GVHB(builder)->ref_count++;
3326
3327   return builder;
3328 }
3329
3330 /**
3331  * g_variant_builder_clear: (skip)
3332  * @builder: a #GVariantBuilder
3333  *
3334  * Releases all memory associated with a #GVariantBuilder without
3335  * freeing the #GVariantBuilder structure itself.
3336  *
3337  * It typically only makes sense to do this on a stack-allocated
3338  * #GVariantBuilder if you want to abort building the value part-way
3339  * through.  This function need not be called if you call
3340  * g_variant_builder_end() and it also doesn't need to be called on
3341  * builders allocated with g_variant_builder_new() (see
3342  * g_variant_builder_unref() for that).
3343  *
3344  * This function leaves the #GVariantBuilder structure set to all-zeros.
3345  * It is valid to call this function on either an initialised
3346  * #GVariantBuilder or one that is set to all-zeros but it is not valid
3347  * to call this function on uninitialised memory.
3348  *
3349  * Since: 2.24
3350  **/
3351 void
3352 g_variant_builder_clear (GVariantBuilder *builder)
3353 {
3354   gsize i;
3355
3356   if (GVSB(builder)->magic == 0)
3357     /* all-zeros or partial case */
3358     return;
3359
3360   return_if_invalid_builder (builder);
3361
3362   g_variant_type_free (GVSB(builder)->type);
3363
3364   for (i = 0; i < GVSB(builder)->offset; i++)
3365     g_variant_unref (GVSB(builder)->children[i]);
3366
3367   g_free (GVSB(builder)->children);
3368
3369   if (GVSB(builder)->parent)
3370     {
3371       g_variant_builder_clear (GVSB(builder)->parent);
3372       g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3373     }
3374
3375   memset (builder, 0, sizeof (GVariantBuilder));
3376 }
3377
3378 /**
3379  * g_variant_builder_init: (skip)
3380  * @builder: a #GVariantBuilder
3381  * @type: a container type
3382  *
3383  * Initialises a #GVariantBuilder structure.
3384  *
3385  * @type must be non-%NULL.  It specifies the type of container to
3386  * construct.  It can be an indefinite type such as
3387  * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3388  * Maybe, array, tuple, dictionary entry and variant-typed values may be
3389  * constructed.
3390  *
3391  * After the builder is initialised, values are added using
3392  * g_variant_builder_add_value() or g_variant_builder_add().
3393  *
3394  * After all the child values are added, g_variant_builder_end() frees
3395  * the memory associated with the builder and returns the #GVariant that
3396  * was created.
3397  *
3398  * This function completely ignores the previous contents of @builder.
3399  * On one hand this means that it is valid to pass in completely
3400  * uninitialised memory.  On the other hand, this means that if you are
3401  * initialising over top of an existing #GVariantBuilder you need to
3402  * first call g_variant_builder_clear() in order to avoid leaking
3403  * memory.
3404  *
3405  * You must not call g_variant_builder_ref() or
3406  * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3407  * with this function.  If you ever pass a reference to a
3408  * #GVariantBuilder outside of the control of your own code then you
3409  * should assume that the person receiving that reference may try to use
3410  * reference counting; you should use g_variant_builder_new() instead of
3411  * this function.
3412  *
3413  * Since: 2.24
3414  **/
3415 void
3416 g_variant_builder_init (GVariantBuilder    *builder,
3417                         const GVariantType *type)
3418 {
3419   g_return_if_fail (type != NULL);
3420   g_return_if_fail (g_variant_type_is_container (type));
3421
3422   memset (builder, 0, sizeof (GVariantBuilder));
3423
3424   GVSB(builder)->type = g_variant_type_copy (type);
3425   GVSB(builder)->magic = GVSB_MAGIC;
3426   GVSB(builder)->trusted = TRUE;
3427
3428   switch (*(const gchar *) type)
3429     {
3430     case G_VARIANT_CLASS_VARIANT:
3431       GVSB(builder)->uniform_item_types = TRUE;
3432       GVSB(builder)->allocated_children = 1;
3433       GVSB(builder)->expected_type = NULL;
3434       GVSB(builder)->min_items = 1;
3435       GVSB(builder)->max_items = 1;
3436       break;
3437
3438     case G_VARIANT_CLASS_ARRAY:
3439       GVSB(builder)->uniform_item_types = TRUE;
3440       GVSB(builder)->allocated_children = 8;
3441       GVSB(builder)->expected_type =
3442         g_variant_type_element (GVSB(builder)->type);
3443       GVSB(builder)->min_items = 0;
3444       GVSB(builder)->max_items = -1;
3445       break;
3446
3447     case G_VARIANT_CLASS_MAYBE:
3448       GVSB(builder)->uniform_item_types = TRUE;
3449       GVSB(builder)->allocated_children = 1;
3450       GVSB(builder)->expected_type =
3451         g_variant_type_element (GVSB(builder)->type);
3452       GVSB(builder)->min_items = 0;
3453       GVSB(builder)->max_items = 1;
3454       break;
3455
3456     case G_VARIANT_CLASS_DICT_ENTRY:
3457       GVSB(builder)->uniform_item_types = FALSE;
3458       GVSB(builder)->allocated_children = 2;
3459       GVSB(builder)->expected_type =
3460         g_variant_type_key (GVSB(builder)->type);
3461       GVSB(builder)->min_items = 2;
3462       GVSB(builder)->max_items = 2;
3463       break;
3464
3465     case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3466       GVSB(builder)->uniform_item_types = FALSE;
3467       GVSB(builder)->allocated_children = 8;
3468       GVSB(builder)->expected_type = NULL;
3469       GVSB(builder)->min_items = 0;
3470       GVSB(builder)->max_items = -1;
3471       break;
3472
3473     case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3474       GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3475       GVSB(builder)->expected_type =
3476         g_variant_type_first (GVSB(builder)->type);
3477       GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3478       GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3479       GVSB(builder)->uniform_item_types = FALSE;
3480       break;
3481
3482     default:
3483       g_assert_not_reached ();
3484    }
3485
3486 #ifdef G_ANALYZER_ANALYZING
3487   /* Static analysers can’t couple the code in g_variant_builder_init() to the
3488    * code in g_variant_builder_end() by GVariantType, so end up assuming that
3489    * @offset and @children mismatch and that uninitialised memory is accessed
3490    * from @children. At runtime, this is caught by the preconditions at the top
3491    * of g_variant_builder_end(). Help the analyser by zero-initialising the
3492    * memory to avoid a false positive. */
3493   GVSB(builder)->children = g_new0 (GVariant *,
3494                                     GVSB(builder)->allocated_children);
3495 #else
3496   GVSB(builder)->children = g_new (GVariant *,
3497                                    GVSB(builder)->allocated_children);
3498 #endif
3499 }
3500
3501 static void
3502 g_variant_builder_make_room (struct stack_builder *builder)
3503 {
3504   if (builder->offset == builder->allocated_children)
3505     {
3506       builder->allocated_children *= 2;
3507       builder->children = g_renew (GVariant *, builder->children,
3508                                    builder->allocated_children);
3509     }
3510 }
3511
3512 /**
3513  * g_variant_builder_add_value:
3514  * @builder: a #GVariantBuilder
3515  * @value: a #GVariant
3516  *
3517  * Adds @value to @builder.
3518  *
3519  * It is an error to call this function in any way that would create an
3520  * inconsistent value to be constructed.  Some examples of this are
3521  * putting different types of items into an array, putting the wrong
3522  * types or number of items in a tuple, putting more than one value into
3523  * a variant, etc.
3524  *
3525  * If @value is a floating reference (see g_variant_ref_sink()),
3526  * the @builder instance takes ownership of @value.
3527  *
3528  * Since: 2.24
3529  **/
3530 void
3531 g_variant_builder_add_value (GVariantBuilder *builder,
3532                              GVariant        *value)
3533 {
3534   return_if_invalid_builder (builder);
3535   g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3536   g_return_if_fail (!GVSB(builder)->expected_type ||
3537                     g_variant_is_of_type (value,
3538                                           GVSB(builder)->expected_type));
3539   g_return_if_fail (!GVSB(builder)->prev_item_type ||
3540                     g_variant_is_of_type (value,
3541                                           GVSB(builder)->prev_item_type));
3542
3543   GVSB(builder)->trusted &= g_variant_is_trusted (value);
3544
3545   if (!GVSB(builder)->uniform_item_types)
3546     {
3547       /* advance our expected type pointers */
3548       if (GVSB(builder)->expected_type)
3549         GVSB(builder)->expected_type =
3550           g_variant_type_next (GVSB(builder)->expected_type);
3551
3552       if (GVSB(builder)->prev_item_type)
3553         GVSB(builder)->prev_item_type =
3554           g_variant_type_next (GVSB(builder)->prev_item_type);
3555     }
3556   else
3557     GVSB(builder)->prev_item_type = g_variant_get_type (value);
3558
3559   g_variant_builder_make_room (GVSB(builder));
3560
3561   GVSB(builder)->children[GVSB(builder)->offset++] =
3562     g_variant_ref_sink (value);
3563 }
3564
3565 /**
3566  * g_variant_builder_open:
3567  * @builder: a #GVariantBuilder
3568  * @type: the #GVariantType of the container
3569  *
3570  * Opens a subcontainer inside the given @builder.  When done adding
3571  * items to the subcontainer, g_variant_builder_close() must be called. @type
3572  * is the type of the container: so to build a tuple of several values, @type
3573  * must include the tuple itself.
3574  *
3575  * It is an error to call this function in any way that would cause an
3576  * inconsistent value to be constructed (ie: adding too many values or
3577  * a value of an incorrect type).
3578  *
3579  * Example of building a nested variant:
3580  * |[<!-- language="C" -->
3581  * GVariantBuilder builder;
3582  * guint32 some_number = get_number ();
3583  * g_autoptr (GHashTable) some_dict = get_dict ();
3584  * GHashTableIter iter;
3585  * const gchar *key;
3586  * const GVariant *value;
3587  * g_autoptr (GVariant) output = NULL;
3588  *
3589  * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3590  * g_variant_builder_add (&builder, "u", some_number);
3591  * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3592  *
3593  * g_hash_table_iter_init (&iter, some_dict);
3594  * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3595  *   {
3596  *     g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3597  *     g_variant_builder_add (&builder, "s", key);
3598  *     g_variant_builder_add (&builder, "v", value);
3599  *     g_variant_builder_close (&builder);
3600  *   }
3601  *
3602  * g_variant_builder_close (&builder);
3603  *
3604  * output = g_variant_builder_end (&builder);
3605  * ]|
3606  *
3607  * Since: 2.24
3608  **/
3609 void
3610 g_variant_builder_open (GVariantBuilder    *builder,
3611                         const GVariantType *type)
3612 {
3613   GVariantBuilder *parent;
3614
3615   return_if_invalid_builder (builder);
3616   g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3617   g_return_if_fail (!GVSB(builder)->expected_type ||
3618                     g_variant_type_is_subtype_of (type,
3619                                                   GVSB(builder)->expected_type));
3620   g_return_if_fail (!GVSB(builder)->prev_item_type ||
3621                     g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3622                                                   type));
3623
3624   parent = g_slice_dup (GVariantBuilder, builder);
3625   g_variant_builder_init (builder, type);
3626   GVSB(builder)->parent = parent;
3627
3628   /* push the prev_item_type down into the subcontainer */
3629   if (GVSB(parent)->prev_item_type)
3630     {
3631       if (!GVSB(builder)->uniform_item_types)
3632         /* tuples and dict entries */
3633         GVSB(builder)->prev_item_type =
3634           g_variant_type_first (GVSB(parent)->prev_item_type);
3635
3636       else if (!g_variant_type_is_variant (GVSB(builder)->type))
3637         /* maybes and arrays */
3638         GVSB(builder)->prev_item_type =
3639           g_variant_type_element (GVSB(parent)->prev_item_type);
3640     }
3641 }
3642
3643 /**
3644  * g_variant_builder_close:
3645  * @builder: a #GVariantBuilder
3646  *
3647  * Closes the subcontainer inside the given @builder that was opened by
3648  * the most recent call to g_variant_builder_open().
3649  *
3650  * It is an error to call this function in any way that would create an
3651  * inconsistent value to be constructed (ie: too few values added to the
3652  * subcontainer).
3653  *
3654  * Since: 2.24
3655  **/
3656 void
3657 g_variant_builder_close (GVariantBuilder *builder)
3658 {
3659   GVariantBuilder *parent;
3660
3661   return_if_invalid_builder (builder);
3662   g_return_if_fail (GVSB(builder)->parent != NULL);
3663
3664   parent = GVSB(builder)->parent;
3665   GVSB(builder)->parent = NULL;
3666
3667   g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3668   *builder = *parent;
3669
3670   g_slice_free (GVariantBuilder, parent);
3671 }
3672
3673 /*< private >
3674  * g_variant_make_maybe_type:
3675  * @element: a #GVariant
3676  *
3677  * Return the type of a maybe containing @element.
3678  */
3679 static GVariantType *
3680 g_variant_make_maybe_type (GVariant *element)
3681 {
3682   return g_variant_type_new_maybe (g_variant_get_type (element));
3683 }
3684
3685 /*< private >
3686  * g_variant_make_array_type:
3687  * @element: a #GVariant
3688  *
3689  * Return the type of an array containing @element.
3690  */
3691 static GVariantType *
3692 g_variant_make_array_type (GVariant *element)
3693 {
3694   return g_variant_type_new_array (g_variant_get_type (element));
3695 }
3696
3697 /**
3698  * g_variant_builder_end:
3699  * @builder: a #GVariantBuilder
3700  *
3701  * Ends the builder process and returns the constructed value.
3702  *
3703  * It is not permissible to use @builder in any way after this call
3704  * except for reference counting operations (in the case of a
3705  * heap-allocated #GVariantBuilder) or by reinitialising it with
3706  * g_variant_builder_init() (in the case of stack-allocated). This
3707  * means that for the stack-allocated builders there is no need to
3708  * call g_variant_builder_clear() after the call to
3709  * g_variant_builder_end().
3710  *
3711  * It is an error to call this function in any way that would create an
3712  * inconsistent value to be constructed (ie: insufficient number of
3713  * items added to a container with a specific number of children
3714  * required).  It is also an error to call this function if the builder
3715  * was created with an indefinite array or maybe type and no children
3716  * have been added; in this case it is impossible to infer the type of
3717  * the empty array.
3718  *
3719  * Returns: (transfer none): a new, floating, #GVariant
3720  *
3721  * Since: 2.24
3722  **/
3723 GVariant *
3724 g_variant_builder_end (GVariantBuilder *builder)
3725 {
3726   GVariantType *my_type;
3727   GVariant *value;
3728
3729   return_val_if_invalid_builder (builder, NULL);
3730   g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3731                         NULL);
3732   g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3733                         GVSB(builder)->prev_item_type != NULL ||
3734                         g_variant_type_is_definite (GVSB(builder)->type),
3735                         NULL);
3736
3737   if (g_variant_type_is_definite (GVSB(builder)->type))
3738     my_type = g_variant_type_copy (GVSB(builder)->type);
3739
3740   else if (g_variant_type_is_maybe (GVSB(builder)->type))
3741     my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3742
3743   else if (g_variant_type_is_array (GVSB(builder)->type))
3744     my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3745
3746   else if (g_variant_type_is_tuple (GVSB(builder)->type))
3747     my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3748                                          GVSB(builder)->offset);
3749
3750   else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3751     my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3752                                               GVSB(builder)->children[1]);
3753   else
3754     g_assert_not_reached ();
3755
3756   value = g_variant_new_from_children (my_type,
3757                                        g_renew (GVariant *,
3758                                                 GVSB(builder)->children,
3759                                                 GVSB(builder)->offset),
3760                                        GVSB(builder)->offset,
3761                                        GVSB(builder)->trusted);
3762   GVSB(builder)->children = NULL;
3763   GVSB(builder)->offset = 0;
3764
3765   g_variant_builder_clear (builder);
3766   g_variant_type_free (my_type);
3767
3768   return value;
3769 }
3770
3771 /* GVariantDict {{{1 */
3772
3773 /**
3774  * GVariantDict:
3775  *
3776  * #GVariantDict is a mutable interface to #GVariant dictionaries.
3777  *
3778  * It can be used for doing a sequence of dictionary lookups in an
3779  * efficient way on an existing #GVariant dictionary or it can be used
3780  * to construct new dictionaries with a hashtable-like interface.  It
3781  * can also be used for taking existing dictionaries and modifying them
3782  * in order to create new ones.
3783  *
3784  * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3785  * dictionaries.
3786  *
3787  * It is possible to use #GVariantDict allocated on the stack or on the
3788  * heap.  When using a stack-allocated #GVariantDict, you begin with a
3789  * call to g_variant_dict_init() and free the resources with a call to
3790  * g_variant_dict_clear().
3791  *
3792  * Heap-allocated #GVariantDict follows normal refcounting rules: you
3793  * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3794  * and g_variant_dict_unref().
3795  *
3796  * g_variant_dict_end() is used to convert the #GVariantDict back into a
3797  * dictionary-type #GVariant.  When used with stack-allocated instances,
3798  * this also implicitly frees all associated memory, but for
3799  * heap-allocated instances, you must still call g_variant_dict_unref()
3800  * afterwards.
3801  *
3802  * You will typically want to use a heap-allocated #GVariantDict when
3803  * you expose it as part of an API.  For most other uses, the
3804  * stack-allocated form will be more convenient.
3805  *
3806  * Consider the following two examples that do the same thing in each
3807  * style: take an existing dictionary and look up the "count" uint32
3808  * key, adding 1 to it if it is found, or returning an error if the
3809  * key is not found.  Each returns the new dictionary as a floating
3810  * #GVariant.
3811  *
3812  * ## Using a stack-allocated GVariantDict
3813  *
3814  * |[<!-- language="C" -->
3815  *   GVariant *
3816  *   add_to_count (GVariant  *orig,
3817  *                 GError   **error)
3818  *   {
3819  *     GVariantDict dict;
3820  *     guint32 count;
3821  *
3822  *     g_variant_dict_init (&dict, orig);
3823  *     if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3824  *       {
3825  *         g_set_error (...);
3826  *         g_variant_dict_clear (&dict);
3827  *         return NULL;
3828  *       }
3829  *
3830  *     g_variant_dict_insert (&dict, "count", "u", count + 1);
3831  *
3832  *     return g_variant_dict_end (&dict);
3833  *   }
3834  * ]|
3835  *
3836  * ## Using heap-allocated GVariantDict
3837  *
3838  * |[<!-- language="C" -->
3839  *   GVariant *
3840  *   add_to_count (GVariant  *orig,
3841  *                 GError   **error)
3842  *   {
3843  *     GVariantDict *dict;
3844  *     GVariant *result;
3845  *     guint32 count;
3846  *
3847  *     dict = g_variant_dict_new (orig);
3848  *
3849  *     if (g_variant_dict_lookup (dict, "count", "u", &count))
3850  *       {
3851  *         g_variant_dict_insert (dict, "count", "u", count + 1);
3852  *         result = g_variant_dict_end (dict);
3853  *       }
3854  *     else
3855  *       {
3856  *         g_set_error (...);
3857  *         result = NULL;
3858  *       }
3859  *
3860  *     g_variant_dict_unref (dict);
3861  *
3862  *     return result;
3863  *   }
3864  * ]|
3865  *
3866  * Since: 2.40
3867  **/
3868 struct stack_dict
3869 {
3870   GHashTable *values;
3871   gsize magic;
3872 };
3873
3874 G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3875
3876 struct heap_dict
3877 {
3878   struct stack_dict dict;
3879   gint ref_count;
3880   gsize magic;
3881 };
3882
3883 #define GVSD(d)                 ((struct stack_dict *) (d))
3884 #define GVHD(d)                 ((struct heap_dict *) (d))
3885 #define GVSD_MAGIC              ((gsize) 2579507750u)
3886 #define GVSD_MAGIC_PARTIAL      ((gsize) 3488698669u)
3887 #define GVHD_MAGIC              ((gsize) 2450270775u)
3888 #define is_valid_dict(d)        (GVSD(d)->magic == GVSD_MAGIC)
3889 #define is_valid_heap_dict(d)   (GVHD(d)->magic == GVHD_MAGIC)
3890
3891 /* Just to make sure that by adding a union to GVariantDict, we didn't
3892  * accidentally change ABI. */
3893 G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (gsize[16]));
3894
3895 static gboolean
3896 ensure_valid_dict (GVariantDict *dict)
3897 {
3898   if (dict == NULL)
3899     return FALSE;
3900   else if (is_valid_dict (dict))
3901     return TRUE;
3902   if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3903     {
3904       static GVariantDict cleared_dict;
3905
3906       /* Make sure that only first two fields were set and the rest is
3907        * zeroed to avoid messing up the builder that had parent
3908        * address equal to GVSB_MAGIC_PARTIAL. */
3909       if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3910         return FALSE;
3911
3912       g_variant_dict_init (dict, dict->u.s.asv);
3913     }
3914   return is_valid_dict (dict);
3915 }
3916
3917 /* return_if_invalid_dict (d) is like
3918  * g_return_if_fail (ensure_valid_dict (d)), except that
3919  * the side effects of ensure_valid_dict are evaluated
3920  * regardless of whether G_DISABLE_CHECKS is defined or not. */
3921 #define return_if_invalid_dict(d) G_STMT_START {                \
3922   gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d);    \
3923   g_return_if_fail (valid_dict);                                \
3924 } G_STMT_END
3925
3926 /* return_val_if_invalid_dict (d, val) is like
3927  * g_return_val_if_fail (ensure_valid_dict (d), val), except that
3928  * the side effects of ensure_valid_dict are evaluated
3929  * regardless of whether G_DISABLE_CHECKS is defined or not. */
3930 #define return_val_if_invalid_dict(d, val) G_STMT_START {       \
3931   gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d);    \
3932   g_return_val_if_fail (valid_dict, val);                       \
3933 } G_STMT_END
3934
3935 /**
3936  * g_variant_dict_new:
3937  * @from_asv: (nullable): the #GVariant with which to initialise the
3938  *   dictionary
3939  *
3940  * Allocates and initialises a new #GVariantDict.
3941  *
3942  * You should call g_variant_dict_unref() on the return value when it
3943  * is no longer needed.  The memory will not be automatically freed by
3944  * any other call.
3945  *
3946  * In some cases it may be easier to place a #GVariantDict directly on
3947  * the stack of the calling function and initialise it with
3948  * g_variant_dict_init().  This is particularly useful when you are
3949  * using #GVariantDict to construct a #GVariant.
3950  *
3951  * Returns: (transfer full): a #GVariantDict
3952  *
3953  * Since: 2.40
3954  **/
3955 GVariantDict *
3956 g_variant_dict_new (GVariant *from_asv)
3957 {
3958   GVariantDict *dict;
3959
3960   dict = g_slice_alloc (sizeof (struct heap_dict));
3961   g_variant_dict_init (dict, from_asv);
3962   GVHD(dict)->magic = GVHD_MAGIC;
3963   GVHD(dict)->ref_count = 1;
3964
3965   return dict;
3966 }
3967
3968 /**
3969  * g_variant_dict_init: (skip)
3970  * @dict: a #GVariantDict
3971  * @from_asv: (nullable): the initial value for @dict
3972  *
3973  * Initialises a #GVariantDict structure.
3974  *
3975  * If @from_asv is given, it is used to initialise the dictionary.
3976  *
3977  * This function completely ignores the previous contents of @dict.  On
3978  * one hand this means that it is valid to pass in completely
3979  * uninitialised memory.  On the other hand, this means that if you are
3980  * initialising over top of an existing #GVariantDict you need to first
3981  * call g_variant_dict_clear() in order to avoid leaking memory.
3982  *
3983  * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
3984  * #GVariantDict that was initialised with this function.  If you ever
3985  * pass a reference to a #GVariantDict outside of the control of your
3986  * own code then you should assume that the person receiving that
3987  * reference may try to use reference counting; you should use
3988  * g_variant_dict_new() instead of this function.
3989  *
3990  * Since: 2.40
3991  **/
3992 void
3993 g_variant_dict_init (GVariantDict *dict,
3994                      GVariant     *from_asv)
3995 {
3996   GVariantIter iter;
3997   gchar *key;
3998   GVariant *value;
3999
4000   GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
4001   GVSD(dict)->magic = GVSD_MAGIC;
4002
4003   if (from_asv)
4004     {
4005       g_variant_iter_init (&iter, from_asv);
4006       while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4007         g_hash_table_insert (GVSD(dict)->values, key, value);
4008     }
4009 }
4010
4011 /**
4012  * g_variant_dict_lookup:
4013  * @dict: a #GVariantDict
4014  * @key: the key to look up in the dictionary
4015  * @format_string: a GVariant format string
4016  * @...: the arguments to unpack the value into
4017  *
4018  * Looks up a value in a #GVariantDict.
4019  *
4020  * This function is a wrapper around g_variant_dict_lookup_value() and
4021  * g_variant_get().  In the case that %NULL would have been returned,
4022  * this function returns %FALSE.  Otherwise, it unpacks the returned
4023  * value and returns %TRUE.
4024  *
4025  * @format_string determines the C types that are used for unpacking the
4026  * values and also determines if the values are copied or borrowed, see the
4027  * section on [GVariant format strings][gvariant-format-strings-pointers].
4028  *
4029  * Returns: %TRUE if a value was unpacked
4030  *
4031  * Since: 2.40
4032  **/
4033 gboolean
4034 g_variant_dict_lookup (GVariantDict *dict,
4035                        const gchar  *key,
4036                        const gchar  *format_string,
4037                        ...)
4038 {
4039   GVariant *value;
4040   va_list ap;
4041
4042   return_val_if_invalid_dict (dict, FALSE);
4043   g_return_val_if_fail (key != NULL, FALSE);
4044   g_return_val_if_fail (format_string != NULL, FALSE);
4045
4046   value = g_hash_table_lookup (GVSD(dict)->values, key);
4047
4048   if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
4049     return FALSE;
4050
4051   va_start (ap, format_string);
4052   g_variant_get_va (value, format_string, NULL, &ap);
4053   va_end (ap);
4054
4055   return TRUE;
4056 }
4057
4058 /**
4059  * g_variant_dict_lookup_value:
4060  * @dict: a #GVariantDict
4061  * @key: the key to look up in the dictionary
4062  * @expected_type: (nullable): a #GVariantType, or %NULL
4063  *
4064  * Looks up a value in a #GVariantDict.
4065  *
4066  * If @key is not found in @dictionary, %NULL is returned.
4067  *
4068  * The @expected_type string specifies what type of value is expected.
4069  * If the value associated with @key has a different type then %NULL is
4070  * returned.
4071  *
4072  * If the key is found and the value has the correct type, it is
4073  * returned.  If @expected_type was specified then any non-%NULL return
4074  * value will have this type.
4075  *
4076  * Returns: (transfer full) (nullable): the value of the dictionary key, or %NULL
4077  *
4078  * Since: 2.40
4079  **/
4080 GVariant *
4081 g_variant_dict_lookup_value (GVariantDict       *dict,
4082                              const gchar        *key,
4083                              const GVariantType *expected_type)
4084 {
4085   GVariant *result;
4086
4087   return_val_if_invalid_dict (dict, NULL);
4088   g_return_val_if_fail (key != NULL, NULL);
4089
4090   result = g_hash_table_lookup (GVSD(dict)->values, key);
4091
4092   if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4093     return g_variant_ref (result);
4094
4095   return NULL;
4096 }
4097
4098 /**
4099  * g_variant_dict_contains:
4100  * @dict: a #GVariantDict
4101  * @key: the key to look up in the dictionary
4102  *
4103  * Checks if @key exists in @dict.
4104  *
4105  * Returns: %TRUE if @key is in @dict
4106  *
4107  * Since: 2.40
4108  **/
4109 gboolean
4110 g_variant_dict_contains (GVariantDict *dict,
4111                          const gchar  *key)
4112 {
4113   return_val_if_invalid_dict (dict, FALSE);
4114   g_return_val_if_fail (key != NULL, FALSE);
4115
4116   return g_hash_table_contains (GVSD(dict)->values, key);
4117 }
4118
4119 /**
4120  * g_variant_dict_insert:
4121  * @dict: a #GVariantDict
4122  * @key: the key to insert a value for
4123  * @format_string: a #GVariant varargs format string
4124  * @...: arguments, as per @format_string
4125  *
4126  * Inserts a value into a #GVariantDict.
4127  *
4128  * This call is a convenience wrapper that is exactly equivalent to
4129  * calling g_variant_new() followed by g_variant_dict_insert_value().
4130  *
4131  * Since: 2.40
4132  **/
4133 void
4134 g_variant_dict_insert (GVariantDict *dict,
4135                        const gchar  *key,
4136                        const gchar  *format_string,
4137                        ...)
4138 {
4139   va_list ap;
4140
4141   return_if_invalid_dict (dict);
4142   g_return_if_fail (key != NULL);
4143   g_return_if_fail (format_string != NULL);
4144
4145   va_start (ap, format_string);
4146   g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4147   va_end (ap);
4148 }
4149
4150 /**
4151  * g_variant_dict_insert_value:
4152  * @dict: a #GVariantDict
4153  * @key: the key to insert a value for
4154  * @value: the value to insert
4155  *
4156  * Inserts (or replaces) a key in a #GVariantDict.
4157  *
4158  * @value is consumed if it is floating.
4159  *
4160  * Since: 2.40
4161  **/
4162 void
4163 g_variant_dict_insert_value (GVariantDict *dict,
4164                              const gchar  *key,
4165                              GVariant     *value)
4166 {
4167   return_if_invalid_dict (dict);
4168   g_return_if_fail (key != NULL);
4169   g_return_if_fail (value != NULL);
4170
4171   g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4172 }
4173
4174 /**
4175  * g_variant_dict_remove:
4176  * @dict: a #GVariantDict
4177  * @key: the key to remove
4178  *
4179  * Removes a key and its associated value from a #GVariantDict.
4180  *
4181  * Returns: %TRUE if the key was found and removed
4182  *
4183  * Since: 2.40
4184  **/
4185 gboolean
4186 g_variant_dict_remove (GVariantDict *dict,
4187                        const gchar  *key)
4188 {
4189   return_val_if_invalid_dict (dict, FALSE);
4190   g_return_val_if_fail (key != NULL, FALSE);
4191
4192   return g_hash_table_remove (GVSD(dict)->values, key);
4193 }
4194
4195 /**
4196  * g_variant_dict_clear:
4197  * @dict: a #GVariantDict
4198  *
4199  * Releases all memory associated with a #GVariantDict without freeing
4200  * the #GVariantDict structure itself.
4201  *
4202  * It typically only makes sense to do this on a stack-allocated
4203  * #GVariantDict if you want to abort building the value part-way
4204  * through.  This function need not be called if you call
4205  * g_variant_dict_end() and it also doesn't need to be called on dicts
4206  * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4207  * that).
4208  *
4209  * It is valid to call this function on either an initialised
4210  * #GVariantDict or one that was previously cleared by an earlier call
4211  * to g_variant_dict_clear() but it is not valid to call this function
4212  * on uninitialised memory.
4213  *
4214  * Since: 2.40
4215  **/
4216 void
4217 g_variant_dict_clear (GVariantDict *dict)
4218 {
4219   if (GVSD(dict)->magic == 0)
4220     /* all-zeros case */
4221     return;
4222
4223   return_if_invalid_dict (dict);
4224
4225   g_hash_table_unref (GVSD(dict)->values);
4226   GVSD(dict)->values = NULL;
4227
4228   GVSD(dict)->magic = 0;
4229 }
4230
4231 /**
4232  * g_variant_dict_end:
4233  * @dict: a #GVariantDict
4234  *
4235  * Returns the current value of @dict as a #GVariant of type
4236  * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4237  *
4238  * It is not permissible to use @dict in any way after this call except
4239  * for reference counting operations (in the case of a heap-allocated
4240  * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4241  * the case of stack-allocated).
4242  *
4243  * Returns: (transfer none): a new, floating, #GVariant
4244  *
4245  * Since: 2.40
4246  **/
4247 GVariant *
4248 g_variant_dict_end (GVariantDict *dict)
4249 {
4250   GVariantBuilder builder;
4251   GHashTableIter iter;
4252   gpointer key, value;
4253
4254   return_val_if_invalid_dict (dict, NULL);
4255
4256   g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4257
4258   g_hash_table_iter_init (&iter, GVSD(dict)->values);
4259   while (g_hash_table_iter_next (&iter, &key, &value))
4260     g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4261
4262   g_variant_dict_clear (dict);
4263
4264   return g_variant_builder_end (&builder);
4265 }
4266
4267 /**
4268  * g_variant_dict_ref:
4269  * @dict: a heap-allocated #GVariantDict
4270  *
4271  * Increases the reference count on @dict.
4272  *
4273  * Don't call this on stack-allocated #GVariantDict instances or bad
4274  * things will happen.
4275  *
4276  * Returns: (transfer full): a new reference to @dict
4277  *
4278  * Since: 2.40
4279  **/
4280 GVariantDict *
4281 g_variant_dict_ref (GVariantDict *dict)
4282 {
4283   g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4284
4285   GVHD(dict)->ref_count++;
4286
4287   return dict;
4288 }
4289
4290 /**
4291  * g_variant_dict_unref:
4292  * @dict: (transfer full): a heap-allocated #GVariantDict
4293  *
4294  * Decreases the reference count on @dict.
4295  *
4296  * In the event that there are no more references, releases all memory
4297  * associated with the #GVariantDict.
4298  *
4299  * Don't call this on stack-allocated #GVariantDict instances or bad
4300  * things will happen.
4301  *
4302  * Since: 2.40
4303  **/
4304 void
4305 g_variant_dict_unref (GVariantDict *dict)
4306 {
4307   g_return_if_fail (is_valid_heap_dict (dict));
4308
4309   if (--GVHD(dict)->ref_count == 0)
4310     {
4311       g_variant_dict_clear (dict);
4312       g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4313     }
4314 }
4315
4316
4317 /* Format strings {{{1 */
4318 /*< private >
4319  * g_variant_format_string_scan:
4320  * @string: a string that may be prefixed with a format string
4321  * @limit: (nullable) (default NULL): a pointer to the end of @string,
4322  *         or %NULL
4323  * @endptr: (nullable) (default NULL): location to store the end pointer,
4324  *          or %NULL
4325  *
4326  * Checks the string pointed to by @string for starting with a properly
4327  * formed #GVariant varargs format string.  If no valid format string is
4328  * found then %FALSE is returned.
4329  *
4330  * If @string does start with a valid format string then %TRUE is
4331  * returned.  If @endptr is non-%NULL then it is updated to point to the
4332  * first character after the format string.
4333  *
4334  * If @limit is non-%NULL then @limit (and any character after it) will
4335  * not be accessed and the effect is otherwise equivalent to if the
4336  * character at @limit were nul.
4337  *
4338  * See the section on [GVariant format strings][gvariant-format-strings].
4339  *
4340  * Returns: %TRUE if there was a valid format string
4341  *
4342  * Since: 2.24
4343  */
4344 gboolean
4345 g_variant_format_string_scan (const gchar  *string,
4346                               const gchar  *limit,
4347                               const gchar **endptr)
4348 {
4349 #define next_char() (string == limit ? '\0' : *(string++))
4350 #define peek_char() (string == limit ? '\0' : *string)
4351   char c;
4352
4353   switch (next_char())
4354     {
4355     case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4356     case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4357     case 'g': case 'v': case '*': case '?': case 'r':
4358       break;
4359
4360     case 'm':
4361       return g_variant_format_string_scan (string, limit, endptr);
4362
4363     case 'a':
4364     case '@':
4365       return g_variant_type_string_scan (string, limit, endptr);
4366
4367     case '(':
4368       while (peek_char() != ')')
4369         if (!g_variant_format_string_scan (string, limit, &string))
4370           return FALSE;
4371
4372       next_char(); /* consume ')' */
4373       break;
4374
4375     case '{':
4376       c = next_char();
4377
4378       if (c == '&')
4379         {
4380           c = next_char ();
4381
4382           if (c != 's' && c != 'o' && c != 'g')
4383             return FALSE;
4384         }
4385       else
4386         {
4387           if (c == '@')
4388             c = next_char ();
4389
4390           /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4391            *    The terminating null character is considered to be
4392            *    part of the string.
4393            */
4394           if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4395             return FALSE;
4396         }
4397
4398       if (!g_variant_format_string_scan (string, limit, &string))
4399         return FALSE;
4400
4401       if (next_char() != '}')
4402         return FALSE;
4403
4404       break;
4405
4406     case '^':
4407       if ((c = next_char()) == 'a')
4408         {
4409           if ((c = next_char()) == '&')
4410             {
4411               if ((c = next_char()) == 'a')
4412                 {
4413                   if ((c = next_char()) == 'y')
4414                     break;      /* '^a&ay' */
4415                 }
4416
4417               else if (c == 's' || c == 'o')
4418                 break;          /* '^a&s', '^a&o' */
4419             }
4420
4421           else if (c == 'a')
4422             {
4423               if ((c = next_char()) == 'y')
4424                 break;          /* '^aay' */
4425             }
4426
4427           else if (c == 's' || c == 'o')
4428             break;              /* '^as', '^ao' */
4429
4430           else if (c == 'y')
4431             break;              /* '^ay' */
4432         }
4433       else if (c == '&')
4434         {
4435           if ((c = next_char()) == 'a')
4436             {
4437               if ((c = next_char()) == 'y')
4438                 break;          /* '^&ay' */
4439             }
4440         }
4441
4442       return FALSE;
4443
4444     case '&':
4445       c = next_char();
4446
4447       if (c != 's' && c != 'o' && c != 'g')
4448         return FALSE;
4449
4450       break;
4451
4452     default:
4453       return FALSE;
4454     }
4455
4456   if (endptr != NULL)
4457     *endptr = string;
4458
4459 #undef next_char
4460 #undef peek_char
4461
4462   return TRUE;
4463 }
4464
4465 /**
4466  * g_variant_check_format_string:
4467  * @value: a #GVariant
4468  * @format_string: a valid #GVariant format string
4469  * @copy_only: %TRUE to ensure the format string makes deep copies
4470  *
4471  * Checks if calling g_variant_get() with @format_string on @value would
4472  * be valid from a type-compatibility standpoint.  @format_string is
4473  * assumed to be a valid format string (from a syntactic standpoint).
4474  *
4475  * If @copy_only is %TRUE then this function additionally checks that it
4476  * would be safe to call g_variant_unref() on @value immediately after
4477  * the call to g_variant_get() without invalidating the result.  This is
4478  * only possible if deep copies are made (ie: there are no pointers to
4479  * the data inside of the soon-to-be-freed #GVariant instance).  If this
4480  * check fails then a g_critical() is printed and %FALSE is returned.
4481  *
4482  * This function is meant to be used by functions that wish to provide
4483  * varargs accessors to #GVariant values of uncertain values (eg:
4484  * g_variant_lookup() or g_menu_model_get_item_attribute()).
4485  *
4486  * Returns: %TRUE if @format_string is safe to use
4487  *
4488  * Since: 2.34
4489  */
4490 gboolean
4491 g_variant_check_format_string (GVariant    *value,
4492                                const gchar *format_string,
4493                                gboolean     copy_only)
4494 {
4495   const gchar *original_format = format_string;
4496   const gchar *type_string;
4497
4498   /* Interesting factoid: assuming a format string is valid, it can be
4499    * converted to a type string by removing all '@' '&' and '^'
4500    * characters.
4501    *
4502    * Instead of doing that, we can just skip those characters when
4503    * comparing it to the type string of @value.
4504    *
4505    * For the copy-only case we can just drop the '&' from the list of
4506    * characters to skip over.  A '&' will never appear in a type string
4507    * so we know that it won't be possible to return %TRUE if it is in a
4508    * format string.
4509    */
4510   type_string = g_variant_get_type_string (value);
4511
4512   while (*type_string || *format_string)
4513     {
4514       gchar format = *format_string++;
4515
4516       switch (format)
4517         {
4518         case '&':
4519           if G_UNLIKELY (copy_only)
4520             {
4521               /* for the love of all that is good, please don't mark this string for translation... */
4522               g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4523                           "interface to validate the passed format string for type safety.  The passed format "
4524                           "(%s) contains a '&' character which would result in a pointer being returned to the "
4525                           "data inside of a GVariant instance that may no longer exist by the time the function "
4526                           "returns.  Modify your code to use a format string without '&'.", original_format);
4527               return FALSE;
4528             }
4529
4530           G_GNUC_FALLTHROUGH;
4531         case '^':
4532         case '@':
4533           /* ignore these 2 (or 3) */
4534           continue;
4535
4536         case '?':
4537           /* attempt to consume one of 'bynqiuxthdsog' */
4538           {
4539             char s = *type_string++;
4540
4541             if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4542               return FALSE;
4543           }
4544           continue;
4545
4546         case 'r':
4547           /* ensure it's a tuple */
4548           if (*type_string != '(')
4549             return FALSE;
4550
4551           G_GNUC_FALLTHROUGH;
4552         case '*':
4553           /* consume a full type string for the '*' or 'r' */
4554           if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4555             return FALSE;
4556
4557           continue;
4558
4559         default:
4560           /* attempt to consume exactly one character equal to the format */
4561           if (format != *type_string++)
4562             return FALSE;
4563         }
4564     }
4565
4566   return TRUE;
4567 }
4568
4569 /*< private >
4570  * g_variant_format_string_scan_type:
4571  * @string: a string that may be prefixed with a format string
4572  * @limit: (nullable) (default NULL): a pointer to the end of @string,
4573  *         or %NULL
4574  * @endptr: (nullable) (default NULL): location to store the end pointer,
4575  *          or %NULL
4576  *
4577  * If @string starts with a valid format string then this function will
4578  * return the type that the format string corresponds to.  Otherwise
4579  * this function returns %NULL.
4580  *
4581  * Use g_variant_type_free() to free the return value when you no longer
4582  * need it.
4583  *
4584  * This function is otherwise exactly like
4585  * g_variant_format_string_scan().
4586  *
4587  * Returns: (nullable): a #GVariantType if there was a valid format string
4588  *
4589  * Since: 2.24
4590  */
4591 GVariantType *
4592 g_variant_format_string_scan_type (const gchar  *string,
4593                                    const gchar  *limit,
4594                                    const gchar **endptr)
4595 {
4596   const gchar *my_end;
4597   gchar *dest;
4598   gchar *new;
4599
4600   if (endptr == NULL)
4601     endptr = &my_end;
4602
4603   if (!g_variant_format_string_scan (string, limit, endptr))
4604     return NULL;
4605
4606   dest = new = g_malloc (*endptr - string + 1);
4607   while (string != *endptr)
4608     {
4609       if (*string != '@' && *string != '&' && *string != '^')
4610         *dest++ = *string;
4611       string++;
4612     }
4613   *dest = '\0';
4614
4615   return (GVariantType *) G_VARIANT_TYPE (new);
4616 }
4617
4618 static gboolean
4619 valid_format_string (const gchar *format_string,
4620                      gboolean     single,
4621                      GVariant    *value)
4622 {
4623   const gchar *endptr;
4624   GVariantType *type;
4625
4626   type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4627
4628   if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4629     {
4630       if (single)
4631         g_critical ("'%s' is not a valid GVariant format string",
4632                     format_string);
4633       else
4634         g_critical ("'%s' does not have a valid GVariant format "
4635                     "string as a prefix", format_string);
4636
4637       if (type != NULL)
4638         g_variant_type_free (type);
4639
4640       return FALSE;
4641     }
4642
4643   if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4644     {
4645       gchar *fragment;
4646       gchar *typestr;
4647
4648       fragment = g_strndup (format_string, endptr - format_string);
4649       typestr = g_variant_type_dup_string (type);
4650
4651       g_critical ("the GVariant format string '%s' has a type of "
4652                   "'%s' but the given value has a type of '%s'",
4653                   fragment, typestr, g_variant_get_type_string (value));
4654
4655       g_variant_type_free (type);
4656       g_free (fragment);
4657       g_free (typestr);
4658
4659       return FALSE;
4660     }
4661
4662   g_variant_type_free (type);
4663
4664   return TRUE;
4665 }
4666
4667 /* Variable Arguments {{{1 */
4668 /* We consider 2 main classes of format strings:
4669  *
4670  *   - recursive format strings
4671  *      these are ones that result in recursion and the collection of
4672  *      possibly more than one argument.  Maybe types, tuples,
4673  *      dictionary entries.
4674  *
4675  *   - leaf format string
4676  *      these result in the collection of a single argument.
4677  *
4678  * Leaf format strings are further subdivided into two categories:
4679  *
4680  *   - single non-null pointer ("nnp")
4681  *      these either collect or return a single non-null pointer.
4682  *
4683  *   - other
4684  *      these collect or return something else (bool, number, etc).
4685  *
4686  * Based on the above, the varargs handling code is split into 4 main parts:
4687  *
4688  *   - nnp handling code
4689  *   - leaf handling code (which may invoke nnp code)
4690  *   - generic handling code (may be recursive, may invoke leaf code)
4691  *   - user-facing API (which invokes the generic code)
4692  *
4693  * Each section implements some of the following functions:
4694  *
4695  *   - skip:
4696  *      collect the arguments for the format string as if
4697  *      g_variant_new() had been called, but do nothing with them.  used
4698  *      for skipping over arguments when constructing a Nothing maybe
4699  *      type.
4700  *
4701  *   - new:
4702  *      create a GVariant *
4703  *
4704  *   - get:
4705  *      unpack a GVariant *
4706  *
4707  *   - free (nnp only):
4708  *      free a previously allocated item
4709  */
4710
4711 static gboolean
4712 g_variant_format_string_is_leaf (const gchar *str)
4713 {
4714   return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4715 }
4716
4717 static gboolean
4718 g_variant_format_string_is_nnp (const gchar *str)
4719 {
4720   return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4721          str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4722          str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4723 }
4724
4725 /* Single non-null pointer ("nnp") {{{2 */
4726 static void
4727 g_variant_valist_free_nnp (const gchar *str,
4728                            gpointer     ptr)
4729 {
4730   switch (*str)
4731     {
4732     case 'a':
4733       g_variant_iter_free (ptr);
4734       break;
4735
4736     case '^':
4737       if (g_str_has_suffix (str, "y"))
4738         {
4739           if (str[2] != 'a') /* '^a&ay', '^ay' */
4740             g_free (ptr);
4741           else if (str[1] == 'a') /* '^aay' */
4742             g_strfreev (ptr);
4743           break; /* '^&ay' */
4744         }
4745       else if (str[2] != '&') /* '^as', '^ao' */
4746         g_strfreev (ptr);
4747       else                      /* '^a&s', '^a&o' */
4748         g_free (ptr);
4749       break;
4750
4751     case 's':
4752     case 'o':
4753     case 'g':
4754       g_free (ptr);
4755       break;
4756
4757     case '@':
4758     case '*':
4759     case '?':
4760     case 'v':
4761       g_variant_unref (ptr);
4762       break;
4763
4764     case '&':
4765       break;
4766
4767     default:
4768       g_assert_not_reached ();
4769     }
4770 }
4771
4772 static gchar
4773 g_variant_scan_convenience (const gchar **str,
4774                             gboolean     *constant,
4775                             guint        *arrays)
4776 {
4777   *constant = FALSE;
4778   *arrays = 0;
4779
4780   for (;;)
4781     {
4782       char c = *(*str)++;
4783
4784       if (c == '&')
4785         *constant = TRUE;
4786
4787       else if (c == 'a')
4788         (*arrays)++;
4789
4790       else
4791         return c;
4792     }
4793 }
4794
4795 static GVariant *
4796 g_variant_valist_new_nnp (const gchar **str,
4797                           gpointer      ptr)
4798 {
4799   if (**str == '&')
4800     (*str)++;
4801
4802   switch (*(*str)++)
4803     {
4804     case 'a':
4805       if (ptr != NULL)
4806         {
4807           const GVariantType *type;
4808           GVariant *value;
4809
4810           value = g_variant_builder_end (ptr);
4811           type = g_variant_get_type (value);
4812
4813           if G_UNLIKELY (!g_variant_type_is_array (type))
4814             g_error ("g_variant_new: expected array GVariantBuilder but "
4815                      "the built value has type '%s'",
4816                      g_variant_get_type_string (value));
4817
4818           type = g_variant_type_element (type);
4819
4820           if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4821             {
4822               gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4823               g_error ("g_variant_new: expected GVariantBuilder array element "
4824                        "type '%s' but the built value has element type '%s'",
4825                        type_string, g_variant_get_type_string (value) + 1);
4826               g_free (type_string);
4827             }
4828
4829           g_variant_type_string_scan (*str, NULL, str);
4830
4831           return value;
4832         }
4833       else
4834
4835         /* special case: NULL pointer for empty array */
4836         {
4837           const GVariantType *type = (GVariantType *) *str;
4838
4839           g_variant_type_string_scan (*str, NULL, str);
4840
4841           if G_UNLIKELY (!g_variant_type_is_definite (type))
4842             g_error ("g_variant_new: NULL pointer given with indefinite "
4843                      "array type; unable to determine which type of empty "
4844                      "array to construct.");
4845
4846           return g_variant_new_array (type, NULL, 0);
4847         }
4848
4849     case 's':
4850       {
4851         GVariant *value;
4852
4853         value = g_variant_new_string (ptr);
4854
4855         if (value == NULL)
4856           value = g_variant_new_string ("[Invalid UTF-8]");
4857
4858         return value;
4859       }
4860
4861     case 'o':
4862       return g_variant_new_object_path (ptr);
4863
4864     case 'g':
4865       return g_variant_new_signature (ptr);
4866
4867     case '^':
4868       {
4869         gboolean constant;
4870         guint arrays;
4871         gchar type;
4872
4873         type = g_variant_scan_convenience (str, &constant, &arrays);
4874
4875         if (type == 's')
4876           return g_variant_new_strv (ptr, -1);
4877
4878         if (type == 'o')
4879           return g_variant_new_objv (ptr, -1);
4880
4881         if (arrays > 1)
4882           return g_variant_new_bytestring_array (ptr, -1);
4883
4884         return g_variant_new_bytestring (ptr);
4885       }
4886
4887     case '@':
4888       if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4889         {
4890           gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4891           g_error ("g_variant_new: expected GVariant of type '%s' but "
4892                    "received value has type '%s'",
4893                    type_string, g_variant_get_type_string (ptr));
4894           g_free (type_string);
4895         }
4896
4897       g_variant_type_string_scan (*str, NULL, str);
4898
4899       return ptr;
4900
4901     case '*':
4902       return ptr;
4903
4904     case '?':
4905       if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4906         g_error ("g_variant_new: format string '?' expects basic-typed "
4907                  "GVariant, but received value has type '%s'",
4908                  g_variant_get_type_string (ptr));
4909
4910       return ptr;
4911
4912     case 'r':
4913       if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4914         g_error ("g_variant_new: format string 'r' expects tuple-typed "
4915                  "GVariant, but received value has type '%s'",
4916                  g_variant_get_type_string (ptr));
4917
4918       return ptr;
4919
4920     case 'v':
4921       return g_variant_new_variant (ptr);
4922
4923     default:
4924       g_assert_not_reached ();
4925     }
4926 }
4927
4928 static gpointer
4929 g_variant_valist_get_nnp (const gchar **str,
4930                           GVariant     *value)
4931 {
4932   switch (*(*str)++)
4933     {
4934     case 'a':
4935       g_variant_type_string_scan (*str, NULL, str);
4936       return g_variant_iter_new (value);
4937
4938     case '&':
4939       (*str)++;
4940       return (gchar *) g_variant_get_string (value, NULL);
4941
4942     case 's':
4943     case 'o':
4944     case 'g':
4945       return g_variant_dup_string (value, NULL);
4946
4947     case '^':
4948       {
4949         gboolean constant;
4950         guint arrays;
4951         gchar type;
4952
4953         type = g_variant_scan_convenience (str, &constant, &arrays);
4954
4955         if (type == 's')
4956           {
4957             if (constant)
4958               return g_variant_get_strv (value, NULL);
4959             else
4960               return g_variant_dup_strv (value, NULL);
4961           }
4962
4963         else if (type == 'o')
4964           {
4965             if (constant)
4966               return g_variant_get_objv (value, NULL);
4967             else
4968               return g_variant_dup_objv (value, NULL);
4969           }
4970
4971         else if (arrays > 1)
4972           {
4973             if (constant)
4974               return g_variant_get_bytestring_array (value, NULL);
4975             else
4976               return g_variant_dup_bytestring_array (value, NULL);
4977           }
4978
4979         else
4980           {
4981             if (constant)
4982               return (gchar *) g_variant_get_bytestring (value);
4983             else
4984               return g_variant_dup_bytestring (value, NULL);
4985           }
4986       }
4987
4988     case '@':
4989       g_variant_type_string_scan (*str, NULL, str);
4990       G_GNUC_FALLTHROUGH;
4991
4992     case '*':
4993     case '?':
4994     case 'r':
4995       return g_variant_ref (value);
4996
4997     case 'v':
4998       return g_variant_get_variant (value);
4999
5000     default:
5001       g_assert_not_reached ();
5002     }
5003 }
5004
5005 /* Leaves {{{2 */
5006 static void
5007 g_variant_valist_skip_leaf (const gchar **str,
5008                             va_list      *app)
5009 {
5010   if (g_variant_format_string_is_nnp (*str))
5011     {
5012       g_variant_format_string_scan (*str, NULL, str);
5013       va_arg (*app, gpointer);
5014       return;
5015     }
5016
5017   switch (*(*str)++)
5018     {
5019     case 'b':
5020     case 'y':
5021     case 'n':
5022     case 'q':
5023     case 'i':
5024     case 'u':
5025     case 'h':
5026       va_arg (*app, int);
5027       return;
5028
5029     case 'x':
5030     case 't':
5031       va_arg (*app, guint64);
5032       return;
5033
5034     case 'd':
5035       va_arg (*app, gdouble);
5036       return;
5037
5038     default:
5039       g_assert_not_reached ();
5040     }
5041 }
5042
5043 static GVariant *
5044 g_variant_valist_new_leaf (const gchar **str,
5045                            va_list      *app)
5046 {
5047   if (g_variant_format_string_is_nnp (*str))
5048     return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
5049
5050   switch (*(*str)++)
5051     {
5052     case 'b':
5053       return g_variant_new_boolean (va_arg (*app, gboolean));
5054
5055     case 'y':
5056       return g_variant_new_byte (va_arg (*app, guint));
5057
5058     case 'n':
5059       return g_variant_new_int16 (va_arg (*app, gint));
5060
5061     case 'q':
5062       return g_variant_new_uint16 (va_arg (*app, guint));
5063
5064     case 'i':
5065       return g_variant_new_int32 (va_arg (*app, gint));
5066
5067     case 'u':
5068       return g_variant_new_uint32 (va_arg (*app, guint));
5069
5070     case 'x':
5071       return g_variant_new_int64 (va_arg (*app, gint64));
5072
5073     case 't':
5074       return g_variant_new_uint64 (va_arg (*app, guint64));
5075
5076     case 'h':
5077       return g_variant_new_handle (va_arg (*app, gint));
5078
5079     case 'd':
5080       return g_variant_new_double (va_arg (*app, gdouble));
5081
5082     default:
5083       g_assert_not_reached ();
5084     }
5085 }
5086
5087 /* The code below assumes this */
5088 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5089 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5090
5091 static void
5092 g_variant_valist_get_leaf (const gchar **str,
5093                            GVariant     *value,
5094                            gboolean      free,
5095                            va_list      *app)
5096 {
5097   gpointer ptr = va_arg (*app, gpointer);
5098
5099   if (ptr == NULL)
5100     {
5101       g_variant_format_string_scan (*str, NULL, str);
5102       return;
5103     }
5104
5105   if (g_variant_format_string_is_nnp (*str))
5106     {
5107       gpointer *nnp = (gpointer *) ptr;
5108
5109       if (free && *nnp != NULL)
5110         g_variant_valist_free_nnp (*str, *nnp);
5111
5112       *nnp = NULL;
5113
5114       if (value != NULL)
5115         *nnp = g_variant_valist_get_nnp (str, value);
5116       else
5117         g_variant_format_string_scan (*str, NULL, str);
5118
5119       return;
5120     }
5121
5122   if (value != NULL)
5123     {
5124       switch (*(*str)++)
5125         {
5126         case 'b':
5127           *(gboolean *) ptr = g_variant_get_boolean (value);
5128           return;
5129
5130         case 'y':
5131           *(guint8 *) ptr = g_variant_get_byte (value);
5132           return;
5133
5134         case 'n':
5135           *(gint16 *) ptr = g_variant_get_int16 (value);
5136           return;
5137
5138         case 'q':
5139           *(guint16 *) ptr = g_variant_get_uint16 (value);
5140           return;
5141
5142         case 'i':
5143           *(gint32 *) ptr = g_variant_get_int32 (value);
5144           return;
5145
5146         case 'u':
5147           *(guint32 *) ptr = g_variant_get_uint32 (value);
5148           return;
5149
5150         case 'x':
5151           *(gint64 *) ptr = g_variant_get_int64 (value);
5152           return;
5153
5154         case 't':
5155           *(guint64 *) ptr = g_variant_get_uint64 (value);
5156           return;
5157
5158         case 'h':
5159           *(gint32 *) ptr = g_variant_get_handle (value);
5160           return;
5161
5162         case 'd':
5163           *(gdouble *) ptr = g_variant_get_double (value);
5164           return;
5165         }
5166     }
5167   else
5168     {
5169       switch (*(*str)++)
5170         {
5171         case 'y':
5172           *(guint8 *) ptr = 0;
5173           return;
5174
5175         case 'n':
5176         case 'q':
5177           *(guint16 *) ptr = 0;
5178           return;
5179
5180         case 'i':
5181         case 'u':
5182         case 'h':
5183         case 'b':
5184           *(guint32 *) ptr = 0;
5185           return;
5186
5187         case 'x':
5188         case 't':
5189         case 'd':
5190           *(guint64 *) ptr = 0;
5191           return;
5192         }
5193     }
5194
5195   g_assert_not_reached ();
5196 }
5197
5198 /* Generic (recursive) {{{2 */
5199 static void
5200 g_variant_valist_skip (const gchar **str,
5201                        va_list      *app)
5202 {
5203   if (g_variant_format_string_is_leaf (*str))
5204     g_variant_valist_skip_leaf (str, app);
5205
5206   else if (**str == 'm') /* maybe */
5207     {
5208       (*str)++;
5209
5210       if (!g_variant_format_string_is_nnp (*str))
5211         va_arg (*app, gboolean);
5212
5213       g_variant_valist_skip (str, app);
5214     }
5215   else /* tuple, dictionary entry */
5216     {
5217       g_assert (**str == '(' || **str == '{');
5218       (*str)++;
5219       while (**str != ')' && **str != '}')
5220         g_variant_valist_skip (str, app);
5221       (*str)++;
5222     }
5223 }
5224
5225 static GVariant *
5226 g_variant_valist_new (const gchar **str,
5227                       va_list      *app)
5228 {
5229   if (g_variant_format_string_is_leaf (*str))
5230     return g_variant_valist_new_leaf (str, app);
5231
5232   if (**str == 'm') /* maybe */
5233     {
5234       GVariantType *type = NULL;
5235       GVariant *value = NULL;
5236
5237       (*str)++;
5238
5239       if (g_variant_format_string_is_nnp (*str))
5240         {
5241           gpointer nnp = va_arg (*app, gpointer);
5242
5243           if (nnp != NULL)
5244             value = g_variant_valist_new_nnp (str, nnp);
5245           else
5246             type = g_variant_format_string_scan_type (*str, NULL, str);
5247         }
5248       else
5249         {
5250           gboolean just = va_arg (*app, gboolean);
5251
5252           if (just)
5253             value = g_variant_valist_new (str, app);
5254           else
5255             {
5256               type = g_variant_format_string_scan_type (*str, NULL, NULL);
5257               g_variant_valist_skip (str, app);
5258             }
5259         }
5260
5261       value = g_variant_new_maybe (type, value);
5262
5263       if (type != NULL)
5264         g_variant_type_free (type);
5265
5266       return value;
5267     }
5268   else /* tuple, dictionary entry */
5269     {
5270       GVariantBuilder b;
5271
5272       if (**str == '(')
5273         g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5274       else
5275         {
5276           g_assert (**str == '{');
5277           g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5278         }
5279
5280       (*str)++; /* '(' */
5281       while (**str != ')' && **str != '}')
5282         g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5283       (*str)++; /* ')' */
5284
5285       return g_variant_builder_end (&b);
5286     }
5287 }
5288
5289 static void
5290 g_variant_valist_get (const gchar **str,
5291                       GVariant     *value,
5292                       gboolean      free,
5293                       va_list      *app)
5294 {
5295   if (g_variant_format_string_is_leaf (*str))
5296     g_variant_valist_get_leaf (str, value, free, app);
5297
5298   else if (**str == 'm')
5299     {
5300       (*str)++;
5301
5302       if (value != NULL)
5303         value = g_variant_get_maybe (value);
5304
5305       if (!g_variant_format_string_is_nnp (*str))
5306         {
5307           gboolean *ptr = va_arg (*app, gboolean *);
5308
5309           if (ptr != NULL)
5310             *ptr = value != NULL;
5311         }
5312
5313       g_variant_valist_get (str, value, free, app);
5314
5315       if (value != NULL)
5316         g_variant_unref (value);
5317     }
5318
5319   else /* tuple, dictionary entry */
5320     {
5321       gint index = 0;
5322
5323       g_assert (**str == '(' || **str == '{');
5324
5325       (*str)++;
5326       while (**str != ')' && **str != '}')
5327         {
5328           if (value != NULL)
5329             {
5330               GVariant *child = g_variant_get_child_value (value, index++);
5331               g_variant_valist_get (str, child, free, app);
5332               g_variant_unref (child);
5333             }
5334           else
5335             g_variant_valist_get (str, NULL, free, app);
5336         }
5337       (*str)++;
5338     }
5339 }
5340
5341 /* User-facing API {{{2 */
5342 /**
5343  * g_variant_new: (skip)
5344  * @format_string: a #GVariant format string
5345  * @...: arguments, as per @format_string
5346  *
5347  * Creates a new #GVariant instance.
5348  *
5349  * Think of this function as an analogue to g_strdup_printf().
5350  *
5351  * The type of the created instance and the arguments that are expected
5352  * by this function are determined by @format_string. See the section on
5353  * [GVariant format strings][gvariant-format-strings]. Please note that
5354  * the syntax of the format string is very likely to be extended in the
5355  * future.
5356  *
5357  * The first character of the format string must not be '*' '?' '@' or
5358  * 'r'; in essence, a new #GVariant must always be constructed by this
5359  * function (and not merely passed through it unmodified).
5360  *
5361  * Note that the arguments must be of the correct width for their types
5362  * specified in @format_string. This can be achieved by casting them. See
5363  * the [GVariant varargs documentation][gvariant-varargs].
5364  *
5365  * |[<!-- language="C" -->
5366  * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5367  * const gchar *some_strings[] = { "a", "b", "c", NULL };
5368  * GVariant *new_variant;
5369  *
5370  * new_variant = g_variant_new ("(t^as)",
5371  *                              // This cast is required.
5372  *                              (guint64) some_flags,
5373  *                              some_strings);
5374  * ]|
5375  *
5376  * Returns: a new floating #GVariant instance
5377  *
5378  * Since: 2.24
5379  **/
5380 GVariant *
5381 g_variant_new (const gchar *format_string,
5382                ...)
5383 {
5384   GVariant *value;
5385   va_list ap;
5386
5387   g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5388                         format_string[0] != '?' && format_string[0] != '@' &&
5389                         format_string[0] != '*' && format_string[0] != 'r',
5390                         NULL);
5391
5392   va_start (ap, format_string);
5393   value = g_variant_new_va (format_string, NULL, &ap);
5394   va_end (ap);
5395
5396   return value;
5397 }
5398
5399 /**
5400  * g_variant_new_va: (skip)
5401  * @format_string: a string that is prefixed with a format string
5402  * @endptr: (nullable) (default NULL): location to store the end pointer,
5403  *          or %NULL
5404  * @app: a pointer to a #va_list
5405  *
5406  * This function is intended to be used by libraries based on
5407  * #GVariant that want to provide g_variant_new()-like functionality
5408  * to their users.
5409  *
5410  * The API is more general than g_variant_new() to allow a wider range
5411  * of possible uses.
5412  *
5413  * @format_string must still point to a valid format string, but it only
5414  * needs to be nul-terminated if @endptr is %NULL.  If @endptr is
5415  * non-%NULL then it is updated to point to the first character past the
5416  * end of the format string.
5417  *
5418  * @app is a pointer to a #va_list.  The arguments, according to
5419  * @format_string, are collected from this #va_list and the list is left
5420  * pointing to the argument following the last.
5421  *
5422  * Note that the arguments in @app must be of the correct width for their
5423  * types specified in @format_string when collected into the #va_list.
5424  * See the [GVariant varargs documentation][gvariant-varargs].
5425  *
5426  * These two generalisations allow mixing of multiple calls to
5427  * g_variant_new_va() and g_variant_get_va() within a single actual
5428  * varargs call by the user.
5429  *
5430  * The return value will be floating if it was a newly created GVariant
5431  * instance (for example, if the format string was "(ii)").  In the case
5432  * that the format_string was '*', '?', 'r', or a format starting with
5433  * '@' then the collected #GVariant pointer will be returned unmodified,
5434  * without adding any additional references.
5435  *
5436  * In order to behave correctly in all cases it is necessary for the
5437  * calling function to g_variant_ref_sink() the return result before
5438  * returning control to the user that originally provided the pointer.
5439  * At this point, the caller will have their own full reference to the
5440  * result.  This can also be done by adding the result to a container,
5441  * or by passing it to another g_variant_new() call.
5442  *
5443  * Returns: a new, usually floating, #GVariant
5444  *
5445  * Since: 2.24
5446  **/
5447 GVariant *
5448 g_variant_new_va (const gchar  *format_string,
5449                   const gchar **endptr,
5450                   va_list      *app)
5451 {
5452   GVariant *value;
5453
5454   g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5455                         NULL);
5456   g_return_val_if_fail (app != NULL, NULL);
5457
5458   value = g_variant_valist_new (&format_string, app);
5459
5460   if (endptr != NULL)
5461     *endptr = format_string;
5462
5463   return value;
5464 }
5465
5466 /**
5467  * g_variant_get: (skip)
5468  * @value: a #GVariant instance
5469  * @format_string: a #GVariant format string
5470  * @...: arguments, as per @format_string
5471  *
5472  * Deconstructs a #GVariant instance.
5473  *
5474  * Think of this function as an analogue to scanf().
5475  *
5476  * The arguments that are expected by this function are entirely
5477  * determined by @format_string.  @format_string also restricts the
5478  * permissible types of @value.  It is an error to give a value with
5479  * an incompatible type.  See the section on
5480  * [GVariant format strings][gvariant-format-strings].
5481  * Please note that the syntax of the format string is very likely to be
5482  * extended in the future.
5483  *
5484  * @format_string determines the C types that are used for unpacking
5485  * the values and also determines if the values are copied or borrowed,
5486  * see the section on
5487  * [GVariant format strings][gvariant-format-strings-pointers].
5488  *
5489  * Since: 2.24
5490  **/
5491 void
5492 g_variant_get (GVariant    *value,
5493                const gchar *format_string,
5494                ...)
5495 {
5496   va_list ap;
5497
5498   g_return_if_fail (value != NULL);
5499   g_return_if_fail (valid_format_string (format_string, TRUE, value));
5500
5501   /* if any direct-pointer-access formats are in use, flatten first */
5502   if (strchr (format_string, '&'))
5503     g_variant_get_data (value);
5504
5505   va_start (ap, format_string);
5506   g_variant_get_va (value, format_string, NULL, &ap);
5507   va_end (ap);
5508 }
5509
5510 /**
5511  * g_variant_get_va: (skip)
5512  * @value: a #GVariant
5513  * @format_string: a string that is prefixed with a format string
5514  * @endptr: (nullable) (default NULL): location to store the end pointer,
5515  *          or %NULL
5516  * @app: a pointer to a #va_list
5517  *
5518  * This function is intended to be used by libraries based on #GVariant
5519  * that want to provide g_variant_get()-like functionality to their
5520  * users.
5521  *
5522  * The API is more general than g_variant_get() to allow a wider range
5523  * of possible uses.
5524  *
5525  * @format_string must still point to a valid format string, but it only
5526  * need to be nul-terminated if @endptr is %NULL.  If @endptr is
5527  * non-%NULL then it is updated to point to the first character past the
5528  * end of the format string.
5529  *
5530  * @app is a pointer to a #va_list.  The arguments, according to
5531  * @format_string, are collected from this #va_list and the list is left
5532  * pointing to the argument following the last.
5533  *
5534  * These two generalisations allow mixing of multiple calls to
5535  * g_variant_new_va() and g_variant_get_va() within a single actual
5536  * varargs call by the user.
5537  *
5538  * @format_string determines the C types that are used for unpacking
5539  * the values and also determines if the values are copied or borrowed,
5540  * see the section on
5541  * [GVariant format strings][gvariant-format-strings-pointers].
5542  *
5543  * Since: 2.24
5544  **/
5545 void
5546 g_variant_get_va (GVariant     *value,
5547                   const gchar  *format_string,
5548                   const gchar **endptr,
5549                   va_list      *app)
5550 {
5551   g_return_if_fail (valid_format_string (format_string, !endptr, value));
5552   g_return_if_fail (value != NULL);
5553   g_return_if_fail (app != NULL);
5554
5555   /* if any direct-pointer-access formats are in use, flatten first */
5556   if (strchr (format_string, '&'))
5557     g_variant_get_data (value);
5558
5559   g_variant_valist_get (&format_string, value, FALSE, app);
5560
5561   if (endptr != NULL)
5562     *endptr = format_string;
5563 }
5564
5565 /* Varargs-enabled Utility Functions {{{1 */
5566
5567 /**
5568  * g_variant_builder_add: (skip)
5569  * @builder: a #GVariantBuilder
5570  * @format_string: a #GVariant varargs format string
5571  * @...: arguments, as per @format_string
5572  *
5573  * Adds to a #GVariantBuilder.
5574  *
5575  * This call is a convenience wrapper that is exactly equivalent to
5576  * calling g_variant_new() followed by g_variant_builder_add_value().
5577  *
5578  * Note that the arguments must be of the correct width for their types
5579  * specified in @format_string. This can be achieved by casting them. See
5580  * the [GVariant varargs documentation][gvariant-varargs].
5581  *
5582  * This function might be used as follows:
5583  *
5584  * |[<!-- language="C" --> 
5585  * GVariant *
5586  * make_pointless_dictionary (void)
5587  * {
5588  *   GVariantBuilder builder;
5589  *   int i;
5590  *
5591  *   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5592  *   for (i = 0; i < 16; i++)
5593  *     {
5594  *       gchar buf[3];
5595  *
5596  *       sprintf (buf, "%d", i);
5597  *       g_variant_builder_add (&builder, "{is}", i, buf);
5598  *     }
5599  *
5600  *   return g_variant_builder_end (&builder);
5601  * }
5602  * ]|
5603  *
5604  * Since: 2.24
5605  */
5606 void
5607 g_variant_builder_add (GVariantBuilder *builder,
5608                        const gchar     *format_string,
5609                        ...)
5610 {
5611   GVariant *variant;
5612   va_list ap;
5613
5614   va_start (ap, format_string);
5615   variant = g_variant_new_va (format_string, NULL, &ap);
5616   va_end (ap);
5617
5618   g_variant_builder_add_value (builder, variant);
5619 }
5620
5621 /**
5622  * g_variant_get_child: (skip)
5623  * @value: a container #GVariant
5624  * @index_: the index of the child to deconstruct
5625  * @format_string: a #GVariant format string
5626  * @...: arguments, as per @format_string
5627  *
5628  * Reads a child item out of a container #GVariant instance and
5629  * deconstructs it according to @format_string.  This call is
5630  * essentially a combination of g_variant_get_child_value() and
5631  * g_variant_get().
5632  *
5633  * @format_string determines the C types that are used for unpacking
5634  * the values and also determines if the values are copied or borrowed,
5635  * see the section on
5636  * [GVariant format strings][gvariant-format-strings-pointers].
5637  *
5638  * Since: 2.24
5639  **/
5640 void
5641 g_variant_get_child (GVariant    *value,
5642                      gsize        index_,
5643                      const gchar *format_string,
5644                      ...)
5645 {
5646   GVariant *child;
5647   va_list ap;
5648
5649   /* if any direct-pointer-access formats are in use, flatten first */
5650   if (strchr (format_string, '&'))
5651     g_variant_get_data (value);
5652
5653   child = g_variant_get_child_value (value, index_);
5654   g_return_if_fail (valid_format_string (format_string, TRUE, child));
5655
5656   va_start (ap, format_string);
5657   g_variant_get_va (child, format_string, NULL, &ap);
5658   va_end (ap);
5659
5660   g_variant_unref (child);
5661 }
5662
5663 /**
5664  * g_variant_iter_next: (skip)
5665  * @iter: a #GVariantIter
5666  * @format_string: a GVariant format string
5667  * @...: the arguments to unpack the value into
5668  *
5669  * Gets the next item in the container and unpacks it into the variable
5670  * argument list according to @format_string, returning %TRUE.
5671  *
5672  * If no more items remain then %FALSE is returned.
5673  *
5674  * All of the pointers given on the variable arguments list of this
5675  * function are assumed to point at uninitialised memory.  It is the
5676  * responsibility of the caller to free all of the values returned by
5677  * the unpacking process.
5678  *
5679  * Here is an example for memory management with g_variant_iter_next():
5680  * |[<!-- language="C" --> 
5681  *   // Iterates a dictionary of type 'a{sv}'
5682  *   void
5683  *   iterate_dictionary (GVariant *dictionary)
5684  *   {
5685  *     GVariantIter iter;
5686  *     GVariant *value;
5687  *     gchar *key;
5688  *
5689  *     g_variant_iter_init (&iter, dictionary);
5690  *     while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5691  *       {
5692  *         g_print ("Item '%s' has type '%s'\n", key,
5693  *                  g_variant_get_type_string (value));
5694  *
5695  *         // must free data for ourselves
5696  *         g_variant_unref (value);
5697  *         g_free (key);
5698  *       }
5699  *   }
5700  * ]|
5701  *
5702  * For a solution that is likely to be more convenient to C programmers
5703  * when dealing with loops, see g_variant_iter_loop().
5704  *
5705  * @format_string determines the C types that are used for unpacking
5706  * the values and also determines if the values are copied or borrowed.
5707  *
5708  * See the section on
5709  * [GVariant format strings][gvariant-format-strings-pointers].
5710  *
5711  * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5712  *
5713  * Since: 2.24
5714  **/
5715 gboolean
5716 g_variant_iter_next (GVariantIter *iter,
5717                      const gchar  *format_string,
5718                      ...)
5719 {
5720   GVariant *value;
5721
5722   value = g_variant_iter_next_value (iter);
5723
5724   g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5725                         FALSE);
5726
5727   if (value != NULL)
5728     {
5729       va_list ap;
5730
5731       va_start (ap, format_string);
5732       g_variant_valist_get (&format_string, value, FALSE, &ap);
5733       va_end (ap);
5734
5735       g_variant_unref (value);
5736     }
5737
5738   return value != NULL;
5739 }
5740
5741 /**
5742  * g_variant_iter_loop: (skip)
5743  * @iter: a #GVariantIter
5744  * @format_string: a GVariant format string
5745  * @...: the arguments to unpack the value into
5746  *
5747  * Gets the next item in the container and unpacks it into the variable
5748  * argument list according to @format_string, returning %TRUE.
5749  *
5750  * If no more items remain then %FALSE is returned.
5751  *
5752  * On the first call to this function, the pointers appearing on the
5753  * variable argument list are assumed to point at uninitialised memory.
5754  * On the second and later calls, it is assumed that the same pointers
5755  * will be given and that they will point to the memory as set by the
5756  * previous call to this function.  This allows the previous values to
5757  * be freed, as appropriate.
5758  *
5759  * This function is intended to be used with a while loop as
5760  * demonstrated in the following example.  This function can only be
5761  * used when iterating over an array.  It is only valid to call this
5762  * function with a string constant for the format string and the same
5763  * string constant must be used each time.  Mixing calls to this
5764  * function and g_variant_iter_next() or g_variant_iter_next_value() on
5765  * the same iterator causes undefined behavior.
5766  *
5767  * If you break out of a such a while loop using g_variant_iter_loop() then
5768  * you must free or unreference all the unpacked values as you would with
5769  * g_variant_get(). Failure to do so will cause a memory leak.
5770  *
5771  * Here is an example for memory management with g_variant_iter_loop():
5772  * |[<!-- language="C" --> 
5773  *   // Iterates a dictionary of type 'a{sv}'
5774  *   void
5775  *   iterate_dictionary (GVariant *dictionary)
5776  *   {
5777  *     GVariantIter iter;
5778  *     GVariant *value;
5779  *     gchar *key;
5780  *
5781  *     g_variant_iter_init (&iter, dictionary);
5782  *     while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5783  *       {
5784  *         g_print ("Item '%s' has type '%s'\n", key,
5785  *                  g_variant_get_type_string (value));
5786  *
5787  *         // no need to free 'key' and 'value' here
5788  *         // unless breaking out of this loop
5789  *       }
5790  *   }
5791  * ]|
5792  *
5793  * For most cases you should use g_variant_iter_next().
5794  *
5795  * This function is really only useful when unpacking into #GVariant or
5796  * #GVariantIter in order to allow you to skip the call to
5797  * g_variant_unref() or g_variant_iter_free().
5798  *
5799  * For example, if you are only looping over simple integer and string
5800  * types, g_variant_iter_next() is definitely preferred.  For string
5801  * types, use the '&' prefix to avoid allocating any memory at all (and
5802  * thereby avoiding the need to free anything as well).
5803  *
5804  * @format_string determines the C types that are used for unpacking
5805  * the values and also determines if the values are copied or borrowed.
5806  *
5807  * See the section on
5808  * [GVariant format strings][gvariant-format-strings-pointers].
5809  *
5810  * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5811  *          value
5812  *
5813  * Since: 2.24
5814  **/
5815 gboolean
5816 g_variant_iter_loop (GVariantIter *iter,
5817                      const gchar  *format_string,
5818                      ...)
5819 {
5820   gboolean first_time = GVSI(iter)->loop_format == NULL;
5821   GVariant *value;
5822   va_list ap;
5823
5824   g_return_val_if_fail (first_time ||
5825                         format_string == GVSI(iter)->loop_format,
5826                         FALSE);
5827
5828   if (first_time)
5829     {
5830       TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5831       GVSI(iter)->loop_format = format_string;
5832
5833       if (strchr (format_string, '&'))
5834         g_variant_get_data (GVSI(iter)->value);
5835     }
5836
5837   value = g_variant_iter_next_value (iter);
5838
5839   g_return_val_if_fail (!first_time ||
5840                         valid_format_string (format_string, TRUE, value),
5841                         FALSE);
5842
5843   va_start (ap, format_string);
5844   g_variant_valist_get (&format_string, value, !first_time, &ap);
5845   va_end (ap);
5846
5847   if (value != NULL)
5848     g_variant_unref (value);
5849
5850   return value != NULL;
5851 }
5852
5853 /* Serialized data {{{1 */
5854 static GVariant *
5855 g_variant_deep_copy (GVariant *value)
5856 {
5857   switch (g_variant_classify (value))
5858     {
5859     case G_VARIANT_CLASS_MAYBE:
5860     case G_VARIANT_CLASS_ARRAY:
5861     case G_VARIANT_CLASS_TUPLE:
5862     case G_VARIANT_CLASS_DICT_ENTRY:
5863     case G_VARIANT_CLASS_VARIANT:
5864       {
5865         GVariantBuilder builder;
5866         GVariantIter iter;
5867         GVariant *child;
5868
5869         g_variant_builder_init (&builder, g_variant_get_type (value));
5870         g_variant_iter_init (&iter, value);
5871
5872         while ((child = g_variant_iter_next_value (&iter)))
5873           {
5874             g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
5875             g_variant_unref (child);
5876           }
5877
5878         return g_variant_builder_end (&builder);
5879       }
5880
5881     case G_VARIANT_CLASS_BOOLEAN:
5882       return g_variant_new_boolean (g_variant_get_boolean (value));
5883
5884     case G_VARIANT_CLASS_BYTE:
5885       return g_variant_new_byte (g_variant_get_byte (value));
5886
5887     case G_VARIANT_CLASS_INT16:
5888       return g_variant_new_int16 (g_variant_get_int16 (value));
5889
5890     case G_VARIANT_CLASS_UINT16:
5891       return g_variant_new_uint16 (g_variant_get_uint16 (value));
5892
5893     case G_VARIANT_CLASS_INT32:
5894       return g_variant_new_int32 (g_variant_get_int32 (value));
5895
5896     case G_VARIANT_CLASS_UINT32:
5897       return g_variant_new_uint32 (g_variant_get_uint32 (value));
5898
5899     case G_VARIANT_CLASS_INT64:
5900       return g_variant_new_int64 (g_variant_get_int64 (value));
5901
5902     case G_VARIANT_CLASS_UINT64:
5903       return g_variant_new_uint64 (g_variant_get_uint64 (value));
5904
5905     case G_VARIANT_CLASS_HANDLE:
5906       return g_variant_new_handle (g_variant_get_handle (value));
5907
5908     case G_VARIANT_CLASS_DOUBLE:
5909       return g_variant_new_double (g_variant_get_double (value));
5910
5911     case G_VARIANT_CLASS_STRING:
5912       return g_variant_new_string (g_variant_get_string (value, NULL));
5913
5914     case G_VARIANT_CLASS_OBJECT_PATH:
5915       return g_variant_new_object_path (g_variant_get_string (value, NULL));
5916
5917     case G_VARIANT_CLASS_SIGNATURE:
5918       return g_variant_new_signature (g_variant_get_string (value, NULL));
5919     }
5920
5921   g_assert_not_reached ();
5922 }
5923
5924 /**
5925  * g_variant_get_normal_form:
5926  * @value: a #GVariant
5927  *
5928  * Gets a #GVariant instance that has the same value as @value and is
5929  * trusted to be in normal form.
5930  *
5931  * If @value is already trusted to be in normal form then a new
5932  * reference to @value is returned.
5933  *
5934  * If @value is not already trusted, then it is scanned to check if it
5935  * is in normal form.  If it is found to be in normal form then it is
5936  * marked as trusted and a new reference to it is returned.
5937  *
5938  * If @value is found not to be in normal form then a new trusted
5939  * #GVariant is created with the same value as @value.
5940  *
5941  * It makes sense to call this function if you've received #GVariant
5942  * data from untrusted sources and you want to ensure your serialized
5943  * output is definitely in normal form.
5944  *
5945  * If @value is already in normal form, a new reference will be returned
5946  * (which will be floating if @value is floating). If it is not in normal form,
5947  * the newly created #GVariant will be returned with a single non-floating
5948  * reference. Typically, g_variant_take_ref() should be called on the return
5949  * value from this function to guarantee ownership of a single non-floating
5950  * reference to it.
5951  *
5952  * Returns: (transfer full): a trusted #GVariant
5953  *
5954  * Since: 2.24
5955  **/
5956 GVariant *
5957 g_variant_get_normal_form (GVariant *value)
5958 {
5959   GVariant *trusted;
5960
5961   if (g_variant_is_normal_form (value))
5962     return g_variant_ref (value);
5963
5964   trusted = g_variant_deep_copy (value);
5965   g_assert (g_variant_is_trusted (trusted));
5966
5967   return g_variant_ref_sink (trusted);
5968 }
5969
5970 /**
5971  * g_variant_byteswap:
5972  * @value: a #GVariant
5973  *
5974  * Performs a byteswapping operation on the contents of @value.  The
5975  * result is that all multi-byte numeric data contained in @value is
5976  * byteswapped.  That includes 16, 32, and 64bit signed and unsigned
5977  * integers as well as file handles and double precision floating point
5978  * values.
5979  *
5980  * This function is an identity mapping on any value that does not
5981  * contain multi-byte numeric data.  That include strings, booleans,
5982  * bytes and containers containing only these things (recursively).
5983  *
5984  * The returned value is always in normal form and is marked as trusted.
5985  *
5986  * Returns: (transfer full): the byteswapped form of @value
5987  *
5988  * Since: 2.24
5989  **/
5990 GVariant *
5991 g_variant_byteswap (GVariant *value)
5992 {
5993   GVariantTypeInfo *type_info;
5994   guint alignment;
5995   GVariant *new;
5996
5997   type_info = g_variant_get_type_info (value);
5998
5999   g_variant_type_info_query (type_info, &alignment, NULL);
6000
6001   if (alignment)
6002     /* (potentially) contains multi-byte numeric data */
6003     {
6004       GVariantSerialised serialised;
6005       GVariant *trusted;
6006       GBytes *bytes;
6007
6008       trusted = g_variant_get_normal_form (value);
6009       serialised.type_info = g_variant_get_type_info (trusted);
6010       serialised.size = g_variant_get_size (trusted);
6011       serialised.data = g_malloc (serialised.size);
6012       serialised.depth = g_variant_get_depth (trusted);
6013       g_variant_store (trusted, serialised.data);
6014       g_variant_unref (trusted);
6015
6016       g_variant_serialised_byteswap (serialised);
6017
6018       bytes = g_bytes_new_take (serialised.data, serialised.size);
6019       new = g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE);
6020       g_bytes_unref (bytes);
6021     }
6022   else
6023     /* contains no multi-byte data */
6024     new = value;
6025
6026   return g_variant_ref_sink (new);
6027 }
6028
6029 /**
6030  * g_variant_new_from_data:
6031  * @type: a definite #GVariantType
6032  * @data: (array length=size) (element-type guint8): the serialized data
6033  * @size: the size of @data
6034  * @trusted: %TRUE if @data is definitely in normal form
6035  * @notify: (scope async): function to call when @data is no longer needed
6036  * @user_data: data for @notify
6037  *
6038  * Creates a new #GVariant instance from serialized data.
6039  *
6040  * @type is the type of #GVariant instance that will be constructed.
6041  * The interpretation of @data depends on knowing the type.
6042  *
6043  * @data is not modified by this function and must remain valid with an
6044  * unchanging value until such a time as @notify is called with
6045  * @user_data.  If the contents of @data change before that time then
6046  * the result is undefined.
6047  *
6048  * If @data is trusted to be serialized data in normal form then
6049  * @trusted should be %TRUE.  This applies to serialized data created
6050  * within this process or read from a trusted location on the disk (such
6051  * as a file installed in /usr/lib alongside your application).  You
6052  * should set trusted to %FALSE if @data is read from the network, a
6053  * file in the user's home directory, etc.
6054  *
6055  * If @data was not stored in this machine's native endianness, any multi-byte
6056  * numeric values in the returned variant will also be in non-native
6057  * endianness. g_variant_byteswap() can be used to recover the original values.
6058  *
6059  * @notify will be called with @user_data when @data is no longer
6060  * needed.  The exact time of this call is unspecified and might even be
6061  * before this function returns.
6062  *
6063  * Note: @data must be backed by memory that is aligned appropriately for the
6064  * @type being loaded. Otherwise this function will internally create a copy of
6065  * the memory (since GLib 2.60) or (in older versions) fail and exit the
6066  * process.
6067  *
6068  * Returns: (transfer none): a new floating #GVariant of type @type
6069  *
6070  * Since: 2.24
6071  **/
6072 GVariant *
6073 g_variant_new_from_data (const GVariantType *type,
6074                          gconstpointer       data,
6075                          gsize               size,
6076                          gboolean            trusted,
6077                          GDestroyNotify      notify,
6078                          gpointer            user_data)
6079 {
6080   GVariant *value;
6081   GBytes *bytes;
6082
6083   g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6084   g_return_val_if_fail (data != NULL || size == 0, NULL);
6085
6086   if (notify)
6087     bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6088   else
6089     bytes = g_bytes_new_static (data, size);
6090
6091   value = g_variant_new_from_bytes (type, bytes, trusted);
6092   g_bytes_unref (bytes);
6093
6094   return value;
6095 }
6096
6097 /* Epilogue {{{1 */
6098 /* vim:set foldmethod=marker: */