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