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