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