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