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