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