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