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