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