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