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