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