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