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