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