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