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