Add g_variant_compare() for like basic types
[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 C nul-terminated string
961  * @returns: a new string #GVariant instance
962  *
963  * Creates a string #GVariant with the contents of @string.
964  *
965  * Since: 2.24
966  **/
967 GVariant *
968 g_variant_new_string (const gchar *string)
969 {
970   g_return_val_if_fail (string != NULL, NULL);
971
972   return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
973                                      string, strlen (string) + 1);
974 }
975
976 /**
977  * g_variant_new_object_path:
978  * @object_path: a normal C nul-terminated string
979  * @returns: a new object path #GVariant instance
980  *
981  * Creates a DBus object path #GVariant with the contents of @string.
982  * @string must be a valid DBus object path.  Use
983  * g_variant_is_object_path() if you're not sure.
984  *
985  * Since: 2.24
986  **/
987 GVariant *
988 g_variant_new_object_path (const gchar *object_path)
989 {
990   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
991
992   return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
993                                      object_path, strlen (object_path) + 1);
994 }
995
996 /**
997  * g_variant_is_object_path:
998  * @string: a normal C nul-terminated string
999  * @returns: %TRUE if @string is a DBus object path
1000  *
1001  * Determines if a given string is a valid DBus object path.  You
1002  * should ensure that a string is a valid DBus object path before
1003  * passing it to g_variant_new_object_path().
1004  *
1005  * A valid object path starts with '/' followed by zero or more
1006  * sequences of characters separated by '/' characters.  Each sequence
1007  * must contain only the characters "[A-Z][a-z][0-9]_".  No sequence
1008  * (including the one following the final '/' character) may be empty.
1009  *
1010  * Since: 2.24
1011  **/
1012 gboolean
1013 g_variant_is_object_path (const gchar *string)
1014 {
1015   g_return_val_if_fail (string != NULL, FALSE);
1016
1017   return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1018 }
1019
1020 /**
1021  * g_variant_new_signature:
1022  * @signature: a normal C nul-terminated string
1023  * @returns: a new signature #GVariant instance
1024  *
1025  * Creates a DBus type signature #GVariant with the contents of
1026  * @string.  @string must be a valid DBus type signature.  Use
1027  * g_variant_is_signature() if you're not sure.
1028  *
1029  * Since: 2.24
1030  **/
1031 GVariant *
1032 g_variant_new_signature (const gchar *signature)
1033 {
1034   g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1035
1036   return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1037                                      signature, strlen (signature) + 1);
1038 }
1039
1040 /**
1041  * g_variant_is_signature:
1042  * @string: a normal C nul-terminated string
1043  * @returns: %TRUE if @string is a DBus type signature
1044  *
1045  * Determines if a given string is a valid DBus type signature.  You
1046  * should ensure that a string is a valid DBus object path before
1047  * passing it to g_variant_new_signature().
1048  *
1049  * DBus type signatures consist of zero or more definite #GVariantType
1050  * strings in sequence.
1051  *
1052  * Since: 2.24
1053  **/
1054 gboolean
1055 g_variant_is_signature (const gchar *string)
1056 {
1057   g_return_val_if_fail (string != NULL, FALSE);
1058
1059   return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1060 }
1061
1062 /**
1063  * g_variant_get_string:
1064  * @value: a string #GVariant instance
1065  * @length: a pointer to a #gsize, to store the length
1066  * @returns: the constant string
1067  *
1068  * Returns the string value of a #GVariant instance with a string
1069  * type.  This includes the types %G_VARIANT_TYPE_STRING,
1070  * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1071  *
1072  * If @length is non-%NULL then the length of the string (in bytes) is
1073  * returned there.  For trusted values, this information is already
1074  * known.  For untrusted values, a strlen() will be performed.
1075  *
1076  * It is an error to call this function with a @value of any type
1077  * other than those three.
1078  *
1079  * The return value remains valid as long as @value exists.
1080  *
1081  * Since: 2.24
1082  **/
1083 const gchar *
1084 g_variant_get_string (GVariant *value,
1085                       gsize    *length)
1086 {
1087   gconstpointer data;
1088   gsize size;
1089
1090   g_return_val_if_fail (value != NULL, NULL);
1091   g_return_val_if_fail (
1092     g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1093     g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1094     g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1095
1096   data = g_variant_get_data (value);
1097   size = g_variant_get_size (value);
1098
1099   if (!g_variant_is_trusted (value))
1100     {
1101       switch (g_variant_classify (value))
1102         {
1103         case G_VARIANT_CLASS_STRING:
1104           if (g_variant_serialiser_is_string (data, size))
1105             break;
1106
1107           data = "";
1108           size = 1;
1109           break;
1110
1111         case G_VARIANT_CLASS_OBJECT_PATH:
1112           if (g_variant_serialiser_is_object_path (data, size))
1113             break;
1114
1115           data = "/";
1116           size = 2;
1117           break;
1118
1119         case G_VARIANT_CLASS_SIGNATURE:
1120           if (g_variant_serialiser_is_signature (data, size))
1121             break;
1122
1123           data = "";
1124           size = 1;
1125           break;
1126
1127         default:
1128           g_assert_not_reached ();
1129         }
1130     }
1131
1132   if (length)
1133     *length = size - 1;
1134
1135   return data;
1136 }
1137
1138 /**
1139  * g_variant_dup_string:
1140  * @value: a string #GVariant instance
1141  * @length: a pointer to a #gsize, to store the length
1142  * @returns: a newly allocated string
1143  *
1144  * Similar to g_variant_get_string() except that instead of returning
1145  * a constant string, the string is duplicated.
1146  *
1147  * The return value must be freed using g_free().
1148  *
1149  * Since: 2.24
1150  **/
1151 gchar *
1152 g_variant_dup_string (GVariant *value,
1153                       gsize    *length)
1154 {
1155   return g_strdup (g_variant_get_string (value, length));
1156 }
1157
1158 /**
1159  * g_variant_new_strv:
1160  * @strv: an array of strings
1161  * @length: the length of @strv, or -1
1162  * @returns: a new floating #GVariant instance
1163  *
1164  * Constructs an array of strings #GVariant from the given array of
1165  * strings.
1166  *
1167  * If @length is not -1 then it gives the maximum length of @strv.  In
1168  * any case, a %NULL pointer in @strv is taken as a terminator.
1169  *
1170  * Since: 2.24
1171  **/
1172 GVariant *
1173 g_variant_new_strv (const gchar * const *strv,
1174                     gssize               length)
1175 {
1176   GVariant **strings;
1177   gsize i;
1178
1179   g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1180
1181   if (length < 0)
1182     length = g_strv_length ((gchar **) strv);
1183
1184   strings = g_new (GVariant *, length);
1185   for (i = 0; i < length; i++)
1186     strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1187
1188   return g_variant_new_from_children (G_VARIANT_TYPE ("as"),
1189                                       strings, length, TRUE);
1190 }
1191
1192 /**
1193  * g_variant_get_strv:
1194  * @value: an array of strings #GVariant
1195  * @length: the length of the result, or %NULL
1196  * @returns: an array of constant strings
1197  *
1198  * Gets the contents of an array of strings #GVariant.  This call
1199  * makes a shallow copy; the return result should be released with
1200  * g_free(), but the individual strings must not be modified.
1201  *
1202  * If @length is non-%NULL then the number of elements in the result
1203  * is stored there.  In any case, the resulting array will be
1204  * %NULL-terminated.
1205  *
1206  * For an empty array, @length will be set to 0 and a pointer to a
1207  * %NULL pointer will be returned.
1208  *
1209  * Since: 2.24
1210  **/
1211 const gchar **
1212 g_variant_get_strv (GVariant *value,
1213                     gsize    *length)
1214 {
1215   const gchar **strv;
1216   gsize n;
1217   gsize i;
1218
1219   g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1220                         g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1221                         g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1222                         NULL);
1223
1224   g_variant_get_data (value);
1225   n = g_variant_n_children (value);
1226   strv = g_new (const gchar *, n + 1);
1227
1228   for (i = 0; i < n; i++)
1229     {
1230       GVariant *string;
1231
1232       string = g_variant_get_child_value (value, i);
1233       strv[i] = g_variant_get_string (string, NULL);
1234       g_variant_unref (string);
1235     }
1236   strv[i] = NULL;
1237
1238   if (length)
1239     *length = n;
1240
1241   return strv;
1242 }
1243
1244 /**
1245  * g_variant_dup_strv:
1246  * @value: an array of strings #GVariant
1247  * @length: the length of the result, or %NULL
1248  * @returns: an array of constant strings
1249  *
1250  * Gets the contents of an array of strings #GVariant.  This call
1251  * makes a deep copy; the return result should be released with
1252  * g_strfreev().
1253  *
1254  * If @length is non-%NULL then the number of elements in the result
1255  * is stored there.  In any case, the resulting array will be
1256  * %NULL-terminated.
1257  *
1258  * For an empty array, @length will be set to 0 and a pointer to a
1259  * %NULL pointer will be returned.
1260  *
1261  * Since: 2.24
1262  **/
1263 gchar **
1264 g_variant_dup_strv (GVariant *value,
1265                     gsize    *length)
1266 {
1267   gchar **strv;
1268   gsize n;
1269   gsize i;
1270
1271   g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1272                         g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1273                         g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1274                         NULL);
1275
1276   n = g_variant_n_children (value);
1277   strv = g_new (gchar *, n + 1);
1278
1279   for (i = 0; i < n; i++)
1280     {
1281       GVariant *string;
1282
1283       string = g_variant_get_child_value (value, i);
1284       strv[i] = g_variant_dup_string (string, NULL);
1285       g_variant_unref (string);
1286     }
1287   strv[i] = NULL;
1288
1289   if (length)
1290     *length = n;
1291
1292   return strv;
1293 }
1294
1295 /* Type checking and querying {{{1 */
1296 /**
1297  * g_variant_get_type:
1298  * @value: a #GVariant
1299  * @returns: a #GVariantType
1300  *
1301  * Determines the type of @value.
1302  *
1303  * The return value is valid for the lifetime of @value and must not
1304  * be freed.
1305  *
1306  * Since: 2.24
1307  **/
1308 const GVariantType *
1309 g_variant_get_type (GVariant *value)
1310 {
1311   GVariantTypeInfo *type_info;
1312
1313   g_return_val_if_fail (value != NULL, NULL);
1314
1315   type_info = g_variant_get_type_info (value);
1316
1317   return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1318 }
1319
1320 /**
1321  * g_variant_get_type_string:
1322  * @value: a #GVariant
1323  * @returns: the type string for the type of @value
1324  *
1325  * Returns the type string of @value.  Unlike the result of calling
1326  * g_variant_type_peek_string(), this string is nul-terminated.  This
1327  * string belongs to #GVariant and must not be freed.
1328  *
1329  * Since: 2.24
1330  **/
1331 const gchar *
1332 g_variant_get_type_string (GVariant *value)
1333 {
1334   GVariantTypeInfo *type_info;
1335
1336   g_return_val_if_fail (value != NULL, NULL);
1337
1338   type_info = g_variant_get_type_info (value);
1339
1340   return g_variant_type_info_get_type_string (type_info);
1341 }
1342
1343 /**
1344  * g_variant_is_of_type:
1345  * @value: a #GVariant instance
1346  * @type: a #GVariantType
1347  * @returns: %TRUE if the type of @value matches @type
1348  *
1349  * Checks if a value has a type matching the provided type.
1350  *
1351  * Since: 2.24
1352  **/
1353 gboolean
1354 g_variant_is_of_type (GVariant           *value,
1355                       const GVariantType *type)
1356 {
1357   return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1358 }
1359
1360 /**
1361  * g_variant_is_container:
1362  * @value: a #GVariant instance
1363  * @returns: %TRUE if @value is a container
1364  *
1365  * Checks if @value is a container.
1366  */
1367 gboolean
1368 g_variant_is_container (GVariant *value)
1369 {
1370   return g_variant_type_is_container (g_variant_get_type (value));
1371 }
1372
1373
1374 /**
1375  * g_variant_classify:
1376  * @value: a #GVariant
1377  * @returns: the #GVariantClass of @value
1378  *
1379  * Classifies @value according to its top-level type.
1380  *
1381  * Since: 2.24
1382  **/
1383 /**
1384  * GVariantClass:
1385  * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
1386  * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
1387  * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
1388  * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
1389  * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
1390  * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
1391  * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
1392  * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
1393  * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
1394  * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating 
1395  *                          point value.
1396  * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
1397  * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a DBus object path 
1398  *                               string.
1399  * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a DBus signature string.
1400  * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
1401  * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
1402  * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
1403  * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
1404  * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
1405  *
1406  * The range of possible top-level types of #GVariant instances.
1407  *
1408  * Since: 2.24
1409  **/
1410 GVariantClass
1411 g_variant_classify (GVariant *value)
1412 {
1413   g_return_val_if_fail (value != NULL, 0);
1414
1415   return *g_variant_get_type_string (value);
1416 }
1417
1418 /* Pretty printer {{{1 */
1419 /**
1420  * g_variant_print_string:
1421  * @value: a #GVariant
1422  * @string: a #GString, or %NULL
1423  * @type_annotate: %TRUE if type information should be included in
1424  *                 the output
1425  * @returns: a #GString containing the string
1426  *
1427  * Behaves as g_variant_print(), but operates on a #GString.
1428  *
1429  * If @string is non-%NULL then it is appended to and returned.  Else,
1430  * a new empty #GString is allocated and it is returned.
1431  *
1432  * Since: 2.24
1433  **/
1434 GString *
1435 g_variant_print_string (GVariant *value,
1436                         GString  *string,
1437                         gboolean  type_annotate)
1438 {
1439   if G_UNLIKELY (string == NULL)
1440     string = g_string_new (NULL);
1441
1442   switch (g_variant_classify (value))
1443     {
1444     case G_VARIANT_CLASS_MAYBE:
1445       if (type_annotate)
1446         g_string_append_printf (string, "@%s ",
1447                                 g_variant_get_type_string (value));
1448
1449       if (g_variant_n_children (value))
1450         {
1451           gchar *printed_child;
1452           GVariant *element;
1453
1454           /* Nested maybes:
1455            *
1456            * Consider the case of the type "mmi".  In this case we could
1457            * write "just just 4", but "4" alone is totally unambiguous,
1458            * so we try to drop "just" where possible.
1459            *
1460            * We have to be careful not to always drop "just", though,
1461            * since "nothing" needs to be distinguishable from "just
1462            * nothing".  The case where we need to ensure we keep the
1463            * "just" is actually exactly the case where we have a nested
1464            * Nothing.
1465            *
1466            * Instead of searching for that nested Nothing, we just print
1467            * the contained value into a separate string and see if we
1468            * end up with "nothing" at the end of it.  If so, we need to
1469            * add "just" at our level.
1470            */
1471           element = g_variant_get_child_value (value, 0);
1472           printed_child = g_variant_print (element, FALSE);
1473           g_variant_unref (element);
1474
1475           if (g_str_has_suffix (printed_child, "nothing"))
1476             g_string_append (string, "just ");
1477           g_string_append (string, printed_child);
1478           g_free (printed_child);
1479         }
1480       else
1481         g_string_append (string, "nothing");
1482
1483       break;
1484
1485     case G_VARIANT_CLASS_ARRAY:
1486       /* it's an array so the first character of the type string is 'a'
1487        *
1488        * if the first two characters are 'a{' then it's an array of
1489        * dictionary entries (ie: a dictionary) so we print that
1490        * differently.
1491        */
1492       if (g_variant_get_type_string (value)[1] == '{')
1493         /* dictionary */
1494         {
1495           const gchar *comma = "";
1496           gsize n, i;
1497
1498           if ((n = g_variant_n_children (value)) == 0)
1499             {
1500               if (type_annotate)
1501                 g_string_append_printf (string, "@%s ",
1502                                         g_variant_get_type_string (value));
1503               g_string_append (string, "{}");
1504               break;
1505             }
1506
1507           g_string_append_c (string, '{');
1508           for (i = 0; i < n; i++)
1509             {
1510               GVariant *entry, *key, *val;
1511
1512               g_string_append (string, comma);
1513               comma = ", ";
1514
1515               entry = g_variant_get_child_value (value, i);
1516               key = g_variant_get_child_value (entry, 0);
1517               val = g_variant_get_child_value (entry, 1);
1518               g_variant_unref (entry);
1519
1520               g_variant_print_string (key, string, type_annotate);
1521               g_variant_unref (key);
1522               g_string_append (string, ": ");
1523               g_variant_print_string (val, string, type_annotate);
1524               g_variant_unref (val);
1525               type_annotate = FALSE;
1526             }
1527           g_string_append_c (string, '}');
1528         }
1529       else
1530         /* normal (non-dictionary) array */
1531         {
1532           const gchar *comma = "";
1533           gsize n, i;
1534
1535           if ((n = g_variant_n_children (value)) == 0)
1536             {
1537               if (type_annotate)
1538                 g_string_append_printf (string, "@%s ",
1539                                         g_variant_get_type_string (value));
1540               g_string_append (string, "[]");
1541               break;
1542             }
1543
1544           g_string_append_c (string, '[');
1545           for (i = 0; i < n; i++)
1546             {
1547               GVariant *element;
1548
1549               g_string_append (string, comma);
1550               comma = ", ";
1551
1552               element = g_variant_get_child_value (value, i);
1553
1554               g_variant_print_string (element, string, type_annotate);
1555               g_variant_unref (element);
1556               type_annotate = FALSE;
1557             }
1558           g_string_append_c (string, ']');
1559         }
1560
1561       break;
1562
1563     case G_VARIANT_CLASS_TUPLE:
1564       {
1565         gsize n, i;
1566
1567         n = g_variant_n_children (value);
1568
1569         g_string_append_c (string, '(');
1570         for (i = 0; i < n; i++)
1571           {
1572             GVariant *element;
1573
1574             element = g_variant_get_child_value (value, i);
1575             g_variant_print_string (element, string, type_annotate);
1576             g_string_append (string, ", ");
1577             g_variant_unref (element);
1578           }
1579
1580         /* for >1 item:  remove final ", "
1581          * for 1 item:   remove final " ", but leave the ","
1582          * for 0 items:  there is only "(", so remove nothing
1583          */
1584         g_string_truncate (string, string->len - (n > 0) - (n > 1));
1585         g_string_append_c (string, ')');
1586       }
1587       break;
1588
1589     case G_VARIANT_CLASS_DICT_ENTRY:
1590       {
1591         GVariant *element;
1592
1593         g_string_append_c (string, '{');
1594
1595         element = g_variant_get_child_value (value, 0);
1596         g_variant_print_string (element, string, type_annotate);
1597         g_variant_unref (element);
1598
1599         g_string_append (string, ", ");
1600
1601         element = g_variant_get_child_value (value, 1);
1602         g_variant_print_string (element, string, type_annotate);
1603         g_variant_unref (element);
1604
1605         g_string_append_c (string, '}');
1606       }
1607       break;
1608
1609     case G_VARIANT_CLASS_VARIANT:
1610       {
1611         GVariant *child = g_variant_get_variant (value);
1612
1613         /* Always annotate types in nested variants, because they are
1614          * (by nature) of variable type.
1615          */
1616         g_string_append_c (string, '<');
1617         g_variant_print_string (child, string, TRUE);
1618         g_string_append_c (string, '>');
1619
1620         g_variant_unref (child);
1621       }
1622       break;
1623
1624     case G_VARIANT_CLASS_BOOLEAN:
1625       if (g_variant_get_boolean (value))
1626         g_string_append (string, "true");
1627       else
1628         g_string_append (string, "false");
1629       break;
1630
1631     case G_VARIANT_CLASS_STRING:
1632       {
1633         const gchar *str = g_variant_get_string (value, NULL);
1634         gchar *escaped = g_strescape (str, NULL);
1635
1636         /* use double quotes only if a ' is in the string */
1637         if (strchr (str, '\''))
1638           g_string_append_printf (string, "\"%s\"", escaped);
1639         else
1640           g_string_append_printf (string, "'%s'", escaped);
1641
1642         g_free (escaped);
1643       }
1644       break;
1645
1646     case G_VARIANT_CLASS_BYTE:
1647       if (type_annotate)
1648         g_string_append (string, "byte ");
1649       g_string_append_printf (string, "0x%02x",
1650                               g_variant_get_byte (value));
1651       break;
1652
1653     case G_VARIANT_CLASS_INT16:
1654       if (type_annotate)
1655         g_string_append (string, "int16 ");
1656       g_string_append_printf (string, "%"G_GINT16_FORMAT,
1657                               g_variant_get_int16 (value));
1658       break;
1659
1660     case G_VARIANT_CLASS_UINT16:
1661       if (type_annotate)
1662         g_string_append (string, "uint16 ");
1663       g_string_append_printf (string, "%"G_GUINT16_FORMAT,
1664                               g_variant_get_uint16 (value));
1665       break;
1666
1667     case G_VARIANT_CLASS_INT32:
1668       /* Never annotate this type because it is the default for numbers
1669        * (and this is a *pretty* printer)
1670        */
1671       g_string_append_printf (string, "%"G_GINT32_FORMAT,
1672                               g_variant_get_int32 (value));
1673       break;
1674
1675     case G_VARIANT_CLASS_HANDLE:
1676       if (type_annotate)
1677         g_string_append (string, "handle ");
1678       g_string_append_printf (string, "%"G_GINT32_FORMAT,
1679                               g_variant_get_handle (value));
1680       break;
1681
1682     case G_VARIANT_CLASS_UINT32:
1683       if (type_annotate)
1684         g_string_append (string, "uint32 ");
1685       g_string_append_printf (string, "%"G_GUINT32_FORMAT,
1686                               g_variant_get_uint32 (value));
1687       break;
1688
1689     case G_VARIANT_CLASS_INT64:
1690       if (type_annotate)
1691         g_string_append (string, "int64 ");
1692       g_string_append_printf (string, "%"G_GINT64_FORMAT,
1693                               g_variant_get_int64 (value));
1694       break;
1695
1696     case G_VARIANT_CLASS_UINT64:
1697       if (type_annotate)
1698         g_string_append (string, "uint64 ");
1699       g_string_append_printf (string, "%"G_GUINT64_FORMAT,
1700                               g_variant_get_uint64 (value));
1701       break;
1702
1703     case G_VARIANT_CLASS_DOUBLE:
1704       {
1705         gchar buffer[100];
1706         gint i;
1707
1708         g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
1709
1710         for (i = 0; buffer[i]; i++)
1711           if (buffer[i] == '.' || buffer[i] == 'e' ||
1712               buffer[i] == 'n' || buffer[i] == 'N')
1713             break;
1714
1715         /* if there is no '.' or 'e' in the float then add one */
1716         if (buffer[i] == '\0')
1717           {
1718             buffer[i++] = '.';
1719             buffer[i++] = '0';
1720             buffer[i++] = '\0';
1721           }
1722
1723         g_string_append (string, buffer);
1724       }
1725       break;
1726
1727     case G_VARIANT_CLASS_OBJECT_PATH:
1728       if (type_annotate)
1729         g_string_append (string, "objectpath ");
1730       g_string_append_printf (string, "\'%s\'",
1731                               g_variant_get_string (value, NULL));
1732       break;
1733
1734     case G_VARIANT_CLASS_SIGNATURE:
1735       if (type_annotate)
1736         g_string_append (string, "signature ");
1737       g_string_append_printf (string, "\'%s\'",
1738                               g_variant_get_string (value, NULL));
1739       break;
1740
1741     default:
1742       g_assert_not_reached ();
1743   }
1744
1745   return string;
1746 }
1747
1748 /**
1749  * g_variant_print:
1750  * @value: a #GVariant
1751  * @type_annotate: %TRUE if type information should be included in
1752  *                 the output
1753  * @returns: a newly-allocated string holding the result.
1754  *
1755  * Pretty-prints @value in the format understood by g_variant_parse().
1756  *
1757  * If @type_annotate is %TRUE, then type information is included in
1758  * the output.
1759  */
1760 gchar *
1761 g_variant_print (GVariant *value,
1762                  gboolean  type_annotate)
1763 {
1764   return g_string_free (g_variant_print_string (value, NULL, type_annotate),
1765                         FALSE);
1766 };
1767
1768 /* Hash, Equal, Compare {{{1 */
1769 /**
1770  * g_variant_hash:
1771  * @value: a basic #GVariant value as a #gconstpointer
1772  * @returns: a hash value corresponding to @value
1773  *
1774  * Generates a hash value for a #GVariant instance.
1775  *
1776  * The output of this function is guaranteed to be the same for a given
1777  * value only per-process.  It may change between different processor
1778  * architectures or even different versions of GLib.  Do not use this
1779  * function as a basis for building protocols or file formats.
1780  *
1781  * The type of @value is #gconstpointer only to allow use of this
1782  * function with #GHashTable.  @value must be a #GVariant.
1783  *
1784  * Since: 2.24
1785  **/
1786 guint
1787 g_variant_hash (gconstpointer value_)
1788 {
1789   GVariant *value = (GVariant *) value_;
1790
1791   switch (g_variant_classify (value))
1792     {
1793     case G_VARIANT_CLASS_STRING:
1794     case G_VARIANT_CLASS_OBJECT_PATH:
1795     case G_VARIANT_CLASS_SIGNATURE:
1796       return g_str_hash (g_variant_get_string (value, NULL));
1797
1798     case G_VARIANT_CLASS_BOOLEAN:
1799       /* this is a very odd thing to hash... */
1800       return g_variant_get_boolean (value);
1801
1802     case G_VARIANT_CLASS_BYTE:
1803       return g_variant_get_byte (value);
1804
1805     case G_VARIANT_CLASS_INT16:
1806     case G_VARIANT_CLASS_UINT16:
1807       {
1808         const guint16 *ptr;
1809
1810         ptr = g_variant_get_data (value);
1811
1812         if (ptr)
1813           return *ptr;
1814         else
1815           return 0;
1816       }
1817
1818     case G_VARIANT_CLASS_INT32:
1819     case G_VARIANT_CLASS_UINT32:
1820     case G_VARIANT_CLASS_HANDLE:
1821       {
1822         const guint *ptr;
1823
1824         ptr = g_variant_get_data (value);
1825
1826         if (ptr)
1827           return *ptr;
1828         else
1829           return 0;
1830       }
1831
1832     case G_VARIANT_CLASS_INT64:
1833     case G_VARIANT_CLASS_UINT64:
1834     case G_VARIANT_CLASS_DOUBLE:
1835       /* need a separate case for these guys because otherwise
1836        * performance could be quite bad on big endian systems
1837        */
1838       {
1839         const guint *ptr;
1840
1841         ptr = g_variant_get_data (value);
1842
1843         if (ptr)
1844           return ptr[0] + ptr[1];
1845         else
1846           return 0;
1847       }
1848
1849     default:
1850       g_return_val_if_fail (!g_variant_is_container (value), 0);
1851       g_assert_not_reached ();
1852     }
1853 }
1854
1855 /**
1856  * g_variant_equal:
1857  * @one: a #GVariant instance
1858  * @two: a #GVariant instance
1859  * @returns: %TRUE if @one and @two are equal
1860  *
1861  * Checks if @one and @two have the same type and value.
1862  *
1863  * The types of @one and @two are #gconstpointer only to allow use of
1864  * this function with #GHashTable.  They must each be a #GVariant.
1865  *
1866  * Since: 2.24
1867  **/
1868 gboolean
1869 g_variant_equal (gconstpointer one,
1870                  gconstpointer two)
1871 {
1872   gboolean equal;
1873
1874   g_return_val_if_fail (one != NULL && two != NULL, FALSE);
1875
1876   if (g_variant_get_type_info ((GVariant *) one) !=
1877       g_variant_get_type_info ((GVariant *) two))
1878     return FALSE;
1879
1880   /* if both values are trusted to be in their canonical serialised form
1881    * then a simple memcmp() of their serialised data will answer the
1882    * question.
1883    *
1884    * if not, then this might generate a false negative (since it is
1885    * possible for two different byte sequences to represent the same
1886    * value).  for now we solve this by pretty-printing both values and
1887    * comparing the result.
1888    */
1889   if (g_variant_is_trusted ((GVariant *) one) &&
1890       g_variant_is_trusted ((GVariant *) two))
1891     {
1892       gconstpointer data_one, data_two;
1893       gsize size_one, size_two;
1894
1895       size_one = g_variant_get_size ((GVariant *) one);
1896       size_two = g_variant_get_size ((GVariant *) two);
1897
1898       if (size_one != size_two)
1899         return FALSE;
1900
1901       data_one = g_variant_get_data ((GVariant *) one);
1902       data_two = g_variant_get_data ((GVariant *) two);
1903
1904       equal = memcmp (data_one, data_two, size_one) == 0;
1905     }
1906   else
1907     {
1908       gchar *strone, *strtwo;
1909
1910       strone = g_variant_print ((GVariant *) one, FALSE);
1911       strtwo = g_variant_print ((GVariant *) two, FALSE);
1912       equal = strcmp (strone, strtwo) == 0;
1913       g_free (strone);
1914       g_free (strtwo);
1915     }
1916
1917   return equal;
1918 }
1919
1920 /**
1921  * g_variant_compare:
1922  * @one: a basic-typed #GVariant instance
1923  * @two: a #GVariant instance of the same type
1924  * @returns: negative value if a &lt; b;
1925  *           zero if a = b;
1926  *           positive value if a &gt; b.
1927  *
1928  * Compares @one and @two.
1929  *
1930  * The types of @one and @two are #gconstpointer only to allow use of
1931  * this function with #GTree, #GPtrArray, etc.  They must each be a
1932  * #GVariant.
1933  *
1934  * Comparison is only defined for basic types (ie: booleans, numbers,
1935  * strings).  For booleans, %FALSE is less than %TRUE.  Numbers are
1936  * ordered in the usual way.  Strings are in ASCII lexographical order.
1937  *
1938  * It is a programmer error to attempt to compare container values or
1939  * two values that have types that are not exactly equal.  For example,
1940  * you can not compare a 32-bit signed integer with a 32-bit unsigned
1941  * integer.  Also note that this function is not particularly
1942  * well-behaved when it comes to comparison of doubles; in particular,
1943  * the handling of incomparable values (ie: NaN) is undefined.
1944  *
1945  * If you only require an equality comparison, g_variant_equal() is more
1946  * general.
1947  **/
1948 gint
1949 g_variant_compare (gconstpointer one,
1950                    gconstpointer two)
1951 {
1952   GVariant *a = (GVariant *) one;
1953   GVariant *b = (GVariant *) two;
1954
1955   g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
1956
1957   switch (g_variant_classify (a))
1958     {
1959     case G_VARIANT_CLASS_BYTE:
1960       return ((gint) g_variant_get_byte (a)) -
1961              ((gint) g_variant_get_byte (b));
1962
1963     case G_VARIANT_CLASS_INT16:
1964       return ((gint) g_variant_get_int16 (a)) -
1965              ((gint) g_variant_get_int16 (b));
1966
1967     case G_VARIANT_CLASS_UINT16:
1968       return ((gint) g_variant_get_uint16 (a)) -
1969              ((gint) g_variant_get_uint16 (b));
1970
1971     case G_VARIANT_CLASS_INT32:
1972       {
1973         gint32 a_val = g_variant_get_int32 (a);
1974         gint32 b_val = g_variant_get_int32 (b);
1975
1976         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
1977       }
1978
1979     case G_VARIANT_CLASS_UINT32:
1980       {
1981         guint32 a_val = g_variant_get_uint32 (a);
1982         guint32 b_val = g_variant_get_uint32 (b);
1983
1984         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
1985       }
1986
1987     case G_VARIANT_CLASS_INT64:
1988       {
1989         gint64 a_val = g_variant_get_int64 (a);
1990         gint64 b_val = g_variant_get_int64 (b);
1991
1992         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
1993       }
1994
1995     case G_VARIANT_CLASS_UINT64:
1996       {
1997         guint64 a_val = g_variant_get_int32 (a);
1998         guint64 b_val = g_variant_get_int32 (b);
1999
2000         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2001       }
2002
2003     case G_VARIANT_CLASS_DOUBLE:
2004       {
2005         gdouble a_val = g_variant_get_double (a);
2006         gdouble b_val = g_variant_get_double (b);
2007
2008         return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2009       }
2010
2011     case G_VARIANT_CLASS_STRING:
2012     case G_VARIANT_CLASS_OBJECT_PATH:
2013     case G_VARIANT_CLASS_SIGNATURE:
2014       return strcmp (g_variant_get_string (a, NULL),
2015                      g_variant_get_string (b, NULL));
2016
2017     default:
2018       g_return_val_if_fail (!g_variant_is_container (a), 0);
2019       g_assert_not_reached ();
2020     }
2021 }
2022
2023 /* GVariantIter {{{1 */
2024 /**
2025  * GVariantIter:
2026  *
2027  * #GVariantIter is an opaque data structure and can only be accessed
2028  * using the following functions.
2029  **/
2030 struct stack_iter
2031 {
2032   GVariant *value;
2033   gssize n, i;
2034
2035   const gchar *loop_format;
2036
2037   gsize padding[3];
2038   gsize magic;
2039 };
2040
2041 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2042
2043 struct heap_iter
2044 {
2045   struct stack_iter iter;
2046
2047   GVariant *value_ref;
2048   gsize magic;
2049 };
2050
2051 #define GVSI(i)                 ((struct stack_iter *) (i))
2052 #define GVHI(i)                 ((struct heap_iter *) (i))
2053 #define GVSI_MAGIC              ((gsize) 3579507750u)
2054 #define GVHI_MAGIC              ((gsize) 1450270775u)
2055 #define is_valid_iter(i)        (i != NULL && \
2056                                  GVSI(i)->magic == GVSI_MAGIC)
2057 #define is_valid_heap_iter(i)   (GVHI(i)->magic == GVHI_MAGIC && \
2058                                  is_valid_iter(i))
2059
2060 /**
2061  * g_variant_iter_new:
2062  * @value: a container #GVariant
2063  * @returns: a new heap-allocated #GVariantIter
2064  *
2065  * Creates a heap-allocated #GVariantIter for iterating over the items
2066  * in @value.
2067  *
2068  * Use g_variant_iter_free() to free the return value when you no longer
2069  * need it.
2070  *
2071  * A reference is taken to @value and will be released only when
2072  * g_variant_iter_free() is called.
2073  *
2074  * Since: 2.24
2075  **/
2076 GVariantIter *
2077 g_variant_iter_new (GVariant *value)
2078 {
2079   GVariantIter *iter;
2080
2081   iter = (GVariantIter *) g_slice_new (struct heap_iter);
2082   GVHI(iter)->value_ref = g_variant_ref (value);
2083   GVHI(iter)->magic = GVHI_MAGIC;
2084
2085   g_variant_iter_init (iter, value);
2086
2087   return iter;
2088 }
2089
2090 /**
2091  * g_variant_iter_init:
2092  * @iter: a pointer to a #GVariantIter
2093  * @value: a container #GVariant
2094  * @returns: the number of items in @value
2095  *
2096  * Initialises (without allocating) a #GVariantIter.  @iter may be
2097  * completely uninitialised prior to this call; its old value is
2098  * ignored.
2099  *
2100  * The iterator remains valid for as long as @value exists, and need not
2101  * be freed in any way.
2102  *
2103  * Since: 2.24
2104  **/
2105 gsize
2106 g_variant_iter_init (GVariantIter *iter,
2107                      GVariant     *value)
2108 {
2109   GVSI(iter)->magic = GVSI_MAGIC;
2110   GVSI(iter)->value = value;
2111   GVSI(iter)->n = g_variant_n_children (value);
2112   GVSI(iter)->i = -1;
2113   GVSI(iter)->loop_format = NULL;
2114
2115   return GVSI(iter)->n;
2116 }
2117
2118 /**
2119  * g_variant_iter_copy:
2120  * @iter: a #GVariantIter
2121  * @returns: a new heap-allocated #GVariantIter
2122  *
2123  * Creates a new heap-allocated #GVariantIter to iterate over the
2124  * container that was being iterated over by @iter.  Iteration begins on
2125  * the new iterator from the current position of the old iterator but
2126  * the two copies are independent past that point.
2127  *
2128  * Use g_variant_iter_free() to free the return value when you no longer
2129  * need it.
2130  *
2131  * A reference is taken to the container that @iter is iterating over
2132  * and will be releated only when g_variant_iter_free() is called.
2133  *
2134  * Since: 2.24
2135  **/
2136 GVariantIter *
2137 g_variant_iter_copy (GVariantIter *iter)
2138 {
2139   GVariantIter *copy;
2140
2141   g_return_val_if_fail (is_valid_iter (iter), 0);
2142
2143   copy = g_variant_iter_new (GVSI(iter)->value);
2144   GVSI(copy)->i = GVSI(iter)->i;
2145
2146   return copy;
2147 }
2148
2149 /**
2150  * g_variant_iter_n_children:
2151  * @iter: a #GVariantIter
2152  * @returns: the number of children in the container
2153  *
2154  * Queries the number of child items in the container that we are
2155  * iterating over.  This is the total number of items -- not the number
2156  * of items remaining.
2157  *
2158  * This function might be useful for preallocation of arrays.
2159  *
2160  * Since: 2.24
2161  **/
2162 gsize
2163 g_variant_iter_n_children (GVariantIter *iter)
2164 {
2165   g_return_val_if_fail (is_valid_iter (iter), 0);
2166
2167   return GVSI(iter)->n;
2168 }
2169
2170 /**
2171  * g_variant_iter_free:
2172  * @iter: a heap-allocated #GVariantIter
2173  *
2174  * Frees a heap-allocated #GVariantIter.  Only call this function on
2175  * iterators that were returned by g_variant_iter_new() or
2176  * g_variant_iter_copy().
2177  *
2178  * Since: 2.24
2179  **/
2180 void
2181 g_variant_iter_free (GVariantIter *iter)
2182 {
2183   g_return_if_fail (is_valid_heap_iter (iter));
2184
2185   g_variant_unref (GVHI(iter)->value_ref);
2186   GVHI(iter)->magic = 0;
2187
2188   g_slice_free (struct heap_iter, GVHI(iter));
2189 }
2190
2191 /**
2192  * g_variant_iter_next_value:
2193  * @iter: a #GVariantIter
2194  * @returns: a #GVariant, or %NULL
2195  *
2196  * Gets the next item in the container.  If no more items remain then
2197  * %NULL is returned.
2198  *
2199  * Use g_variant_unref() to drop your reference on the return value when
2200  * you no longer need it.
2201  *
2202  * <example>
2203  *  <title>Iterating with g_variant_iter_next_value()</title>
2204  *  <programlisting>
2205  *   /<!-- -->* recursively iterate a container *<!-- -->/
2206  *   void
2207  *   iterate_container_recursive (GVariant *container)
2208  *   {
2209  *     GVariantIter iter;
2210  *     GVariant *child;
2211  *
2212  *     g_variant_iter_init (&iter, dictionary);
2213  *     while ((child = g_variant_iter_next_value (&iter)))
2214  *       {
2215  *         g_print ("type '%s'\n", g_variant_get_type_string (child));
2216  *
2217  *         if (g_variant_is_container (child))
2218  *           iterate_container_recursive (child);
2219  *
2220  *         g_variant_unref (child);
2221  *       }
2222  *   }
2223  * </programlisting>
2224  * </example>
2225  *
2226  * Since: 2.24
2227  **/
2228 GVariant *
2229 g_variant_iter_next_value (GVariantIter *iter)
2230 {
2231   g_return_val_if_fail (is_valid_iter (iter), FALSE);
2232
2233   if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2234     {
2235       g_critical ("g_variant_iter_next_value: must not be called again "
2236                   "after NULL has already been returned.");
2237       return NULL;
2238     }
2239
2240   GVSI(iter)->i++;
2241
2242   if (GVSI(iter)->i < GVSI(iter)->n)
2243     return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2244
2245   return NULL;
2246 }
2247
2248 /* GVariantBuilder {{{1 */
2249 /**
2250  * GVariantBuilder:
2251  *
2252  * A utility type for constructing container-type #GVariant instances.
2253  *
2254  * This is an opaque structure and may only be accessed using the
2255  * following functions.
2256  *
2257  * #GVariantBuilder is not threadsafe in any way.  Do not attempt to
2258  * access it from more than one thread.
2259  **/
2260
2261 struct stack_builder
2262 {
2263   GVariantBuilder *parent;
2264   GVariantType *type;
2265
2266   /* type constraint explicitly specified by 'type'.
2267    * for tuple types, this moves along as we add more items.
2268    */
2269   const GVariantType *expected_type;
2270
2271   /* type constraint implied by previous array item.
2272    */
2273   const GVariantType *prev_item_type;
2274
2275   /* constraints on the number of children.  max = -1 for unlimited. */
2276   gsize min_items;
2277   gsize max_items;
2278
2279   /* dynamically-growing pointer array */
2280   GVariant **children;
2281   gsize allocated_children;
2282   gsize offset;
2283
2284   /* set to '1' if all items in the container will have the same type
2285    * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
2286    */
2287   guint uniform_item_types : 1;
2288
2289   /* set to '1' initially and changed to '0' if an untrusted value is
2290    * added
2291    */
2292   guint trusted : 1;
2293
2294   gsize magic;
2295 };
2296
2297 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
2298
2299 struct heap_builder
2300 {
2301   GVariantBuilder builder;
2302   gsize magic;
2303
2304   gint ref_count;
2305 };
2306
2307 #define GVSB(b)                  ((struct stack_builder *) (b))
2308 #define GVHB(b)                  ((struct heap_builder *) (b))
2309 #define GVSB_MAGIC               ((gsize) 1033660112u)
2310 #define GVHB_MAGIC               ((gsize) 3087242682u)
2311 #define is_valid_builder(b)      (b != NULL && \
2312                                   GVSB(b)->magic == GVSB_MAGIC)
2313 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
2314
2315 /**
2316  * g_variant_builder_new:
2317  * @type: a container type
2318  * @returns: a #GVariantBuilder
2319  *
2320  * Allocates and initialises a new #GVariantBuilder.
2321  *
2322  * You should call g_variant_builder_unref() on the return value when it
2323  * is no longer needed.  The memory will not be automatically freed by
2324  * any other call.
2325  *
2326  * In most cases it is easier to place a #GVariantBuilder directly on
2327  * the stack of the calling function and initialise it with
2328  * g_variant_builder_init().
2329  *
2330  * Since: 2.24
2331  **/
2332 GVariantBuilder *
2333 g_variant_builder_new (const GVariantType *type)
2334 {
2335   GVariantBuilder *builder;
2336
2337   builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
2338   g_variant_builder_init (builder, type);
2339   GVHB(builder)->magic = GVHB_MAGIC;
2340   GVHB(builder)->ref_count = 1;
2341
2342   return builder;
2343 }
2344
2345 /**
2346  * g_variant_builder_unref:
2347  * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2348  *
2349  * Decreases the reference count on @builder.
2350  *
2351  * In the event that there are no more references, releases all memory
2352  * associated with the #GVariantBuilder.
2353  *
2354  * Don't call this on stack-allocated #GVariantBuilder instances or bad
2355  * things will happen.
2356  *
2357  * Since: 2.24
2358  **/
2359 void
2360 g_variant_builder_unref (GVariantBuilder *builder)
2361 {
2362   g_return_if_fail (is_valid_heap_builder (builder));
2363
2364   if (--GVHB(builder)->ref_count)
2365     return;
2366
2367   g_variant_builder_clear (builder);
2368   GVHB(builder)->magic = 0;
2369
2370   g_slice_free (struct heap_builder, GVHB(builder));
2371 }
2372
2373 /**
2374  * g_variant_builder_ref:
2375  * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2376  * @returns: a new reference to @builder
2377  *
2378  * Increases the reference count on @builder.
2379  *
2380  * Don't call this on stack-allocated #GVariantBuilder instances or bad
2381  * things will happen.
2382  *
2383  * Since: 2.24
2384  **/
2385 GVariantBuilder *
2386 g_variant_builder_ref (GVariantBuilder *builder)
2387 {
2388   g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
2389
2390   GVHB(builder)->ref_count++;
2391
2392   return builder;
2393 }
2394
2395 /**
2396  * g_variant_builder_clear:
2397  * @builder: a #GVariantBuilder
2398  *
2399  * Releases all memory associated with a #GVariantBuilder without
2400  * freeing the #GVariantBuilder structure itself.
2401  *
2402  * It typically only makes sense to do this on a stack-allocated
2403  * #GVariantBuilder if you want to abort building the value part-way
2404  * through.  This function need not be called if you call
2405  * g_variant_builder_end() and it also doesn't need to be called on
2406  * builders allocated with g_variant_builder_new (see
2407  * g_variant_builder_free() for that).
2408  *
2409  * This function leaves the #GVariantBuilder structure set to all-zeros.
2410  * It is valid to call this function on either an initialised
2411  * #GVariantBuilder or one that is set to all-zeros but it is not valid
2412  * to call this function on uninitialised memory.
2413  *
2414  * Since: 2.24
2415  **/
2416 void
2417 g_variant_builder_clear (GVariantBuilder *builder)
2418 {
2419   gsize i;
2420
2421   if (GVSB(builder)->magic == 0)
2422     /* all-zeros case */
2423     return;
2424
2425   g_return_if_fail (is_valid_builder (builder));
2426
2427   g_variant_type_free (GVSB(builder)->type);
2428
2429   for (i = 0; i < GVSB(builder)->offset; i++)
2430     g_variant_unref (GVSB(builder)->children[i]);
2431
2432   g_free (GVSB(builder)->children);
2433
2434   if (GVSB(builder)->parent)
2435     {
2436       g_variant_builder_clear (GVSB(builder)->parent);
2437       g_slice_free (GVariantBuilder, GVSB(builder)->parent);
2438     }
2439
2440   memset (builder, 0, sizeof (GVariantBuilder));
2441 }
2442
2443 /**
2444  * g_variant_builder_init:
2445  * @builder: a #GVariantBuilder
2446  * @type: a container type
2447  *
2448  * Initialises a #GVariantBuilder structure.
2449  *
2450  * @type must be non-%NULL.  It specifies the type of container to
2451  * construct.  It can be an indefinite type such as
2452  * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
2453  * Maybe, array, tuple, dictionary entry and variant-typed values may be
2454  * constructed.
2455  *
2456  * After the builder is initialised, values are added using
2457  * g_variant_builder_add_value() or g_variant_builder_add().
2458  *
2459  * After all the child values are added, g_variant_builder_end() frees
2460  * the memory associated with the builder and returns the #GVariant that
2461  * was created.
2462  *
2463  * This function completely ignores the previous contents of @builder.
2464  * On one hand this means that it is valid to pass in completely
2465  * uninitialised memory.  On the other hand, this means that if you are
2466  * initialising over top of an existing #GVariantBuilder you need to
2467  * first call g_variant_builder_clear() in order to avoid leaking
2468  * memory.
2469  *
2470  * You must not call g_variant_builder_ref() or
2471  * g_variant_builder_unref() on a #GVariantBuilder that was initialised
2472  * with this function.  If you ever pass a reference to a
2473  * #GVariantBuilder outside of the control of your own code then you
2474  * should assume that the person receiving that reference may try to use
2475  * reference counting; you should use g_variant_builder_new() instead of
2476  * this function.
2477  *
2478  * Since: 2.24
2479  **/
2480 void
2481 g_variant_builder_init (GVariantBuilder    *builder,
2482                         const GVariantType *type)
2483 {
2484   g_return_if_fail (type != NULL);
2485   g_return_if_fail (g_variant_type_is_container (type));
2486
2487   memset (builder, 0, sizeof (GVariantBuilder));
2488
2489   GVSB(builder)->type = g_variant_type_copy (type);
2490   GVSB(builder)->magic = GVSB_MAGIC;
2491   GVSB(builder)->trusted = TRUE;
2492
2493   switch (*(const gchar *) type)
2494     {
2495     case G_VARIANT_CLASS_VARIANT:
2496       GVSB(builder)->uniform_item_types = TRUE;
2497       GVSB(builder)->allocated_children = 1;
2498       GVSB(builder)->expected_type = NULL;
2499       GVSB(builder)->min_items = 1;
2500       GVSB(builder)->max_items = 1;
2501       break;
2502
2503     case G_VARIANT_CLASS_ARRAY:
2504       GVSB(builder)->uniform_item_types = TRUE;
2505       GVSB(builder)->allocated_children = 8;
2506       GVSB(builder)->expected_type =
2507         g_variant_type_element (GVSB(builder)->type);
2508       GVSB(builder)->min_items = 0;
2509       GVSB(builder)->max_items = -1;
2510       break;
2511
2512     case G_VARIANT_CLASS_MAYBE:
2513       GVSB(builder)->uniform_item_types = TRUE;
2514       GVSB(builder)->allocated_children = 1;
2515       GVSB(builder)->expected_type =
2516         g_variant_type_element (GVSB(builder)->type);
2517       GVSB(builder)->min_items = 0;
2518       GVSB(builder)->max_items = 1;
2519       break;
2520
2521     case G_VARIANT_CLASS_DICT_ENTRY:
2522       GVSB(builder)->uniform_item_types = FALSE;
2523       GVSB(builder)->allocated_children = 2;
2524       GVSB(builder)->expected_type =
2525         g_variant_type_key (GVSB(builder)->type);
2526       GVSB(builder)->min_items = 2;
2527       GVSB(builder)->max_items = 2;
2528       break;
2529
2530     case 'r': /* G_VARIANT_TYPE_TUPLE was given */
2531       GVSB(builder)->uniform_item_types = FALSE;
2532       GVSB(builder)->allocated_children = 8;
2533       GVSB(builder)->expected_type = NULL;
2534       GVSB(builder)->min_items = 0;
2535       GVSB(builder)->max_items = -1;
2536       break;
2537
2538     case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
2539       GVSB(builder)->allocated_children = g_variant_type_n_items (type);
2540       GVSB(builder)->expected_type =
2541         g_variant_type_first (GVSB(builder)->type);
2542       GVSB(builder)->min_items = GVSB(builder)->allocated_children;
2543       GVSB(builder)->max_items = GVSB(builder)->allocated_children;
2544       GVSB(builder)->uniform_item_types = FALSE;
2545       break;
2546
2547     default:
2548       g_assert_not_reached ();
2549    }
2550
2551   GVSB(builder)->children = g_new (GVariant *,
2552                                    GVSB(builder)->allocated_children);
2553 }
2554
2555 static void
2556 g_variant_builder_make_room (struct stack_builder *builder)
2557 {
2558   if (builder->offset == builder->allocated_children)
2559     {
2560       builder->allocated_children *= 2;
2561       builder->children = g_renew (GVariant *, builder->children,
2562                                    builder->allocated_children);
2563     }
2564 }
2565
2566 /**
2567  * g_variant_builder_add_value:
2568  * @builder: a #GVariantBuilder
2569  * @value: a #GVariant
2570  *
2571  * Adds @value to @builder.
2572  *
2573  * It is an error to call this function in any way that would create an
2574  * inconsistent value to be constructed.  Some examples of this are
2575  * putting different types of items into an array, putting the wrong
2576  * types or number of items in a tuple, putting more than one value into
2577  * a variant, etc.
2578  *
2579  * Since: 2.24
2580  **/
2581 void
2582 g_variant_builder_add_value (GVariantBuilder *builder,
2583                              GVariant        *value)
2584 {
2585   g_return_if_fail (is_valid_builder (builder));
2586   g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2587   g_return_if_fail (!GVSB(builder)->expected_type ||
2588                     g_variant_is_of_type (value,
2589                                           GVSB(builder)->expected_type));
2590   g_return_if_fail (!GVSB(builder)->prev_item_type ||
2591                     g_variant_is_of_type (value,
2592                                           GVSB(builder)->prev_item_type));
2593
2594   GVSB(builder)->trusted &= g_variant_is_trusted (value);
2595
2596   if (!GVSB(builder)->uniform_item_types)
2597     {
2598       /* advance our expected type pointers */
2599       if (GVSB(builder)->expected_type)
2600         GVSB(builder)->expected_type =
2601           g_variant_type_next (GVSB(builder)->expected_type);
2602
2603       if (GVSB(builder)->prev_item_type)
2604         GVSB(builder)->prev_item_type =
2605           g_variant_type_next (GVSB(builder)->prev_item_type);
2606     }
2607   else
2608     GVSB(builder)->prev_item_type = g_variant_get_type (value);
2609
2610   g_variant_builder_make_room (GVSB(builder));
2611
2612   GVSB(builder)->children[GVSB(builder)->offset++] =
2613     g_variant_ref_sink (value);
2614 }
2615
2616 /**
2617  * g_variant_builder_open:
2618  * @builder: a #GVariantBuilder
2619  * @type: a #GVariantType
2620  *
2621  * Opens a subcontainer inside the given @builder.  When done adding
2622  * items to the subcontainer, g_variant_builder_close() must be called.
2623  *
2624  * It is an error to call this function in any way that would cause an
2625  * inconsistent value to be constructed (ie: adding too many values or
2626  * a value of an incorrect type).
2627  *
2628  * Since: 2.24
2629  **/
2630 void
2631 g_variant_builder_open (GVariantBuilder    *builder,
2632                         const GVariantType *type)
2633 {
2634   GVariantBuilder *parent;
2635
2636   g_return_if_fail (is_valid_builder (builder));
2637   g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2638   g_return_if_fail (!GVSB(builder)->expected_type ||
2639                     g_variant_type_is_subtype_of (type,
2640                                                   GVSB(builder)->expected_type));
2641   g_return_if_fail (!GVSB(builder)->prev_item_type ||
2642                     g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
2643                                                   type));
2644
2645   parent = g_slice_dup (GVariantBuilder, builder);
2646   g_variant_builder_init (builder, type);
2647   GVSB(builder)->parent = parent;
2648
2649   /* push the prev_item_type down into the subcontainer */
2650   if (GVSB(parent)->prev_item_type)
2651     {
2652       if (!GVSB(builder)->uniform_item_types)
2653         /* tuples and dict entries */
2654         GVSB(builder)->prev_item_type =
2655           g_variant_type_first (GVSB(parent)->prev_item_type);
2656
2657       else if (!g_variant_type_is_variant (GVSB(builder)->type))
2658         /* maybes and arrays */
2659         GVSB(builder)->prev_item_type =
2660           g_variant_type_element (GVSB(parent)->prev_item_type);
2661     }
2662 }
2663
2664 /**
2665  * g_variant_builder_close:
2666  * @builder: a #GVariantBuilder
2667  *
2668  * Closes the subcontainer inside the given @builder that was opened by
2669  * the most recent call to g_variant_builder_open().
2670  *
2671  * It is an error to call this function in any way that would create an
2672  * inconsistent value to be constructed (ie: too few values added to the
2673  * subcontainer).
2674  *
2675  * Since: 2.24
2676  **/
2677 void
2678 g_variant_builder_close (GVariantBuilder *builder)
2679 {
2680   GVariantBuilder *parent;
2681
2682   g_return_if_fail (is_valid_builder (builder));
2683   g_return_if_fail (GVSB(builder)->parent != NULL);
2684
2685   parent = GVSB(builder)->parent;
2686   GVSB(builder)->parent = NULL;
2687
2688   g_variant_builder_add_value (parent, g_variant_builder_end (builder));
2689   *builder = *parent;
2690
2691   g_slice_free (GVariantBuilder, parent);
2692 }
2693
2694 /*< private >
2695  * g_variant_make_maybe_type:
2696  * @element: a #GVariant
2697  *
2698  * Return the type of a maybe containing @element.
2699  */
2700 static GVariantType *
2701 g_variant_make_maybe_type (GVariant *element)
2702 {
2703   return g_variant_type_new_maybe (g_variant_get_type (element));
2704 }
2705
2706 /*< private >
2707  * g_variant_make_array_type:
2708  * @element: a #GVariant
2709  *
2710  * Return the type of an array containing @element.
2711  */
2712 static GVariantType *
2713 g_variant_make_array_type (GVariant *element)
2714 {
2715   return g_variant_type_new_array (g_variant_get_type (element));
2716 }
2717
2718 /**
2719  * g_variant_builder_end:
2720  * @builder: a #GVariantBuilder
2721  * @returns: a new, floating, #GVariant
2722  *
2723  * Ends the builder process and returns the constructed value.
2724  *
2725  * This call automatically reduces the reference count on @builder by
2726  * one, unless it has previously had g_variant_builder_no_autofree()
2727  * called on it.  Unless you've taken other actions, this is usually
2728  * sufficient to free @builder.
2729  *
2730  * Even if additional references are held, it is not permissible to use
2731  * @builder in any way after this call except for further reference
2732  * counting operations.
2733  *
2734  * It is an error to call this function in any way that would create an
2735  * inconsistent value to be constructed (ie: insufficient number of
2736  * items added to a container with a specific number of children
2737  * required).  It is also an error to call this function if the builder
2738  * was created with an indefinite array or maybe type and no children
2739  * have been added; in this case it is impossible to infer the type of
2740  * the empty array.
2741  *
2742  * Since: 2.24
2743  **/
2744 GVariant *
2745 g_variant_builder_end (GVariantBuilder *builder)
2746 {
2747   GVariantType *my_type;
2748   GVariant *value;
2749
2750   g_return_val_if_fail (is_valid_builder (builder), NULL);
2751   g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
2752                         NULL);
2753   g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
2754                         GVSB(builder)->prev_item_type != NULL ||
2755                         g_variant_type_is_definite (GVSB(builder)->type),
2756                         NULL);
2757
2758   if (g_variant_type_is_definite (GVSB(builder)->type))
2759     my_type = g_variant_type_copy (GVSB(builder)->type);
2760
2761   else if (g_variant_type_is_maybe (GVSB(builder)->type))
2762     my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
2763
2764   else if (g_variant_type_is_array (GVSB(builder)->type))
2765     my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
2766
2767   else if (g_variant_type_is_tuple (GVSB(builder)->type))
2768     my_type = g_variant_make_tuple_type (GVSB(builder)->children,
2769                                          GVSB(builder)->offset);
2770
2771   else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
2772     my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
2773                                               GVSB(builder)->children[1]);
2774   else
2775     g_assert_not_reached ();
2776
2777   value = g_variant_new_from_children (my_type,
2778                                        g_renew (GVariant *,
2779                                                 GVSB(builder)->children,
2780                                                 GVSB(builder)->offset),
2781                                        GVSB(builder)->offset,
2782                                        GVSB(builder)->trusted);
2783   GVSB(builder)->children = NULL;
2784   GVSB(builder)->offset = 0;
2785
2786   g_variant_builder_clear (builder);
2787   g_variant_type_free (my_type);
2788
2789   return value;
2790 }
2791
2792 /* Format strings {{{1 */
2793 /*< private >
2794  * g_variant_format_string_scan:
2795  * @string: a string that may be prefixed with a format string
2796  * @limit: a pointer to the end of @string, or %NULL
2797  * @endptr: location to store the end pointer, or %NULL
2798  * @returns: %TRUE if there was a valid format string
2799  *
2800  * Checks the string pointed to by @string for starting with a properly
2801  * formed #GVariant varargs format string.  If no valid format string is
2802  * found then %FALSE is returned.
2803  *
2804  * If @string does start with a valid format string then %TRUE is
2805  * returned.  If @endptr is non-%NULL then it is updated to point to the
2806  * first character after the format string.
2807  *
2808  * If @limit is non-%NULL then @limit (and any charater after it) will
2809  * not be accessed and the effect is otherwise equivalent to if the
2810  * character at @limit were nul.
2811  *
2812  * See the section on <link linkend='gvariant-format-strings'>GVariant
2813  * Format Strings</link>.
2814  *
2815  * Since: 2.24
2816  */
2817 gboolean
2818 g_variant_format_string_scan (const gchar  *string,
2819                               const gchar  *limit,
2820                               const gchar **endptr)
2821 {
2822 #define next_char() (string == limit ? '\0' : *string++)
2823 #define peek_char() (string == limit ? '\0' : *string)
2824   char c;
2825
2826   switch (next_char())
2827     {
2828     case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
2829     case 'x': case 't': case 'h': case 'd': case 's': case 'o':
2830     case 'g': case 'v': case '*': case '?': case 'r':
2831       break;
2832
2833     case 'm':
2834       return g_variant_format_string_scan (string, limit, endptr);
2835
2836     case 'a':
2837     case '@':
2838       return g_variant_type_string_scan (string, limit, endptr);
2839
2840     case '(':
2841       while (peek_char() != ')')
2842         if (!g_variant_format_string_scan (string, limit, &string))
2843           return FALSE;
2844
2845       next_char(); /* consume ')' */
2846       break;
2847
2848     case '{':
2849       c = next_char();
2850
2851       if (c == '&')
2852         {
2853           c = next_char ();
2854
2855           if (c != 's' && c != 'o' && c != 'g')
2856             return FALSE;
2857         }
2858       else
2859         {
2860           if (c == '@')
2861             c = next_char ();
2862
2863           /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
2864            *    The terminating null character is considered to be
2865            *    part of the string.
2866            */
2867           if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
2868             return FALSE;
2869         }
2870
2871       if (!g_variant_format_string_scan (string, limit, &string))
2872         return FALSE;
2873
2874       if (next_char() != '}')
2875         return FALSE;
2876
2877       break;
2878
2879     case '^': /* '^as' or '^a&s' only */
2880       if (next_char() != 'a')
2881         return FALSE;
2882
2883       if (peek_char() == '&')
2884         next_char ();
2885
2886       c = next_char ();
2887
2888       if (c != 's' && c != 'o' && c != 'g')
2889         return FALSE;
2890
2891       break;
2892
2893     case '&':
2894       c = next_char();
2895
2896       if (c != 's' && c != 'o' && c != 'g')
2897         return FALSE;
2898
2899       break;
2900
2901     default:
2902       return FALSE;
2903     }
2904
2905   if (endptr != NULL)
2906     *endptr = string;
2907
2908 #undef next_char
2909 #undef peek_char
2910
2911   return TRUE;
2912 }
2913
2914 /*< private >
2915  * g_variant_format_string_scan_type:
2916  * @string: a string that may be prefixed with a format string
2917  * @limit: a pointer to the end of @string
2918  * @endptr: location to store the end pointer, or %NULL
2919  * @returns: a #GVariantType if there was a valid format string
2920  *
2921  * If @string starts with a valid format string then this function will
2922  * return the type that the format string corresponds to.  Otherwise
2923  * this function returns %NULL.
2924  *
2925  * Use g_variant_type_free() to free the return value when you no longer
2926  * need it.
2927  *
2928  * This function is otherwise exactly like
2929  * g_variant_format_string_scan().
2930  *
2931  * Since: 2.24
2932  */
2933 GVariantType *
2934 g_variant_format_string_scan_type (const gchar  *string,
2935                                    const gchar  *limit,
2936                                    const gchar **endptr)
2937 {
2938   const gchar *my_end;
2939   gchar *dest;
2940   gchar *new;
2941
2942   if (endptr == NULL)
2943     endptr = &my_end;
2944
2945   if (!g_variant_format_string_scan (string, limit, endptr))
2946     return NULL;
2947
2948   dest = new = g_malloc (*endptr - string + 1);
2949   while (string != *endptr)
2950     {
2951       if (*string != '@' && *string != '&' && *string != '^')
2952         *dest++ = *string;
2953       string++;
2954     }
2955   *dest = '\0';
2956
2957   return (GVariantType *) G_VARIANT_TYPE (new);
2958 }
2959
2960 static gboolean
2961 valid_format_string (const gchar *format_string,
2962                      gboolean     single,
2963                      GVariant    *value)
2964 {
2965   const gchar *endptr;
2966   GVariantType *type;
2967
2968   type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
2969
2970   if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
2971     {
2972       if (single)
2973         g_critical ("`%s' is not a valid GVariant format string",
2974                     format_string);
2975       else
2976         g_critical ("`%s' does not have a valid GVariant format "
2977                     "string as a prefix", format_string);
2978
2979       if (type != NULL)
2980         g_variant_type_free (type);
2981
2982       return FALSE;
2983     }
2984
2985   if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
2986     {
2987       gchar *fragment;
2988       gchar *typestr;
2989
2990       fragment = g_strndup (format_string, endptr - format_string);
2991       typestr = g_variant_type_dup_string (type);
2992
2993       g_critical ("the GVariant format string `%s' has a type of "
2994                   "`%s' but the given value has a type of `%s'",
2995                   fragment, typestr, g_variant_get_type_string (value));
2996
2997       g_variant_type_free (type);
2998
2999       return FALSE;
3000     }
3001
3002   g_variant_type_free (type);
3003
3004   return TRUE;
3005 }
3006
3007 /* Variable Arguments {{{1 */
3008 /* We consider 2 main classes of format strings:
3009  *
3010  *   - recursive format strings
3011  *      these are ones that result in recursion and the collection of
3012  *      possibly more than one argument.  Maybe types, tuples,
3013  *      dictionary entries.
3014  *
3015  *   - leaf format string
3016  *      these result in the collection of a single argument.
3017  *
3018  * Leaf format strings are further subdivided into two categories:
3019  *
3020  *   - single non-null pointer ("nnp")
3021  *      these either collect or return a single non-null pointer.
3022  *
3023  *   - other
3024  *      these collect or return something else (bool, number, etc).
3025  *
3026  * Based on the above, the varargs handling code is split into 4 main parts:
3027  *
3028  *   - nnp handling code
3029  *   - leaf handling code (which may invoke nnp code)
3030  *   - generic handling code (may be recursive, may invoke leaf code)
3031  *   - user-facing API (which invokes the generic code)
3032  *
3033  * Each section implements some of the following functions:
3034  *
3035  *   - skip:
3036  *      collect the arguments for the format string as if
3037  *      g_variant_new() had been called, but do nothing with them.  used
3038  *      for skipping over arguments when constructing a Nothing maybe
3039  *      type.
3040  *
3041  *   - new:
3042  *      create a GVariant *
3043  *
3044  *   - get:
3045  *      unpack a GVariant *
3046  *
3047  *   - free (nnp only):
3048  *      free a previously allocated item
3049  */
3050
3051 static gboolean
3052 g_variant_format_string_is_leaf (const gchar *str)
3053 {
3054   return str[0] != 'm' && str[0] != '(' && str[0] != '{';
3055 }
3056
3057 static gboolean
3058 g_variant_format_string_is_nnp (const gchar *str)
3059 {
3060   return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
3061          str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
3062          str[0] == 'r' || str[0] == 'v' || str[0] == '&';
3063 }
3064
3065 /* Single non-null pointer ("nnp") {{{2 */
3066 static void
3067 g_variant_valist_free_nnp (const gchar *str,
3068                            gpointer     ptr)
3069 {
3070   switch (*str)
3071     {
3072     case 'a':
3073       g_variant_iter_free (ptr);
3074       break;
3075
3076     case '^':
3077       if (str[2] != '&')        /* '^as' */
3078         g_strfreev (ptr);
3079       else                      /* '^a&s' */
3080         g_free (ptr);
3081       break;
3082
3083     case 's':
3084     case 'o':
3085     case 'g':
3086       g_free (ptr);
3087       break;
3088
3089     case '@':
3090     case '*':
3091     case '?':
3092     case 'v':
3093       g_variant_unref (ptr);
3094       break;
3095
3096     case '&':
3097       break;
3098
3099     default:
3100       g_assert_not_reached ();
3101     }
3102 }
3103
3104 static GVariant *
3105 g_variant_valist_new_nnp (const gchar **str,
3106                           gpointer      ptr)
3107 {
3108   if (**str == '&')
3109     (*str)++;
3110
3111   switch (*(*str)++)
3112     {
3113     case 'a':
3114       {
3115         const GVariantType *type;
3116         GVariant *value;
3117
3118         value = g_variant_builder_end (ptr);
3119         type = g_variant_get_type (value);
3120
3121         if G_UNLIKELY (!g_variant_type_is_array (type))
3122           g_error ("g_variant_new: expected array GVariantBuilder but "
3123                    "the built value has type `%s'",
3124                    g_variant_get_type_string (value));
3125
3126         type = g_variant_type_element (type);
3127
3128         if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
3129           g_error ("g_variant_new: expected GVariantBuilder array element "
3130                    "type `%s' but the built value has element type `%s'",
3131                    g_variant_type_dup_string ((GVariantType *) *str),
3132                    g_variant_get_type_string (value) + 1);
3133
3134         g_variant_type_string_scan (*str, NULL, str);
3135
3136         return value;
3137       }
3138
3139     case 's':
3140       return g_variant_new_string (ptr);
3141
3142     case 'o':
3143       return g_variant_new_object_path (ptr);
3144
3145     case 'g':
3146       return g_variant_new_signature (ptr);
3147
3148     case '^':
3149       {
3150         const GVariantType *type;
3151         GVariantType *array_type;
3152         GVariant **children;
3153         gchar **strv = ptr;
3154         GVariant *value;
3155         guint length, i;
3156
3157         if ((*str)[1] == '&')    /* '^a&s' */
3158           (*str) += 2;
3159         else                     /* '^as' */
3160           (*str)++;
3161
3162         type = (GVariantType *) (*str)++;
3163         array_type = g_variant_type_new_array (type);
3164         length = g_strv_length (strv);
3165         children = g_new (GVariant *, length);
3166         for (i = 0; i < length; i++)
3167           children[i] = g_variant_ref_sink (
3168             g_variant_new_from_trusted (type, strv[i], strlen (strv[i]) + 1));
3169
3170         value = g_variant_new_from_children (array_type, children,
3171                                              length, TRUE);
3172         g_variant_type_free (array_type);
3173
3174         return value;
3175       }
3176
3177     case '@':
3178       if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
3179         g_error ("g_variant_new: expected GVariant of type `%s' but "
3180                  "received value has type `%s'",
3181                  g_variant_type_dup_string ((GVariantType *) *str),
3182                  g_variant_get_type_string (ptr));
3183
3184       g_variant_type_string_scan (*str, NULL, str);
3185
3186       return ptr;
3187
3188     case '*':
3189       return ptr;
3190
3191     case '?':
3192       if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
3193         g_error ("g_variant_new: format string `?' expects basic-typed "
3194                  "GVariant, but received value has type `%s'",
3195                  g_variant_get_type_string (ptr));
3196
3197       return ptr;
3198
3199     case 'r':
3200       if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
3201         g_error ("g_variant_new: format string `r` expects tuple-typed "
3202                  "GVariant, but received value has type `%s'",
3203                  g_variant_get_type_string (ptr));
3204
3205       return ptr;
3206
3207     case 'v':
3208       return g_variant_new_variant (ptr);
3209
3210     default:
3211       g_assert_not_reached ();
3212     }
3213 }
3214
3215 static gpointer
3216 g_variant_valist_get_nnp (const gchar **str,
3217                           GVariant     *value)
3218 {
3219   switch (*(*str)++)
3220     {
3221     case 'a':
3222       g_variant_type_string_scan (*str, NULL, str);
3223       return g_variant_iter_new (value);
3224
3225     case '&':
3226       (*str)++;
3227       return (gchar *) g_variant_get_string (value, NULL);
3228
3229     case 's':
3230     case 'o':
3231     case 'g':
3232       return g_variant_dup_string (value, NULL);
3233
3234     case '^':
3235       if ((*str)[1] == '&')    /* '^a&s' */
3236         {
3237           (*str) += 3;
3238           return g_variant_get_strv (value, NULL);
3239         }
3240       else                    /* '^as' */
3241         {
3242           (*str) += 2;
3243           return g_variant_dup_strv (value, NULL);
3244         }
3245
3246     case '@':
3247       g_variant_type_string_scan (*str, NULL, str);
3248       /* fall through */
3249
3250     case '*':
3251     case '?':
3252     case 'r':
3253       return g_variant_ref (value);
3254
3255     case 'v':
3256       return g_variant_get_variant (value);
3257
3258     default:
3259       g_assert_not_reached ();
3260     }
3261 }
3262
3263 /* Leaves {{{2 */
3264 static void
3265 g_variant_valist_skip_leaf (const gchar **str,
3266                             va_list      *app)
3267 {
3268   if (g_variant_format_string_is_nnp (*str))
3269     {
3270       g_variant_format_string_scan (*str, NULL, str);
3271       va_arg (*app, gpointer);
3272       return;
3273     }
3274
3275   switch (*(*str)++)
3276     {
3277     case 'b':
3278     case 'y':
3279     case 'n':
3280     case 'q':
3281     case 'i':
3282     case 'u':
3283     case 'h':
3284       va_arg (*app, int);
3285       return;
3286
3287     case 'x':
3288     case 't':
3289       va_arg (*app, guint64);
3290       return;
3291
3292     case 'd':
3293       va_arg (*app, gdouble);
3294       return;
3295
3296     default:
3297       g_assert_not_reached ();
3298     }
3299 }
3300
3301 static GVariant *
3302 g_variant_valist_new_leaf (const gchar **str,
3303                            va_list      *app)
3304 {
3305   if (g_variant_format_string_is_nnp (*str))
3306     return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
3307
3308   switch (*(*str)++)
3309     {
3310     case 'b':
3311       return g_variant_new_boolean (va_arg (*app, gboolean));
3312
3313     case 'y':
3314       return g_variant_new_byte (va_arg (*app, guint));
3315
3316     case 'n':
3317       return g_variant_new_int16 (va_arg (*app, gint));
3318
3319     case 'q':
3320       return g_variant_new_uint16 (va_arg (*app, guint));
3321
3322     case 'i':
3323       return g_variant_new_int32 (va_arg (*app, gint));
3324
3325     case 'u':
3326       return g_variant_new_uint32 (va_arg (*app, guint));
3327
3328     case 'x':
3329       return g_variant_new_int64 (va_arg (*app, gint64));
3330
3331     case 't':
3332       return g_variant_new_uint64 (va_arg (*app, guint64));
3333
3334     case 'h':
3335       return g_variant_new_handle (va_arg (*app, gint));
3336
3337     case 'd':
3338       return g_variant_new_double (va_arg (*app, gdouble));
3339
3340     default:
3341       g_assert_not_reached ();
3342     }
3343 }
3344
3345 /* The code below assumes this */
3346 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
3347 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
3348
3349 static void
3350 g_variant_valist_get_leaf (const gchar **str,
3351                            GVariant     *value,
3352                            gboolean      free,
3353                            va_list      *app)
3354 {
3355   gpointer ptr = va_arg (*app, gpointer);
3356
3357   if (ptr == NULL)
3358     {
3359       g_variant_format_string_scan (*str, NULL, str);
3360       return;
3361     }
3362
3363   if (g_variant_format_string_is_nnp (*str))
3364     {
3365       gpointer *nnp = (gpointer *) ptr;
3366
3367       if (free && *nnp != NULL)
3368         g_variant_valist_free_nnp (*str, *nnp);
3369
3370       *nnp = NULL;
3371
3372       if (value != NULL)
3373         *nnp = g_variant_valist_get_nnp (str, value);
3374       else
3375         g_variant_format_string_scan (*str, NULL, str);
3376
3377       return;
3378     }
3379
3380   if (value != NULL)
3381     {
3382       switch (*(*str)++)
3383         {
3384         case 'b':
3385           *(gboolean *) ptr = g_variant_get_boolean (value);
3386           return;
3387
3388         case 'y':
3389           *(guchar *) ptr = g_variant_get_byte (value);
3390           return;
3391
3392         case 'n':
3393           *(gint16 *) ptr = g_variant_get_int16 (value);
3394           return;
3395
3396         case 'q':
3397           *(guint16 *) ptr = g_variant_get_uint16 (value);
3398           return;
3399
3400         case 'i':
3401           *(gint32 *) ptr = g_variant_get_int32 (value);
3402           return;
3403
3404         case 'u':
3405           *(guint32 *) ptr = g_variant_get_uint32 (value);
3406           return;
3407
3408         case 'x':
3409           *(gint64 *) ptr = g_variant_get_int64 (value);
3410           return;
3411
3412         case 't':
3413           *(guint64 *) ptr = g_variant_get_uint64 (value);
3414           return;
3415
3416         case 'h':
3417           *(gint32 *) ptr = g_variant_get_handle (value);
3418           return;
3419
3420         case 'd':
3421           *(gdouble *) ptr = g_variant_get_double (value);
3422           return;
3423         }
3424     }
3425   else
3426     {
3427       switch (*(*str)++)
3428         {
3429         case 'y':
3430           *(guchar *) ptr = 0;
3431           return;
3432
3433         case 'n':
3434         case 'q':
3435           *(guint16 *) ptr = 0;
3436           return;
3437
3438         case 'i':
3439         case 'u':
3440         case 'h':
3441         case 'b':
3442           *(guint32 *) ptr = 0;
3443           return;
3444
3445         case 'x':
3446         case 't':
3447         case 'd':
3448           *(guint64 *) ptr = 0;
3449           return;
3450         }
3451     }
3452
3453   g_assert_not_reached ();
3454 }
3455
3456 /* Generic (recursive) {{{2 */
3457 static void
3458 g_variant_valist_skip (const gchar **str,
3459                        va_list      *app)
3460 {
3461   if (g_variant_format_string_is_leaf (*str))
3462     g_variant_valist_skip_leaf (str, app);
3463
3464   else if (**str == 'm') /* maybe */
3465     {
3466       (*str)++;
3467
3468       if (!g_variant_format_string_is_nnp (*str))
3469         va_arg (*app, gboolean);
3470
3471       g_variant_valist_skip (str, app);
3472     }
3473   else /* tuple, dictionary entry */
3474     {
3475       g_assert (**str == '(' || **str == '{');
3476       (*str)++;
3477       while (**str != ')' && **str != '}')
3478         g_variant_valist_skip (str, app);
3479       (*str)++;
3480     }
3481 }
3482
3483 static GVariant *
3484 g_variant_valist_new (const gchar **str,
3485                       va_list      *app)
3486 {
3487   if (g_variant_format_string_is_leaf (*str))
3488     return g_variant_valist_new_leaf (str, app);
3489
3490   if (**str == 'm') /* maybe */
3491     {
3492       GVariantType *type = NULL;
3493       GVariant *value = NULL;
3494
3495       (*str)++;
3496
3497       if (g_variant_format_string_is_nnp (*str))
3498         {
3499           gpointer nnp = va_arg (*app, gpointer);
3500
3501           if (nnp != NULL)
3502             value = g_variant_valist_new_nnp (str, nnp);
3503           else
3504             type = g_variant_format_string_scan_type (*str, NULL, str);
3505         }
3506       else
3507         {
3508           gboolean just = va_arg (*app, gboolean);
3509
3510           if (just)
3511             value = g_variant_valist_new (str, app);
3512           else
3513             {
3514               type = g_variant_format_string_scan_type (*str, NULL, NULL);
3515               g_variant_valist_skip (str, app);
3516             }
3517         }
3518
3519       value = g_variant_new_maybe (type, value);
3520
3521       if (type != NULL)
3522         g_variant_type_free (type);
3523
3524       return value;
3525     }
3526   else /* tuple, dictionary entry */
3527     {
3528       GVariantBuilder b;
3529
3530       if (**str == '(')
3531         g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
3532       else
3533         {
3534           g_assert (**str == '{');
3535           g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
3536         }
3537
3538       (*str)++; /* '(' */
3539       while (**str != ')' && **str != '}')
3540         g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
3541       (*str)++; /* ')' */
3542
3543       return g_variant_builder_end (&b);
3544     }
3545 }
3546
3547 static void
3548 g_variant_valist_get (const gchar **str,
3549                       GVariant     *value,
3550                       gboolean      free,
3551                       va_list      *app)
3552 {
3553   if (g_variant_format_string_is_leaf (*str))
3554     g_variant_valist_get_leaf (str, value, free, app);
3555
3556   else if (**str == 'm')
3557     {
3558       (*str)++;
3559
3560       if (value != NULL)
3561         value = g_variant_get_maybe (value);
3562
3563       if (!g_variant_format_string_is_nnp (*str))
3564         {
3565           gboolean *ptr = va_arg (*app, gboolean *);
3566
3567           if (ptr != NULL)
3568             *ptr = value != NULL;
3569         }
3570
3571       g_variant_valist_get (str, value, free, app);
3572
3573       if (value != NULL)
3574         g_variant_unref (value);
3575     }
3576
3577   else /* tuple, dictionary entry */
3578     {
3579       gint index = 0;
3580
3581       g_assert (**str == '(' || **str == '{');
3582
3583       (*str)++;
3584       while (**str != ')' && **str != '}')
3585         {
3586           if (value != NULL)
3587             {
3588               GVariant *child = g_variant_get_child_value (value, index++);
3589               g_variant_valist_get (str, child, free, app);
3590               g_variant_unref (child);
3591             }
3592           else
3593             g_variant_valist_get (str, NULL, free, app);
3594         }
3595       (*str)++;
3596     }
3597 }
3598
3599 /* User-facing API {{{2 */
3600 /**
3601  * g_variant_new:
3602  * @format_string: a #GVariant format string
3603  * @...: arguments, as per @format_string
3604  * @returns: a new floating #GVariant instance
3605  *
3606  * Creates a new #GVariant instance.
3607  *
3608  * Think of this function as an analogue to g_strdup_printf().
3609  *
3610  * The type of the created instance and the arguments that are
3611  * expected by this function are determined by @format_string.  See the
3612  * section on <link linkend='gvariant-format-strings'>GVariant Format
3613  * Strings</link>.  Please note that the syntax of the format string is
3614  * very likely to be extended in the future.
3615  *
3616  * The first character of the format string must not be '*' '?' '@' or
3617  * 'r'; in essence, a new #GVariant must always be constructed by this
3618  * function (and not merely passed through it unmodified).
3619  *
3620  * Since: 2.24
3621  **/
3622 GVariant *
3623 g_variant_new (const gchar *format_string,
3624                ...)
3625 {
3626   GVariant *value;
3627   va_list ap;
3628
3629   g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
3630                         format_string[0] != '?' && format_string[0] != '@' &&
3631                         format_string[0] != '*' && format_string[0] != 'r',
3632                         NULL);
3633
3634   va_start (ap, format_string);
3635   value = g_variant_new_va (format_string, NULL, &ap);
3636   va_end (ap);
3637
3638   return value;
3639 }
3640
3641 /**
3642  * g_variant_new_va:
3643  * @format_string: a string that is prefixed with a format string
3644  * @endptr: location to store the end pointer, or %NULL
3645  * @app: a pointer to a #va_list
3646  * @returns: a new, usually floating, #GVariant
3647  *
3648  * This function is intended to be used by libraries based on
3649  * #GVariant that want to provide g_variant_new()-like functionality
3650  * to their users.
3651  *
3652  * The API is more general than g_variant_new() to allow a wider range
3653  * of possible uses.
3654  *
3655  * @format_string must still point to a valid format string, but it only
3656  * needs to be nul-terminated if @endptr is %NULL.  If @endptr is
3657  * non-%NULL then it is updated to point to the first character past the
3658  * end of the format string.
3659  *
3660  * @app is a pointer to a #va_list.  The arguments, according to
3661  * @format_string, are collected from this #va_list and the list is left
3662  * pointing to the argument following the last.
3663  *
3664  * These two generalisations allow mixing of multiple calls to
3665  * g_variant_new_va() and g_variant_get_va() within a single actual
3666  * varargs call by the user.
3667  *
3668  * The return value will be floating if it was a newly created GVariant
3669  * instance (for example, if the format string was "(ii)").  In the case
3670  * that the format_string was '*', '?', 'r', or a format starting with
3671  * '@' then the collected #GVariant pointer will be returned unmodified,
3672  * without adding any additional references.
3673  *
3674  * In order to behave correctly in all cases it is necessary for the
3675  * calling function to g_variant_ref_sink() the return result before
3676  * returning control to the user that originally provided the pointer.
3677  * At this point, the caller will have their own full reference to the
3678  * result.  This can also be done by adding the result to a container,
3679  * or by passing it to another g_variant_new() call.
3680  *
3681  * Since: 2.24
3682  **/
3683 GVariant *
3684 g_variant_new_va (const gchar  *format_string,
3685                   const gchar **endptr,
3686                   va_list      *app)
3687 {
3688   GVariant *value;
3689
3690   g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
3691                         NULL);
3692   g_return_val_if_fail (app != NULL, NULL);
3693
3694   value = g_variant_valist_new (&format_string, app);
3695
3696   if (endptr != NULL)
3697     *endptr = format_string;
3698
3699   return value;
3700 }
3701
3702 /**
3703  * g_variant_get:
3704  * @value: a #GVariant instance
3705  * @format_string: a #GVariant format string
3706  * @...: arguments, as per @format_string
3707  *
3708  * Deconstructs a #GVariant instance.
3709  *
3710  * Think of this function as an analogue to scanf().
3711  *
3712  * The arguments that are expected by this function are entirely
3713  * determined by @format_string.  @format_string also restricts the
3714  * permissible types of @value.  It is an error to give a value with
3715  * an incompatible type.  See the section on <link
3716  * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
3717  * Please note that the syntax of the format string is very likely to be
3718  * extended in the future.
3719  *
3720  * Since: 2.24
3721  **/
3722 void
3723 g_variant_get (GVariant    *value,
3724                const gchar *format_string,
3725                ...)
3726 {
3727   va_list ap;
3728
3729   g_return_if_fail (valid_format_string (format_string, TRUE, value));
3730
3731   /* if any direct-pointer-access formats are in use, flatten first */
3732   if (strchr (format_string, '&'))
3733     g_variant_get_data (value);
3734
3735   va_start (ap, format_string);
3736   g_variant_get_va (value, format_string, NULL, &ap);
3737   va_end (ap);
3738 }
3739
3740 /**
3741  * g_variant_get_va:
3742  * @value: a #GVariant
3743  * @format_string: a string that is prefixed with a format string
3744  * @endptr: location to store the end pointer, or %NULL
3745  * @app: a pointer to a #va_list
3746  *
3747  * This function is intended to be used by libraries based on #GVariant
3748  * that want to provide g_variant_get()-like functionality to their
3749  * users.
3750  *
3751  * The API is more general than g_variant_get() to allow a wider range
3752  * of possible uses.
3753  *
3754  * @format_string must still point to a valid format string, but it only
3755  * need to be nul-terminated if @endptr is %NULL.  If @endptr is
3756  * non-%NULL then it is updated to point to the first character past the
3757  * end of the format string.
3758  *
3759  * @app is a pointer to a #va_list.  The arguments, according to
3760  * @format_string, are collected from this #va_list and the list is left
3761  * pointing to the argument following the last.
3762  *
3763  * These two generalisations allow mixing of multiple calls to
3764  * g_variant_new_va() and g_variant_get_va() within a single actual
3765  * varargs call by the user.
3766  *
3767  * Since: 2.24
3768  **/
3769 void
3770 g_variant_get_va (GVariant     *value,
3771                   const gchar  *format_string,
3772                   const gchar **endptr,
3773                   va_list      *app)
3774 {
3775   g_return_if_fail (valid_format_string (format_string, !endptr, value));
3776   g_return_if_fail (value != NULL);
3777   g_return_if_fail (app != NULL);
3778
3779   /* if any direct-pointer-access formats are in use, flatten first */
3780   if (strchr (format_string, '&'))
3781     g_variant_get_data (value);
3782
3783   g_variant_valist_get (&format_string, value, FALSE, app);
3784
3785   if (endptr != NULL)
3786     *endptr = format_string;
3787 }
3788
3789 /* Varargs-enabled Utility Functions {{{1 */
3790
3791 /**
3792  * g_variant_builder_add:
3793  * @builder: a #GVariantBuilder
3794  * @format_string: a #GVariant varargs format string
3795  * @...: arguments, as per @format_string
3796  *
3797  * Adds to a #GVariantBuilder.
3798  *
3799  * This call is a convenience wrapper that is exactly equivalent to
3800  * calling g_variant_new() followed by g_variant_builder_add_value().
3801  *
3802  * This function might be used as follows:
3803  *
3804  * <programlisting>
3805  * GVariant *
3806  * make_pointless_dictionary (void)
3807  * {
3808  *   GVariantBuilder *builder;
3809  *   int i;
3810  *
3811  *   builder = g_variant_builder_new (G_VARIANT_TYPE_CLASS_ARRAY,
3812  *                                    NULL);
3813  *   for (i = 0; i < 16; i++)
3814  *     {
3815  *       gchar buf[3];
3816  *
3817  *       sprintf (buf, "%d", i);
3818  *       g_variant_builder_add (builder, "{is}", i, buf);
3819  *     }
3820  *
3821  *   return g_variant_builder_end (builder);
3822  * }
3823  * </programlisting>
3824  *
3825  * Since: 2.24
3826  **/
3827 void
3828 g_variant_builder_add (GVariantBuilder *builder,
3829                        const gchar     *format_string,
3830                        ...)
3831 {
3832   GVariant *variant;
3833   va_list ap;
3834
3835   va_start (ap, format_string);
3836   variant = g_variant_new_va (format_string, NULL, &ap);
3837   va_end (ap);
3838
3839   g_variant_builder_add_value (builder, variant);
3840 }
3841
3842 /**
3843  * g_variant_get_child:
3844  * @value: a container #GVariant
3845  * @index_: the index of the child to deconstruct
3846  * @format_string: a #GVariant format string
3847  * @...: arguments, as per @format_string
3848  *
3849  * Reads a child item out of a container #GVariant instance and
3850  * deconstructs it according to @format_string.  This call is
3851  * essentially a combination of g_variant_get_child_value() and
3852  * g_variant_get().
3853  *
3854  * Since: 2.24
3855  **/
3856 void
3857 g_variant_get_child (GVariant    *value,
3858                      gsize        index_,
3859                      const gchar *format_string,
3860                      ...)
3861 {
3862   GVariant *child;
3863   va_list ap;
3864
3865   child = g_variant_get_child_value (value, index_);
3866   g_return_if_fail (valid_format_string (format_string, TRUE, child));
3867
3868   va_start (ap, format_string);
3869   g_variant_get_va (child, format_string, NULL, &ap);
3870   va_end (ap);
3871
3872   g_variant_unref (child);
3873 }
3874
3875 /**
3876  * g_variant_iter_next:
3877  * @iter: a #GVariantIter
3878  * @format_string: a GVariant format string
3879  * @...: the arguments to unpack the value into
3880  * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
3881  *           value
3882  *
3883  * Gets the next item in the container and unpacks it into the variable
3884  * argument list according to @format_string, returning %TRUE.
3885  *
3886  * If no more items remain then %FALSE is returned.
3887  *
3888  * All of the pointers given on the variable arguments list of this
3889  * function are assumed to point at uninitialised memory.  It is the
3890  * responsibility of the caller to free all of the values returned by
3891  * the unpacking process.
3892  *
3893  * <example>
3894  *  <title>Memory management with g_variant_iter_next()</title>
3895  *  <programlisting>
3896  *   /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
3897  *   void
3898  *   iterate_dictionary (GVariant *dictionary)
3899  *   {
3900  *     GVariantIter iter;
3901  *     GVariant *value;
3902  *     gchar *key;
3903  *
3904  *     g_variant_iter_init (&iter, dictionary);
3905  *     while (g_variant_iter_next (&iter, "{sv}", &key, &value))
3906  *       {
3907  *         g_print ("Item '%s' has type '%s'\n", key,
3908  *                  g_variant_get_type_string (value));
3909  *
3910  *         /<!-- -->* must free data for ourselves *<!-- -->/
3911  *         g_variant_unref (value);
3912  *         g_free (key);
3913  *       }
3914  *   }
3915  *  </programlisting>
3916  * </example>
3917  *
3918  * For a solution that is likely to be more convenient to C programmers
3919  * when dealing with loops, see g_variant_iter_loop().
3920  *
3921  * Since: 2.24
3922  **/
3923 gboolean
3924 g_variant_iter_next (GVariantIter *iter,
3925                      const gchar  *format_string,
3926                      ...)
3927 {
3928   GVariant *value;
3929
3930   value = g_variant_iter_next_value (iter);
3931
3932   g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
3933                         FALSE);
3934
3935   if (value != NULL)
3936     {
3937       va_list ap;
3938
3939       va_start (ap, format_string);
3940       g_variant_valist_get (&format_string, value, FALSE, &ap);
3941       va_end (ap);
3942
3943       g_variant_unref (value);
3944     }
3945
3946   return value != NULL;
3947 }
3948
3949 /**
3950  * g_variant_iter_loop:
3951  * @iter: a #GVariantIter
3952  * @format_string: a GVariant format string
3953  * @...: the arguments to unpack the value into
3954  * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
3955  *           value
3956  *
3957  * Gets the next item in the container and unpacks it into the variable
3958  * argument list according to @format_string, returning %TRUE.
3959  *
3960  * If no more items remain then %FALSE is returned.
3961  *
3962  * On the first call to this function, the pointers appearing on the
3963  * variable argument list are assumed to point at uninitialised memory.
3964  * On the second and later calls, it is assumed that the same pointers
3965  * will be given and that they will point to the memory as set by the
3966  * previous call to this function.  This allows the previous values to
3967  * be freed, as appropriate.
3968  *
3969  * This function is intended to be used with a while loop as
3970  * demonstrated in the following example.  This function can only be
3971  * used when iterating over an array.  It is only valid to call this
3972  * function with a string constant for the format string and the same
3973  * string constant must be used each time.  Mixing calls to this
3974  * function and g_variant_iter_next() or g_variant_iter_next_value() on
3975  * the same iterator is not recommended.
3976  *
3977  * <example>
3978  *  <title>Memory management with g_variant_iter_loop()</title>
3979  *  <programlisting>
3980  *   /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
3981  *   void
3982  *   iterate_dictionary (GVariant *dictionary)
3983  *   {
3984  *     GVariantIter iter;
3985  *     GVariant *value;
3986  *     gchar *key;
3987  *
3988  *     g_variant_iter_init (&iter, dictionary);
3989  *     while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
3990  *       {
3991  *         g_print ("Item '%s' has type '%s'\n", key,
3992  *                  g_variant_get_type_string (value));
3993  *
3994  *         /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
3995  *       }
3996  *   }
3997  *  </programlisting>
3998  * </example>
3999  *
4000  * If you want a slightly less magical alternative that requires more
4001  * typing, see g_variant_iter_next().
4002  *
4003  * Since: 2.24
4004  **/
4005 gboolean
4006 g_variant_iter_loop (GVariantIter *iter,
4007                      const gchar  *format_string,
4008                      ...)
4009 {
4010   gboolean first_time = GVSI(iter)->loop_format == NULL;
4011   GVariant *value;
4012   va_list ap;
4013
4014   g_return_val_if_fail (first_time ||
4015                         format_string == GVSI(iter)->loop_format,
4016                         FALSE);
4017
4018   if (first_time)
4019     {
4020       TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
4021       GVSI(iter)->loop_format = format_string;
4022
4023       if (strchr (format_string, '&'))
4024         g_variant_get_data (GVSI(iter)->value);
4025     }
4026
4027   value = g_variant_iter_next_value (iter);
4028
4029   g_return_val_if_fail (!first_time ||
4030                         valid_format_string (format_string, TRUE, value),
4031                         FALSE);
4032
4033   va_start (ap, format_string);
4034   g_variant_valist_get (&format_string, value, !first_time, &ap);
4035   va_end (ap);
4036
4037   if (value != NULL)
4038     g_variant_unref (value);
4039
4040   return value != NULL;
4041 }
4042
4043 /* Serialised data {{{1 */
4044 static GVariant *
4045 g_variant_deep_copy (GVariant *value)
4046 {
4047   switch (g_variant_classify (value))
4048     {
4049     case G_VARIANT_CLASS_MAYBE:
4050     case G_VARIANT_CLASS_ARRAY:
4051     case G_VARIANT_CLASS_TUPLE:
4052     case G_VARIANT_CLASS_DICT_ENTRY:
4053     case G_VARIANT_CLASS_VARIANT:
4054       {
4055         GVariantBuilder builder;
4056         GVariantIter iter;
4057         GVariant *child;
4058
4059         g_variant_builder_init (&builder, g_variant_get_type (value));
4060         g_variant_iter_init (&iter, value);
4061
4062         while ((child = g_variant_iter_next_value (&iter)))
4063           {
4064             g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
4065             g_variant_unref (child);
4066           }
4067
4068         return g_variant_builder_end (&builder);
4069       }
4070
4071     case G_VARIANT_CLASS_BOOLEAN:
4072       return g_variant_new_boolean (g_variant_get_boolean (value));
4073
4074     case G_VARIANT_CLASS_BYTE:
4075       return g_variant_new_byte (g_variant_get_byte (value));
4076
4077     case G_VARIANT_CLASS_INT16:
4078       return g_variant_new_int16 (g_variant_get_int16 (value));
4079
4080     case G_VARIANT_CLASS_UINT16:
4081       return g_variant_new_uint16 (g_variant_get_uint16 (value));
4082
4083     case G_VARIANT_CLASS_INT32:
4084       return g_variant_new_int32 (g_variant_get_int32 (value));
4085
4086     case G_VARIANT_CLASS_UINT32:
4087       return g_variant_new_uint32 (g_variant_get_uint32 (value));
4088
4089     case G_VARIANT_CLASS_INT64:
4090       return g_variant_new_int64 (g_variant_get_int64 (value));
4091
4092     case G_VARIANT_CLASS_UINT64:
4093       return g_variant_new_uint64 (g_variant_get_uint64 (value));
4094
4095     case G_VARIANT_CLASS_HANDLE:
4096       return g_variant_new_handle (g_variant_get_handle (value));
4097
4098     case G_VARIANT_CLASS_DOUBLE:
4099       return g_variant_new_double (g_variant_get_double (value));
4100
4101     case G_VARIANT_CLASS_STRING:
4102       return g_variant_new_string (g_variant_get_string (value, NULL));
4103
4104     case G_VARIANT_CLASS_OBJECT_PATH:
4105       return g_variant_new_object_path (g_variant_get_string (value, NULL));
4106
4107     case G_VARIANT_CLASS_SIGNATURE:
4108       return g_variant_new_signature (g_variant_get_string (value, NULL));
4109     }
4110
4111   g_assert_not_reached ();
4112 }
4113
4114 /**
4115  * g_variant_get_normal_form:
4116  * @value: a #GVariant
4117  * @returns: a trusted #GVariant
4118  *
4119  * Gets a #GVariant instance that has the same value as @value and is
4120  * trusted to be in normal form.
4121  *
4122  * If @value is already trusted to be in normal form then a new
4123  * reference to @value is returned.
4124  *
4125  * If @value is not already trusted, then it is scanned to check if it
4126  * is in normal form.  If it is found to be in normal form then it is
4127  * marked as trusted and a new reference to it is returned.
4128  *
4129  * If @value is found not to be in normal form then a new trusted
4130  * #GVariant is created with the same value as @value.
4131  *
4132  * It makes sense to call this function if you've received #GVariant
4133  * data from untrusted sources and you want to ensure your serialised
4134  * output is definitely in normal form.
4135  *
4136  * Since: 2.24
4137  **/
4138 GVariant *
4139 g_variant_get_normal_form (GVariant *value)
4140 {
4141   GVariant *trusted;
4142
4143   if (g_variant_is_normal_form (value))
4144     return g_variant_ref (value);
4145
4146   trusted = g_variant_deep_copy (value);
4147   g_assert (g_variant_is_trusted (trusted));
4148
4149   return g_variant_ref_sink (trusted);
4150 }
4151
4152 /**
4153  * g_variant_byteswap:
4154  * @value: a #GVariant
4155  * @returns: the byteswapped form of @value
4156  *
4157  * Performs a byteswapping operation on the contents of @value.  The
4158  * result is that all multi-byte numeric data contained in @value is
4159  * byteswapped.  That includes 16, 32, and 64bit signed and unsigned
4160  * integers as well as file handles and double precision floating point
4161  * values.
4162  *
4163  * This function is an identity mapping on any value that does not
4164  * contain multi-byte numeric data.  That include strings, booleans,
4165  * bytes and containers containing only these things (recursively).
4166  *
4167  * The returned value is always in normal form and is marked as trusted.
4168  *
4169  * Since: 2.24
4170  **/
4171 GVariant *
4172 g_variant_byteswap (GVariant *value)
4173 {
4174   GVariantSerialised serialised;
4175   GVariant *trusted;
4176   GBuffer *buffer;
4177   GVariant *new;
4178
4179   trusted = g_variant_get_normal_form (value);
4180   serialised.type_info = g_variant_get_type_info (trusted);
4181   serialised.size = g_variant_get_size (trusted);
4182   serialised.data = g_malloc (serialised.size);
4183   g_variant_store (trusted, serialised.data);
4184   g_variant_unref (trusted);
4185
4186   g_variant_serialised_byteswap (serialised);
4187
4188   buffer = g_buffer_new_take_data (serialised.data, serialised.size);
4189   new = g_variant_new_from_buffer (g_variant_get_type (value), buffer, TRUE);
4190   g_buffer_unref (buffer);
4191
4192   return g_variant_ref_sink (new);
4193 }
4194
4195 /**
4196  * g_variant_new_from_data:
4197  * @type: a definite #GVariantType
4198  * @data: the serialised data
4199  * @size: the size of @data
4200  * @trusted: %TRUE if @data is definitely in normal form
4201  * @notify: function to call when @data is no longer needed
4202  * @user_data: data for @notify
4203  * @returns: a new floating #GVariant of type @type
4204  *
4205  * Creates a new #GVariant instance from serialised data.
4206  *
4207  * @type is the type of #GVariant instance that will be constructed.
4208  * The interpretation of @data depends on knowing the type.
4209  *
4210  * @data is not modified by this function and must remain valid with an
4211  * unchanging value until such a time as @notify is called with
4212  * @user_data.  If the contents of @data change before that time then
4213  * the result is undefined.
4214  *
4215  * If @data is trusted to be serialised data in normal form then
4216  * @trusted should be %TRUE.  This applies to serialised data created
4217  * within this process or read from a trusted location on the disk (such
4218  * as a file installed in /usr/lib alongside your application).  You
4219  * should set trusted to %FALSE if @data is read from the network, a
4220  * file in the user's home directory, etc.
4221  *
4222  * @notify will be called with @user_data when @data is no longer
4223  * needed.  The exact time of this call is unspecified and might even be
4224  * before this function returns.
4225  *
4226  * Since: 2.24
4227  **/
4228 GVariant *
4229 g_variant_new_from_data (const GVariantType *type,
4230                          gconstpointer       data,
4231                          gsize               size,
4232                          gboolean            trusted,
4233                          GDestroyNotify      notify,
4234                          gpointer            user_data)
4235 {
4236   GVariant *value;
4237   GBuffer *buffer;
4238
4239   g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
4240   g_return_val_if_fail (data != NULL || size == 0, NULL);
4241
4242   if (notify)
4243     buffer = g_buffer_new_from_pointer (data, size, notify, user_data);
4244   else
4245     buffer = g_buffer_new_from_static_data (data, size);
4246
4247   value = g_variant_new_from_buffer (type, buffer, trusted);
4248   g_buffer_unref (buffer);
4249
4250   return value;
4251 }
4252
4253 /* Epilogue {{{1 */
4254 #define __G_VARIANT_C__
4255 #include "galiasdef.c"
4256
4257 /* vim:set foldmethod=marker: */