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