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