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