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