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