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