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