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