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