b54cd89da1ba622beb902ff9a9706404c1c912fa
[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 <glib/gvariant-core.h>
29 #include <glib/gtestutils.h>
30 #include <glib/gstrfuncs.h>
31 #include <glib/ghash.h>
32 #include <glib/gmem.h>
33
34 #include <string.h>
35
36 #include "galias.h"
37
38 /**
39  * SECTION: gvariant
40  * @title: GVariant
41  * @short_description: strongly typed value datatype
42  * @see_also: GVariantType
43  *
44  * #GVariant is a variant datatype; it stores a value along with
45  * information about the type of that value.  The range of possible
46  * values is determined by the type.  The type system used by #GVariant
47  * is #GVariantType.
48  *
49  * #GVariant instances always have a type and a value (which are given
50  * at construction time).  The type and value of a #GVariant instance
51  * can never change other than by the #GVariant itself being
52  * destroyed.  A #GVariant can not contain a pointer.
53  *
54  * #GVariant is reference counted using g_variant_ref() and
55  * g_variant_unref().  #GVariant also has floating reference counts --
56  * see g_variant_ref_sink().
57  *
58  * #GVariant is completely threadsafe.  A #GVariant instance can be
59  * concurrently accessed in any way from any number of threads without
60  * problems.
61  *
62  * #GVariant is heavily optimised for dealing with data in serialised
63  * form.  It works particularly well with data located in memory-mapped
64  * files.  It can perform nearly all deserialisation operations in a
65  * small constant time, usually touching only a single memory page.
66  * Serialised #GVariant data can also be sent over the network.
67  *
68  * #GVariant is largely compatible with DBus.  Almost all types of
69  * #GVariant instances can be sent over DBus.  See #GVariantType for
70  * exceptions.
71  *
72  * For convenience to C programmers, #GVariant features powerful
73  * varargs-based value construction and destruction.  This feature is
74  * designed to be embedded in other libraries.
75  *
76  * There is a Python-inspired text language for describing #GVariant
77  * values.  #GVariant includes a printer for this language and a parser
78  * with type inferencing.
79  *
80  * <refsect2>
81  *  <title>Memory Use</title>
82  *  <para>
83  *   #GVariant tries to be quite efficient with respect to memory use.
84  *   This section gives a rough idea of how much memory is used by the
85  *   current implementation.  The information here is subject to change
86  *   in the future.
87  *  </para>
88  *  <para>
89  *   The memory allocated by #GVariant can be grouped into 4 broad
90  *   purposes: memory for serialised data, memory for the type
91  *   information cache, buffer management memory and memory for the
92  *   #GVariant structure itself.
93  *  </para>
94  *  <refsect3>
95  *   <title>Serialised Data Memory</title>
96  *   <para>
97  *    This is the memory that is used for storing GVariant data in
98  *    serialised form.  This is what would be sent over the network or
99  *    what would end up on disk.
100  *   </para>
101  *   <para>
102  *    The amount of memory required to store a boolean is 1 byte.  16,
103  *    32 and 64 bit integers and double precision floating point numbers
104  *    use their "natural" size.  Strings (including object path and
105  *    signature strings) are stored with a nul terminator, and as such
106  *    use the length of the string plus 1 byte.
107  *   </para>
108  *   <para>
109  *    Maybe types use no space at all to represent the null value and
110  *    use the same amount of space (sometimes plus one byte) as the
111  *    equivalent non-maybe-typed value to represent the non-null case.
112  *   </para>
113  *   <para>
114  *    Arrays use the amount of space required to store each of their
115  *    members, concatenated.  Additionally, if the items stored in an
116  *    array are not of a fixed-size (ie: strings, other arrays, etc)
117  *    then an additional framing offset is stored for each item.  The
118  *    size of this offset is either 1, 2 or 4 bytes depending on the
119  *    overall size of the container.  Additionally, extra padding bytes
120  *    are added as required for alignment of child values.
121  *   </para>
122  *   <para>
123  *    Tuples (including dictionary entries) use the amount of space
124  *    required to store each of their members, concatenated, plus one
125  *    framing offset (as per arrays) for each non-fixed-sized item in
126  *    the tuple, except for the last one.  Additionally, extra padding
127  *    bytes are added as required for alignment of child values.
128  *   </para>
129  *   <para>
130  *    Variants use the same amount of space as the item inside of the
131  *    variant, plus 1 byte, plus the length of the type string for the
132  *    item inside the variant.
133  *   </para>
134  *   <para>
135  *    As an example, consider a dictionary mapping strings to variants.
136  *    In the case that the dictionary is empty, 0 bytes are required for
137  *    the serialisation.
138  *   </para>
139  *   <para>
140  *    If we add an item "width" that maps to the int32 value of 500 then
141  *    we will use 4 byte to store the int32 (so 6 for the variant
142  *    containing it) and 6 bytes for the string.  The variant must be
143  *    aligned to 8 after the 6 bytes of the string, so that's 2 extra
144  *    bytes.  6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
145  *    for the dictionary entry.  An additional 1 byte is added to the
146  *    array as a framing offset making a total of 15 bytes.
147  *   </para>
148  *   <para>
149  *    If we add another entry, "title" that maps to a nullable string
150  *    that happens to have a value of null, then we use 0 bytes for the
151  *    null value (and 3 bytes for the variant to contain it along with
152  *    its type string) plus 6 bytes for the string.  Again, we need 2
153  *    padding bytes.  That makes a total of 6 + 2 + 3 = 11 bytes.
154  *   </para>
155  *   <para>
156  *    We now require extra padding between the two items in the array.
157  *    After the 14 bytes of the first item, that's 2 bytes required.  We
158  *    now require 2 framing offsets for an extra two bytes.  14 + 2 + 11
159  *    + 2 = 29 bytes to encode the entire two-item dictionary.
160  *   </para>
161  *  </refsect3>
162  *  <refsect3>
163  *   <title>Type Information Cache</title>
164  *   <para>
165  *    For each GVariant type that currently exists in the program a type
166  *    information structure is kept in the type information cache.  The
167  *    type information structure is required for rapid deserialisation.
168  *   </para>
169  *   <para>
170  *    Continuing with the above example, if a #GVariant exists with the
171  *    type "a{sv}" then a type information struct will exist for
172  *    "a{sv}", "{sv}", "s", and "v".  Multiple uses of the same type
173  *    will share the same type information.  Additionally, all
174  *    single-digit types are stored in read-only static memory and do
175  *    not contribute to the writable memory footprint of a program using
176  *    #GVariant.
177  *   </para>
178  *   <para>
179  *    Aside from the type information structures stored in read-only
180  *    memory, there are two forms of type information.  One is used for
181  *    container types where there is a single element type: arrays and
182  *    maybe types.  The other is used for container types where there
183  *    are multiple element types: tuples and dictionary entries.
184  *   </para>
185  *   <para>
186  *    Array type info structures are 6 * sizeof (void *), plus the
187  *    memory required to store the type string itself.  This means that
188  *    on 32bit systems, the cache entry for "a{sv}" would require 30
189  *    bytes of memory (plus malloc overhead).
190  *   </para>
191  *   <para>
192  *    Tuple type info structures are 6 * sizeof (void *), plus 4 *
193  *    sizeof (void *) for each item in the tuple, plus the memory
194  *    required to store the type string itself.  A 2-item tuple, for
195  *    example, would have a type information structure that consumed
196  *    writable memory in the size of 14 * sizeof (void *) (plus type
197  *    string)  This means that on 32bit systems, the cache entry for
198  *    "{sv}" would require 61 bytes of memory (plus malloc overhead).
199  *   </para>
200  *   <para>
201  *    This means that in total, for our "a{sv}" example, 91 bytes of
202  *    type information would be allocated.
203  *   </para>
204  *   <para>
205  *    The type information cache, additionally, uses a #GHashTable to
206  *    store and lookup the cached items and stores a pointer to this
207  *    hash table in static storage.  The hash table is freed when there
208  *    are zero items in the type cache.
209  *   </para>
210  *   <para>
211  *    Although these sizes may seem large it is important to remember
212  *    that a program will probably only have a very small number of
213  *    different types of values in it and that only one type information
214  *    structure is required for many different values of the same type.
215  *   </para>
216  *  </refsect3>
217  *  <refsect3>
218  *   <title>Buffer Management Memory</title>
219  *   <para>
220  *    #GVariant uses an internal buffer management structure to deal
221  *    with the various different possible sources of serialised data
222  *    that it uses.  The buffer is responsible for ensuring that the
223  *    correct call is made when the data is no longer in use by
224  *    #GVariant.  This may involve a g_free() or a g_slice_free() or
225  *    even g_mapped_file_unref().
226  *   </para>
227  *   <para>
228  *    One buffer management structure is used for each chunk of
229  *    serialised data.  The size of the buffer management structure is 4
230  *    * (void *).  On 32bit systems, that's 16 bytes.
231  *   </para>
232  *  </refsect3>
233  *  <refsect3>
234  *   <title>GVariant structure</title>
235  *   <para>
236  *    The size of a #GVariant structure is 6 * (void *).  On 32 bit
237  *    systems, that's 24 bytes.
238  *   </para>
239  *   <para>
240  *    #GVariant structures only exist if they are explicitly created
241  *    with API calls.  For example, if a #GVariant is constructed out of
242  *    serialised data for the example given above (with the dictionary)
243  *    then although there are 9 individual values that comprise the
244  *    entire dictionary (two keys, two values, two variants containing
245  *    the values, two dictionary entries, plus the dictionary itself),
246  *    only 1 #GVariant instance exists -- the one refering to the
247  *    dictionary.
248  *   </para>
249  *   <para>
250  *    If calls are made to start accessing the other values then
251  *    #GVariant instances will exist for those values only for as long
252  *    as they are in use (ie: until you call g_variant_unref()).  The
253  *    type information is shared.  The serialised data and the buffer
254  *    management structure for that serialised data is shared by the
255  *    child.
256  *   </para>
257  *  </refsect3>
258  *  <refsect3>
259  *   <title>Summary</title>
260  *   <para>
261  *    To put the entire example together, for our dictionary mapping
262  *    strings to variants (with two entries, as given above), we are
263  *    using 91 bytes of memory for type information, 29 byes of memory
264  *    for the serialised data, 16 bytes for buffer management and 24
265  *    bytes for the #GVariant instance, or a total of 160 bytes, plus
266  *    malloc overhead.  If we were to use g_variant_get_child_value() to
267  *    access the two dictionary entries, we would use an additional 48
268  *    bytes.  If we were to have other dictionaries of the same type, we
269  *    would use more memory for the serialised data and buffer
270  *    management for those dictionaries, but the type information would
271  *    be shared.
272  *   </para>
273  *  </refsect3>
274  * </refsect2>
275  */
276
277 /* definition of GVariant structure is in gvariant-core.c */
278
279 /* this is a g_return_val_if_fail() for making
280  * sure a (GVariant *) has the required type.
281  */
282 #define TYPE_CHECK(value, TYPE, val) \
283   if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) {           \
284     g_return_if_fail_warning (G_LOG_DOMAIN, __PRETTY_FUNCTION__,  \
285                               "g_variant_is_of_type (" #value     \
286                               ", " #TYPE ")");                    \
287     return val;                                                   \
288   }
289
290 /* Numeric Type Constructor/Getters {{{1 */
291 /* < private >
292  * g_variant_new_from_trusted:
293  * @type: the #GVariantType
294  * @data: the data to use
295  * @size: the size of @data
296  * @returns: a new floating #GVariant
297  *
298  * Constructs a new trusted #GVariant instance from the provided data.
299  * This is used to implement g_variant_new_* for all the basic types.
300  */
301 static GVariant *
302 g_variant_new_from_trusted (const GVariantType *type,
303                             gconstpointer       data,
304                             gsize               size)
305 {
306   GVariant *value;
307   GBuffer *buffer;
308
309   buffer = g_buffer_new_from_data (data, size);
310   value = g_variant_new_from_buffer (type, buffer, TRUE);
311   g_buffer_unref (buffer);
312
313   return value;
314 }
315
316 /**
317  * g_variant_new_boolean:
318  * @boolean: a #gboolean value
319  * @returns: a new boolean #GVariant instance
320  *
321  * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
322  *
323  * Since: 2.24
324  **/
325 GVariant *
326 g_variant_new_boolean (gboolean value)
327 {
328   guchar v = value;
329
330   return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
331 }
332
333 /**
334  * g_variant_get_boolean:
335  * @value: a boolean #GVariant instance
336  * @returns: %TRUE or %FALSE
337  *
338  * Returns the boolean value of @value.
339  *
340  * It is an error to call this function with a @value of any type
341  * other than %G_VARIANT_TYPE_BOOLEAN.
342  *
343  * Since: 2.24
344  **/
345 gboolean
346 g_variant_get_boolean (GVariant *value)
347 {
348   const guchar *data;
349
350   TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
351
352   data = g_variant_get_data (value);
353
354   return data != NULL ? *data != 0 : FALSE;
355 }
356
357 /* the constructors and accessors for byte, int{16,32,64}, handles and
358  * doubles all look pretty much exactly the same, so we reduce
359  * copy/pasting here.
360  */
361 #define NUMERIC_TYPE(TYPE, type, ctype) \
362   GVariant *g_variant_new_##type (ctype value) {                \
363     return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE,   \
364                                        &value, sizeof value);   \
365   }                                                             \
366   ctype g_variant_get_##type (GVariant *value) {                \
367     const ctype *data;                                          \
368     TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0);             \
369     data = g_variant_get_data (value);                          \
370     return data != NULL ? *data : 0;                            \
371   }
372
373
374 /**
375  * g_variant_new_byte:
376  * @byte: a #guint8 value
377  * @returns: a new byte #GVariant instance
378  *
379  * Creates a new byte #GVariant instance.
380  *
381  * Since: 2.24
382  **/
383 /**
384  * g_variant_get_byte:
385  * @value: a byte #GVariant instance
386  * @returns: a #guchar
387  *
388  * Returns the byte value of @value.
389  *
390  * It is an error to call this function with a @value of any type
391  * other than %G_VARIANT_TYPE_BYTE.
392  *
393  * Since: 2.24
394  **/
395 NUMERIC_TYPE (BYTE, byte, guchar)
396
397 /**
398  * g_variant_new_int16:
399  * @int16: a #gint16 value
400  * @returns: a new int16 #GVariant instance
401  *
402  * Creates a new int16 #GVariant instance.
403  *
404  * Since: 2.24
405  **/
406 /**
407  * g_variant_get_int16:
408  * @value: a int16 #GVariant instance
409  * @returns: a #gint16
410  *
411  * Returns the 16-bit signed integer value of @value.
412  *
413  * It is an error to call this function with a @value of any type
414  * other than %G_VARIANT_TYPE_INT16.
415  *
416  * Since: 2.24
417  **/
418 NUMERIC_TYPE (INT16, int16, gint16)
419
420 /**
421  * g_variant_new_uint16:
422  * @uint16: a #guint16 value
423  * @returns: a new uint16 #GVariant instance
424  *
425  * Creates a new uint16 #GVariant instance.
426  *
427  * Since: 2.24
428  **/
429 /**
430  * g_variant_get_uint16:
431  * @value: a uint16 #GVariant instance
432  * @returns: a #guint16
433  *
434  * Returns the 16-bit unsigned integer value of @value.
435  *
436  * It is an error to call this function with a @value of any type
437  * other than %G_VARIANT_TYPE_UINT16.
438  *
439  * Since: 2.24
440  **/
441 NUMERIC_TYPE (UINT16, uint16, guint16)
442
443 /**
444  * g_variant_new_int32:
445  * @int32: a #gint32 value
446  * @returns: a new int32 #GVariant instance
447  *
448  * Creates a new int32 #GVariant instance.
449  *
450  * Since: 2.24
451  **/
452 /**
453  * g_variant_get_int32:
454  * @value: a int32 #GVariant instance
455  * @returns: a #gint32
456  *
457  * Returns the 32-bit signed integer value of @value.
458  *
459  * It is an error to call this function with a @value of any type
460  * other than %G_VARIANT_TYPE_INT32.
461  *
462  * Since: 2.24
463  **/
464 NUMERIC_TYPE (INT32, int32, gint32)
465
466 /**
467  * g_variant_new_uint32:
468  * @uint32: a #guint32 value
469  * @returns: a new uint32 #GVariant instance
470  *
471  * Creates a new uint32 #GVariant instance.
472  *
473  * Since: 2.24
474  **/
475 /**
476  * g_variant_get_uint32:
477  * @value: a uint32 #GVariant instance
478  * @returns: a #guint32
479  *
480  * Returns the 32-bit unsigned integer value of @value.
481  *
482  * It is an error to call this function with a @value of any type
483  * other than %G_VARIANT_TYPE_UINT32.
484  *
485  * Since: 2.24
486  **/
487 NUMERIC_TYPE (UINT32, uint32, guint32)
488
489 /**
490  * g_variant_new_int64:
491  * @int64: a #gint64 value
492  * @returns: a new int64 #GVariant instance
493  *
494  * Creates a new int64 #GVariant instance.
495  *
496  * Since: 2.24
497  **/
498 /**
499  * g_variant_get_int64:
500  * @value: a int64 #GVariant instance
501  * @returns: a #gint64
502  *
503  * Returns the 64-bit signed integer value of @value.
504  *
505  * It is an error to call this function with a @value of any type
506  * other than %G_VARIANT_TYPE_INT64.
507  *
508  * Since: 2.24
509  **/
510 NUMERIC_TYPE (INT64, int64, gint64)
511
512 /**
513  * g_variant_new_uint64:
514  * @uint64: a #guint64 value
515  * @returns: a new uint64 #GVariant instance
516  *
517  * Creates a new uint64 #GVariant instance.
518  *
519  * Since: 2.24
520  **/
521 /**
522  * g_variant_get_uint64:
523  * @value: a uint64 #GVariant instance
524  * @returns: a #guint64
525  *
526  * Returns the 64-bit unsigned integer value of @value.
527  *
528  * It is an error to call this function with a @value of any type
529  * other than %G_VARIANT_TYPE_UINT64.
530  *
531  * Since: 2.24
532  **/
533 NUMERIC_TYPE (UINT64, uint64, guint64)
534
535 /**
536  * g_variant_new_handle:
537  * @handle: a #gint32 value
538  * @returns: a new handle #GVariant instance
539  *
540  * Creates a new handle #GVariant instance.
541  *
542  * By convention, handles are indexes into an array of file descriptors
543  * that are sent alongside a DBus message.  If you're not interacting
544  * with DBus, you probably don't need them.
545  *
546  * Since: 2.24
547  **/
548 /**
549  * g_variant_get_handle:
550  * @value: a handle #GVariant instance
551  * @returns: a #gint32
552  *
553  * Returns the 32-bit signed integer value of @value.
554  *
555  * It is an error to call this function with a @value of any type other
556  * than %G_VARIANT_TYPE_HANDLE.
557  *
558  * By convention, handles are indexes into an array of file descriptors
559  * that are sent alongside a DBus message.  If you're not interacting
560  * with DBus, you probably don't need them.
561  *
562  * Since: 2.24
563  **/
564 NUMERIC_TYPE (HANDLE, handle, gint32)
565
566 /**
567  * g_variant_new_double:
568  * @floating: a #gdouble floating point value
569  * @returns: a new double #GVariant instance
570  *
571  * Creates a new double #GVariant instance.
572  *
573  * Since: 2.24
574  **/
575 /**
576  * g_variant_get_double:
577  * @value: a double #GVariant instance
578  * @returns: a #gdouble
579  *
580  * Returns the double precision floating point value of @value.
581  *
582  * It is an error to call this function with a @value of any type
583  * other than %G_VARIANT_TYPE_DOUBLE.
584  *
585  * Since: 2.24
586  **/
587 NUMERIC_TYPE (DOUBLE, double, gdouble)
588
589 /* Container type Constructor / Deconstructors {{{1 */
590 /**
591  * g_variant_new_maybe:
592  * @child_type: the #GVariantType of the child
593  * @child: the child value, or %NULL
594  * @returns: a new #GVariant maybe instance
595  *
596  * Depending on if @value is %NULL, either wraps @value inside of a
597  * maybe container or creates a Nothing instance for the given @type.
598  *
599  * At least one of @type and @value must be non-%NULL.  If @type is
600  * non-%NULL then it must be a definite type.  If they are both
601  * non-%NULL then @type must be the type of @value.
602  *
603  * Since: 2.24
604  **/
605 GVariant *
606 g_variant_new_maybe (const GVariantType *child_type,
607                      GVariant           *child)
608 {
609   GVariantType *maybe_type;
610   GVariant *value;
611
612   g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
613                         (child_type), 0);
614   g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
615   g_return_val_if_fail (child_type == NULL || child == NULL ||
616                         g_variant_is_of_type (child, child_type),
617                         NULL);
618
619   if (child_type == NULL)
620     child_type = g_variant_get_type (child);
621
622   maybe_type = g_variant_type_new_maybe (child_type);
623
624   if (child != NULL)
625     {
626       GVariant **children;
627       gboolean trusted;
628
629       children = g_new (GVariant *, 1);
630       children[0] = g_variant_ref_sink (child);
631       trusted = g_variant_is_trusted (children[0]);
632
633       value = g_variant_new_from_children (maybe_type, children, 1, trusted);
634     }
635   else
636     value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
637
638   g_variant_type_free (maybe_type);
639
640   return value;
641 }
642
643 /**
644  * g_variant_get_maybe:
645  * @value: a maybe-typed value
646  * @returns: the contents of @value, or %NULL
647  *
648  * Given a maybe-typed #GVariant instance, extract its value.  If the
649  * value is Nothing, then this function returns %NULL.
650  *
651  * Since: 2.24
652  **/
653 GVariant *
654 g_variant_get_maybe (GVariant *value)
655 {
656   TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
657
658   if (g_variant_n_children (value))
659     return g_variant_get_child_value (value, 0);
660
661   return NULL;
662 }
663
664 /**
665  * g_variant_new_variant:
666  * @value: a #GVariance instance
667  * @returns: a new variant #GVariant instance
668  *
669  * Boxes @value.  The result is a #GVariant instance representing a
670  * variant containing the original value.
671  *
672  * Since: 2.24
673  **/
674 GVariant *
675 g_variant_new_variant (GVariant *value)
676 {
677   g_return_val_if_fail (value != NULL, NULL);
678
679   return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
680                                       g_memdup (&value, sizeof value),
681                                       1, g_variant_is_trusted (value));
682 }
683
684 /**
685  * g_variant_get_variant:
686  * @value: a variant #GVariance instance
687  * @returns: the item contained in the variant
688  *
689  * Unboxes @value.  The result is the #GVariant instance that was
690  * contained in @value.
691  *
692  * Since: 2.24
693  **/
694 GVariant *
695 g_variant_get_variant (GVariant *value)
696 {
697   TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
698
699   return g_variant_get_child_value (value, 0);
700 }
701
702 /**
703  * g_variant_new_array:
704  * @child_type: the element type of the new array
705  * @children: an array of #GVariant pointers, the children
706  * @n_children: the length of @children
707  * @returns: a new #GVariant array
708  *
709  * Creates a new #GVariant array from @children.
710  *
711  * @child_type must be non-%NULL if @n_children is zero.  Otherwise, the
712  * child type is determined by inspecting the first element of the
713  * @children array.  If @child_type is non-%NULL then it must be a
714  * definite type.
715  *
716  * The items of the array are taken from the @children array.  No entry
717  * in the @children array may be %NULL.
718  *
719  * All items in the array must have the same type, which must be the
720  * same as @child_type, if given.
721  *
722  * Since: 2.24
723  **/
724 GVariant *
725 g_variant_new_array (const GVariantType *child_type,
726                      GVariant * const   *children,
727                      gsize               n_children)
728 {
729   GVariantType *array_type;
730   GVariant **my_children;
731   gboolean trusted;
732   GVariant *value;
733   gsize i;
734
735   g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
736   g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
737   g_return_val_if_fail (child_type == NULL ||
738                         g_variant_type_is_definite (child_type), NULL);
739
740   my_children = g_new (GVariant *, n_children);
741   trusted = TRUE;
742
743   if (child_type == NULL)
744     child_type = g_variant_get_type (children[0]);
745   array_type = g_variant_type_new_array (child_type);
746
747   for (i = 0; i < n_children; i++)
748     {
749       TYPE_CHECK (children[i], child_type, NULL);
750       my_children[i] = g_variant_ref_sink (children[i]);
751       trusted &= g_variant_is_trusted (children[i]);
752     }
753
754   value = g_variant_new_from_children (array_type, my_children,
755                                        n_children, trusted);
756   g_variant_type_free (array_type);
757
758   return value;
759 }
760
761 /*< private >
762  * g_variant_make_tuple_type:
763  * @children: an array of GVariant *
764  * @n_children: the length of @children
765  *
766  * Return the type of a tuple containing @children as its items.
767  **/
768 static GVariantType *
769 g_variant_make_tuple_type (GVariant * const *children,
770                            gsize             n_children)
771 {
772   const GVariantType **types;
773   GVariantType *type;
774   gsize i;
775
776   types = g_new (const GVariantType *, n_children);
777
778   for (i = 0; i < n_children; i++)
779     types[i] = g_variant_get_type (children[i]);
780
781   type = g_variant_type_new_tuple (types, n_children);
782   g_free (types);
783
784   return type;
785 }
786
787 /**
788  * g_variant_new_tuple:
789  * @children: the items to make the tuple out of
790  * @n_children: the length of @children
791  * @returns: a new #GVariant tuple
792  *
793  * Creates a new tuple #GVariant out of the items in @children.  The
794  * type is determined from the types of @children.  No entry in the
795  * @children array may be %NULL.
796  *
797  * If @n_children is 0 then the unit tuple is constructed.
798  *
799  * Since: 2.24
800  **/
801 GVariant *
802 g_variant_new_tuple (GVariant * const *children,
803                      gsize             n_children)
804 {
805   GVariantType *tuple_type;
806   GVariant **my_children;
807   gboolean trusted;
808   GVariant *value;
809   gsize i;
810
811   g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
812
813   my_children = g_new (GVariant *, n_children);
814   trusted = TRUE;
815
816   for (i = 0; i < n_children; i++)
817     {
818       my_children[i] = g_variant_ref_sink (children[i]);
819       trusted &= g_variant_is_trusted (children[i]);
820     }
821
822   tuple_type = g_variant_make_tuple_type (children, n_children);
823   value = g_variant_new_from_children (tuple_type, my_children,
824                                        n_children, trusted);
825   g_variant_type_free (tuple_type);
826
827   return value;
828 }
829
830 /*< private >
831  * g_variant_make_dict_entry_type:
832  * @key: a #GVariant, the key
833  * @val: a #GVariant, the value
834  *
835  * Return the type of a dictionary entry containing @key and @val as its
836  * children.
837  **/
838 static GVariantType *
839 g_variant_make_dict_entry_type (GVariant *key,
840                                 GVariant *val)
841 {
842   return g_variant_type_new_dict_entry (g_variant_get_type (key),
843                                         g_variant_get_type (val));
844 }
845
846 /**
847  * g_variant_new_dict_entry:
848  * @key: a basic #GVariant, the key
849  * @value: a #GVariant, the value
850  * @returns: a new dictionary entry #GVariant
851  *
852  * Creates a new dictionary entry #GVariant.  @key and @value must be
853  * non-%NULL.
854  *
855  * @key must be a value of a basic type (ie: not a container).
856  *
857  * Since: 2.24
858  **/
859 GVariant *
860 g_variant_new_dict_entry (GVariant *key,
861                           GVariant *value)
862 {
863   GVariantType *dict_type;
864   GVariant **children;
865   gboolean trusted;
866
867   g_return_val_if_fail (key != NULL && value != NULL, NULL);
868   g_return_val_if_fail (!g_variant_is_container (key), NULL);
869
870   children = g_new (GVariant *, 2);
871   children[0] = g_variant_ref_sink (key);
872   children[1] = g_variant_ref_sink (value);
873   trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
874
875   dict_type = g_variant_make_dict_entry_type (key, value);
876   value = g_variant_new_from_children (dict_type, children, 2, trusted);
877   g_variant_type_free (dict_type);
878
879   return value;
880 }
881
882 /**
883  * g_variant_get_fixed_array:
884  * @value: a #GVariant array with fixed-sized elements
885  * @n_elements: a pointer to the location to store the number of items
886  * @element_size: the size of each element
887  * @returns: a pointer to the fixed array
888  *
889  * Provides access to the serialised data for an array of fixed-sized
890  * items.
891  *
892  * @value must be an array with fixed-sized elements.  Numeric types are
893  * fixed-size as are tuples containing only other fixed-sized types.
894  *
895  * @element_size must be the size of a single element in the array.  For
896  * example, if calling this function for an array of 32 bit integers,
897  * you might say <code>sizeof (gint32)</code>.  This value isn't used
898  * except for the purpose of a double-check that the form of the
899  * seralised data matches the caller's expectation.
900  *
901  * @n_elements, which must be non-%NULL is set equal to the number of
902  * items in the array.
903  *
904  * Since: 2.24
905  **/
906 gconstpointer
907 g_variant_get_fixed_array (GVariant *value,
908                            gsize    *n_elements,
909                            gsize     element_size)
910 {
911   GVariantTypeInfo *array_info;
912   gsize array_element_size;
913   gconstpointer data;
914   gsize size;
915
916   TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
917
918   g_return_val_if_fail (n_elements != NULL, NULL);
919   g_return_val_if_fail (element_size > 0, NULL);
920
921   array_info = g_variant_get_type_info (value);
922   g_variant_type_info_query_element (array_info, NULL, &array_element_size);
923
924   g_return_val_if_fail (array_element_size, NULL);
925
926   if G_UNLIKELY (array_element_size != element_size)
927     {
928       if (array_element_size)
929         g_critical ("g_variant_get_fixed_array: assertion "
930                     "`g_variant_array_has_fixed_size (value, element_size)' "
931                     "failed: array size %"G_GSIZE_FORMAT" does not match "
932                     "given element_size %"G_GSIZE_FORMAT".",
933                     array_element_size, element_size);
934       else
935         g_critical ("g_variant_get_fixed_array: assertion "
936                     "`g_variant_array_has_fixed_size (value, element_size)' "
937                     "failed: array does not have fixed size.");
938     }
939
940   data = g_variant_get_data (value);
941   size = g_variant_get_size (value);
942
943   if (size % element_size)
944     *n_elements = 0;
945   else
946     *n_elements = size / element_size;
947
948   if (*n_elements)
949     return data;
950
951   return NULL;
952 }
953
954 /* String type constructor/getters/validation {{{1 */
955 /**
956  * g_variant_new_string:
957  * @string: a normal C nul-terminated string
958  * @returns: a new string #GVariant instance
959  *
960  * Creates a string #GVariant with the contents of @string.
961  *
962  * Since: 2.24
963  **/
964 GVariant *
965 g_variant_new_string (const gchar *string)
966 {
967   g_return_val_if_fail (string != NULL, NULL);
968
969   return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
970                                      string, strlen (string) + 1);
971 }
972
973 /**
974  * g_variant_new_object_path:
975  * @object_path: a normal C nul-terminated string
976  * @returns: a new object path #GVariant instance
977  *
978  * Creates a DBus object path #GVariant with the contents of @string.
979  * @string must be a valid DBus object path.  Use
980  * g_variant_is_object_path() if you're not sure.
981  *
982  * Since: 2.24
983  **/
984 GVariant *
985 g_variant_new_object_path (const gchar *object_path)
986 {
987   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
988
989   return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
990                                      object_path, strlen (object_path) + 1);
991 }
992
993 /**
994  * g_variant_is_object_path:
995  * @string: a normal C nul-terminated string
996  * @returns: %TRUE if @string is a DBus object path
997  *
998  * Determines if a given string is a valid DBus object path.  You
999  * should ensure that a string is a valid DBus object path before
1000  * passing it to g_variant_new_object_path().
1001  *
1002  * A valid object path starts with '/' followed by zero or more
1003  * sequences of characters separated by '/' characters.  Each sequence
1004  * must contain only the characters "[A-Z][a-z][0-9]_".  No sequence
1005  * (including the one following the final '/' character) may be empty.
1006  *
1007  * Since: 2.24
1008  **/
1009 gboolean
1010 g_variant_is_object_path (const gchar *string)
1011 {
1012   g_return_val_if_fail (string != NULL, FALSE);
1013
1014   return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1015 }
1016
1017 /**
1018  * g_variant_new_signature:
1019  * @signature: a normal C nul-terminated string
1020  * @returns: a new signature #GVariant instance
1021  *
1022  * Creates a DBus type signature #GVariant with the contents of
1023  * @string.  @string must be a valid DBus type signature.  Use
1024  * g_variant_is_signature() if you're not sure.
1025  *
1026  * Since: 2.24
1027  **/
1028 GVariant *
1029 g_variant_new_signature (const gchar *signature)
1030 {
1031   g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1032
1033   return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1034                                      signature, strlen (signature) + 1);
1035 }
1036
1037 /**
1038  * g_variant_is_signature:
1039  * @string: a normal C nul-terminated string
1040  * @returns: %TRUE if @string is a DBus type signature
1041  *
1042  * Determines if a given string is a valid DBus type signature.  You
1043  * should ensure that a string is a valid DBus object path before
1044  * passing it to g_variant_new_signature().
1045  *
1046  * DBus type signatures consist of zero or more definite #GVariantType
1047  * strings in sequence.
1048  *
1049  * Since: 2.24
1050  **/
1051 gboolean
1052 g_variant_is_signature (const gchar *string)
1053 {
1054   g_return_val_if_fail (string != NULL, FALSE);
1055
1056   return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1057 }
1058
1059 /**
1060  * g_variant_get_string:
1061  * @value: a string #GVariant instance
1062  * @length: a pointer to a #gsize, to store the length
1063  * @returns: the constant string
1064  *
1065  * Returns the string value of a #GVariant instance with a string
1066  * type.  This includes the types %G_VARIANT_TYPE_STRING,
1067  * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1068  *
1069  * If @length is non-%NULL then the length of the string (in bytes) is
1070  * returned there.  For trusted values, this information is already
1071  * known.  For untrusted values, a strlen() will be performed.
1072  *
1073  * It is an error to call this function with a @value of any type
1074  * other than those three.
1075  *
1076  * The return value remains valid as long as @value exists.
1077  *
1078  * Since: 2.24
1079  **/
1080 const gchar *
1081 g_variant_get_string (GVariant *value,
1082                       gsize    *length)
1083 {
1084   g_return_val_if_fail (value != NULL, NULL);
1085   g_return_val_if_fail (
1086     g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1087     g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1088     g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1089   gconstpointer data = g_variant_get_data (value);
1090   gsize size = g_variant_get_size (value);
1091
1092   if (!g_variant_is_trusted (value))
1093     {
1094       switch (g_variant_classify (value))
1095         {
1096         case G_VARIANT_CLASS_STRING:
1097           if (g_variant_serialiser_is_string (data, size))
1098             break;
1099
1100           data = "";
1101           size = 1;
1102           break;
1103
1104         case G_VARIANT_CLASS_OBJECT_PATH:
1105           if (g_variant_serialiser_is_object_path (data, size))
1106             break;
1107
1108           data = "/";
1109           size = 2;
1110           break;
1111
1112         case G_VARIANT_CLASS_SIGNATURE:
1113           if (g_variant_serialiser_is_signature (data, size))
1114             break;
1115
1116           data = "";
1117           size = 1;
1118           break;
1119
1120         default:
1121           g_assert_not_reached ();
1122         }
1123     }
1124
1125   if (length)
1126     *length = size - 1;
1127
1128   return data;
1129 }
1130
1131 /**
1132  * g_variant_dup_string:
1133  * @value: a string #GVariant instance
1134  * @length: a pointer to a #gsize, to store the length
1135  * @returns: a newly allocated string
1136  *
1137  * Similar to g_variant_get_string() except that instead of returning
1138  * a constant string, the string is duplicated.
1139  *
1140  * The return value must be freed using g_free().
1141  *
1142  * Since: 2.24
1143  **/
1144 gchar *
1145 g_variant_dup_string (GVariant *value,
1146                       gsize    *length)
1147 {
1148   return g_strdup (g_variant_get_string (value, length));
1149 }
1150
1151 /**
1152  * g_variant_new_strv:
1153  * @strv: an array of strings
1154  * @length: the length of @strv, or -1
1155  * @returns: a new floating #GVariant instance
1156  *
1157  * Constructs an array of strings #GVariant from the given array of
1158  * strings.
1159  *
1160  * If @length is not -1 then it gives the maximum length of @strv.  In
1161  * any case, a %NULL pointer in @strv is taken as a terminator.
1162  *
1163  * Since: 2.24
1164  **/
1165 GVariant *
1166 g_variant_new_strv (const gchar * const *strv,
1167                     gssize               length)
1168 {
1169   GVariant **strings;
1170   gsize i;
1171
1172   g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1173
1174   if (length < 0)
1175     for (length = 0; strv[length]; length++);
1176
1177   strings = g_new (GVariant *, length);
1178   for (i = 0; i < length; i++)
1179     strings[i] = g_variant_new_string (strv[i]);
1180
1181   return g_variant_new_from_children (G_VARIANT_TYPE ("as"),
1182                                       strings, length, TRUE);
1183 }
1184
1185 /**
1186  * g_variant_get_strv:
1187  * @value: an array of strings #GVariant
1188  * @length: the length of the result, or %NULL
1189  * @returns: an array of constant strings
1190  *
1191  * Gets the contents of an array of strings #GVariant.  This call
1192  * makes a shallow copy; the return result should be released with
1193  * g_free(), but the individual strings must not be modified.
1194  *
1195  * If @length is non-%NULL then the number of elements in the result
1196  * is stored there.  In any case, the resulting array will be
1197  * %NULL-terminated.
1198  *
1199  * For an empty array, @length will be set to 0 and a pointer to a
1200  * %NULL pointer will be returned.
1201  *
1202  * Since: 2.24
1203  **/
1204 const gchar **
1205 g_variant_get_strv (GVariant *value,
1206                     gsize    *length)
1207 {
1208   const gchar **strv;
1209   gsize n;
1210   gsize i;
1211
1212   TYPE_CHECK (value, G_VARIANT_TYPE ("as"), NULL);
1213
1214   g_variant_get_data (value);
1215   n = g_variant_n_children (value);
1216   strv = g_new (const gchar *, n + 1);
1217
1218   for (i = 0; i < n; i++)
1219     {
1220       GVariant *string;
1221
1222       string = g_variant_get_child_value (value, i);
1223       strv[i] = g_variant_get_string (string, NULL);
1224       g_variant_unref (string);
1225     }
1226   strv[i] = NULL;
1227
1228   if (length)
1229     *length = n;
1230
1231   return strv;
1232 }
1233
1234 /**
1235  * g_variant_dup_strv:
1236  * @value: an array of strings #GVariant
1237  * @length: the length of the result, or %NULL
1238  * @returns: an array of constant strings
1239  *
1240  * Gets the contents of an array of strings #GVariant.  This call
1241  * makes a deep copy; the return result should be released with
1242  * g_strfreev().
1243  *
1244  * If @length is non-%NULL then the number of elements in the result
1245  * is stored there.  In any case, the resulting array will be
1246  * %NULL-terminated.
1247  *
1248  * For an empty array, @length will be set to 0 and a pointer to a
1249  * %NULL pointer will be returned.
1250  *
1251  * Since: 2.24
1252  **/
1253 gchar **
1254 g_variant_dup_strv (GVariant *value,
1255                     gsize    *length)
1256 {
1257   gchar **strv;
1258   gsize n;
1259   gsize i;
1260
1261   TYPE_CHECK (value, G_VARIANT_TYPE ("as"), NULL);
1262
1263   n = g_variant_n_children (value);
1264   strv = g_new (gchar *, n + 1);
1265
1266   for (i = 0; i < n; i++)
1267     {
1268       GVariant *string;
1269
1270       string = g_variant_get_child_value (value, i);
1271       strv[i] = g_variant_dup_string (string, NULL);
1272       g_variant_unref (string);
1273     }
1274   strv[i] = NULL;
1275
1276   if (length)
1277     *length = n;
1278
1279   return strv;
1280 }
1281
1282 /* Type checking and querying {{{1 */
1283 /**
1284  * g_variant_get_type:
1285  * @value: a #GVariant
1286  * @returns: a #GVariantType
1287  *
1288  * Determines the type of @value.
1289  *
1290  * The return value is valid for the lifetime of @value and must not
1291  * be freed.
1292  *
1293  * Since: 2.24
1294  **/
1295 const GVariantType *
1296 g_variant_get_type (GVariant *value)
1297 {
1298   GVariantTypeInfo *type_info;
1299
1300   g_return_val_if_fail (value != NULL, NULL);
1301
1302   type_info = g_variant_get_type_info (value);
1303
1304   return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1305 }
1306
1307 /**
1308  * g_variant_get_type_string:
1309  * @value: a #GVariant
1310  * @returns: the type string for the type of @value
1311  *
1312  * Returns the type string of @value.  Unlike the result of calling
1313  * g_variant_type_peek_string(), this string is nul-terminated.  This
1314  * string belongs to #GVariant and must not be freed.
1315  *
1316  * Since: 2.24
1317  **/
1318 const gchar *
1319 g_variant_get_type_string (GVariant *value)
1320 {
1321   GVariantTypeInfo *type_info;
1322
1323   g_return_val_if_fail (value != NULL, NULL);
1324
1325   type_info = g_variant_get_type_info (value);
1326
1327   return g_variant_type_info_get_type_string (type_info);
1328 }
1329
1330 /**
1331  * g_variant_is_of_type:
1332  * @value: a #GVariant instance
1333  * @type: a #GVariantType
1334  * @returns: %TRUE if the type of @value matches @type
1335  *
1336  * Checks if a value has a type matching the provided type.
1337  *
1338  * Since: 2.24
1339  **/
1340 gboolean
1341 g_variant_is_of_type (GVariant           *value,
1342                       const GVariantType *type)
1343 {
1344   return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1345 }
1346
1347 /**
1348  * g_variant_is_container:
1349  * @value: a #GVariant instance
1350  * @returns: %TRUE if @value is a container
1351  *
1352  * Checks if @value is a container.
1353  */
1354 gboolean
1355 g_variant_is_container (GVariant *value)
1356 {
1357   return g_variant_type_is_container (g_variant_get_type (value));
1358 }
1359
1360
1361 /**
1362  * g_variant_classify:
1363  * @value: a #GVariant
1364  * @returns: the #GVariantClass of @value
1365  *
1366  * Classifies @value according to its top-level type.
1367  *
1368  * Since: 2.24
1369  **/
1370 /**
1371  * GVariantClass:
1372  * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
1373  * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
1374  * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
1375  * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
1376  * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
1377  * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
1378  * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
1379  * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
1380  * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
1381  * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating 
1382  *                          point value.
1383  * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
1384  * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a DBus object path 
1385  *                               string.
1386  * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a DBus signature string.
1387  * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
1388  * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
1389  * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
1390  * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
1391  * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
1392  *
1393  * The range of possible top-level types of #GVariant instances.
1394  *
1395  * Since: 2.24
1396  **/
1397 GVariantClass
1398 g_variant_classify (GVariant *value)
1399 {
1400   g_return_val_if_fail (value != NULL, 0);
1401
1402   return *g_variant_get_type_string (value);
1403 }
1404
1405 /* Pretty printer {{{1 */
1406 /**
1407  * g_variant_print_string:
1408  * @value: a #GVariant
1409  * @string: a #GString, or %NULL
1410  * @type_annotate: %TRUE if type information should be included in
1411  *                 the output
1412  * @returns: a #GString containing the string
1413  *
1414  * Behaves as g_variant_print(), but operates on a #GString.
1415  *
1416  * If @string is non-%NULL then it is appended to and returned.  Else,
1417  * a new empty #GString is allocated and it is returned.
1418  *
1419  * Since: 2.24
1420  **/
1421 GString *
1422 g_variant_print_string (GVariant *value,
1423                         GString  *string,
1424                         gboolean  type_annotate)
1425 {
1426   if G_UNLIKELY (string == NULL)
1427     string = g_string_new (NULL);
1428
1429   switch (g_variant_classify (value))
1430     {
1431     case G_VARIANT_CLASS_MAYBE:
1432       if (type_annotate)
1433         g_string_append_printf (string, "@%s ",
1434                                 g_variant_get_type_string (value));
1435
1436       if (g_variant_n_children (value))
1437         {
1438           gchar *printed_child;
1439           GVariant *element;
1440
1441           /* Nested maybes:
1442            *
1443            * Consider the case of the type "mmi".  In this case we could
1444            * write "Just Just 4", but "4" alone is totally unambiguous,
1445            * so we try to drop "Just" where possible.
1446            *
1447            * We have to be careful not to always drop "Just", though,
1448            * since "Nothing" needs to be distinguishable from "Just
1449            * Nothing".  The case where we need to ensure we keep the
1450            * "Just" is actually exactly the case where we have a nested
1451            * Nothing.
1452            *
1453            * Instead of searching for that nested Nothing, we just print
1454            * the contained value into a separate string and see if we
1455            * end up with "Nothing" at the end of it.  If so, we need to
1456            * add "Just" at our level.
1457            */
1458           element = g_variant_get_child_value (value, 0);
1459           printed_child = g_variant_print (element, FALSE);
1460           g_variant_unref (element);
1461
1462           if (g_str_has_suffix (printed_child, "Nothing"))
1463             g_string_append (string, "Just ");
1464           g_string_append (string, printed_child);
1465           g_free (printed_child);
1466         }
1467       else
1468         g_string_append (string, "Nothing");
1469
1470       break;
1471
1472     case G_VARIANT_CLASS_ARRAY:
1473       /* it's an array so the first character of the type string is 'a'
1474        *
1475        * if the first two characters are 'a{' then it's an array of
1476        * dictionary entries (ie: a dictionary) so we print that
1477        * differently.
1478        */
1479       if (g_variant_get_type_string (value)[1] == '{')
1480         /* dictionary */
1481         {
1482           const gchar *comma = "";
1483           gsize n, i;
1484
1485           if ((n = g_variant_n_children (value)) == 0)
1486             {
1487               if (type_annotate)
1488                 g_string_append_printf (string, "@%s ",
1489                                         g_variant_get_type_string (value));
1490               g_string_append (string, "{}");
1491               break;
1492             }
1493
1494           g_string_append_c (string, '{');
1495           for (i = 0; i < n; i++)
1496             {
1497               GVariant *entry, *key, *val;
1498
1499               g_string_append (string, comma);
1500               comma = ", ";
1501
1502               entry = g_variant_get_child_value (value, i);
1503               key = g_variant_get_child_value (entry, 0);
1504               val = g_variant_get_child_value (entry, 1);
1505               g_variant_unref (entry);
1506
1507               g_variant_print_string (key, string, type_annotate);
1508               g_variant_unref (key);
1509               g_string_append (string, ": ");
1510               g_variant_print_string (val, string, type_annotate);
1511               g_variant_unref (val);
1512               type_annotate = FALSE;
1513             }
1514           g_string_append_c (string, '}');
1515         }
1516       else
1517         /* normal (non-dictionary) array */
1518         {
1519           const gchar *comma = "";
1520           gsize n, i;
1521
1522           if ((n = g_variant_n_children (value)) == 0)
1523             {
1524               if (type_annotate)
1525                 g_string_append_printf (string, "@%s ",
1526                                         g_variant_get_type_string (value));
1527               g_string_append (string, "[]");
1528               break;
1529             }
1530
1531           g_string_append_c (string, '[');
1532           for (i = 0; i < n; i++)
1533             {
1534               GVariant *element;
1535
1536               g_string_append (string, comma);
1537               comma = ", ";
1538
1539               element = g_variant_get_child_value (value, i);
1540
1541               g_variant_print_string (element, string, type_annotate);
1542               g_variant_unref (element);
1543               type_annotate = FALSE;
1544             }
1545           g_string_append_c (string, ']');
1546         }
1547
1548       break;
1549
1550     case G_VARIANT_CLASS_TUPLE:
1551       {
1552         gsize n, i;
1553
1554         n = g_variant_n_children (value);
1555
1556         g_string_append_c (string, '(');
1557         for (i = 0; i < n; i++)
1558           {
1559             GVariant *element;
1560
1561             element = g_variant_get_child_value (value, i);
1562             g_variant_print_string (element, string, type_annotate);
1563             g_string_append (string, ", ");
1564           }
1565
1566         /* for >1 item:  remove final ", "
1567          * for 1 item:   remove final " ", but leave the ","
1568          * for 0 items:  there is only "(", so remove nothing
1569          */
1570         g_string_truncate (string, string->len - (n > 0) - (n > 1));
1571         g_string_append_c (string, ')');
1572       }
1573       break;
1574
1575     case G_VARIANT_CLASS_DICT_ENTRY:
1576       {
1577         GVariant *element;
1578
1579         g_string_append_c (string, '{');
1580
1581         element = g_variant_get_child_value (value, 0);
1582         g_variant_print_string (element, string, type_annotate);
1583         g_variant_unref (element);
1584
1585         g_string_append (string, ", ");
1586
1587         element = g_variant_get_child_value (value, 1);
1588         g_variant_print_string (element, string, type_annotate);
1589         g_variant_unref (element);
1590
1591         g_string_append_c (string, '}');
1592       }
1593       break;
1594
1595     case G_VARIANT_CLASS_VARIANT:
1596       {
1597         GVariant *child = g_variant_get_variant (value);
1598
1599         /* Always annotate types in nested variants, because they are
1600          * (by nature) of variable type.
1601          */
1602         g_string_append_c (string, '<');
1603         g_variant_print_string (child, string, TRUE);
1604         g_string_append_c (string, '>');
1605
1606         g_variant_unref (child);
1607       }
1608       break;
1609
1610     case G_VARIANT_CLASS_BOOLEAN:
1611       if (g_variant_get_boolean (value))
1612         g_string_append (string, "true");
1613       else
1614         g_string_append (string, "false");
1615       break;
1616
1617     case G_VARIANT_CLASS_STRING:
1618       {
1619         const gchar *str = g_variant_get_string (value, NULL);
1620         gchar *escaped = g_strescape (str, NULL);
1621
1622         g_string_append_printf (string, "\"%s\"", escaped);
1623
1624         g_free (escaped);
1625       }
1626       break;
1627
1628     case G_VARIANT_CLASS_BYTE:
1629       if (type_annotate)
1630         g_string_append (string, "byte ");
1631       g_string_append_printf (string, "0x%02x",
1632                               g_variant_get_byte (value));
1633       break;
1634
1635     case G_VARIANT_CLASS_INT16:
1636       if (type_annotate)
1637         g_string_append (string, "int16 ");
1638       g_string_append_printf (string, "%"G_GINT16_FORMAT,
1639                               g_variant_get_int16 (value));
1640       break;
1641
1642     case G_VARIANT_CLASS_UINT16:
1643       if (type_annotate)
1644         g_string_append (string, "uint16 ");
1645       g_string_append_printf (string, "%"G_GUINT16_FORMAT,
1646                               g_variant_get_uint16 (value));
1647       break;
1648
1649     case G_VARIANT_CLASS_INT32:
1650       /* Never annotate this type because it is the default for numbers
1651        * (and this is a *pretty* printer)
1652        */
1653       g_string_append_printf (string, "%"G_GINT32_FORMAT,
1654                               g_variant_get_int32 (value));
1655       break;
1656
1657     case G_VARIANT_CLASS_HANDLE:
1658       if (type_annotate)
1659         g_string_append (string, "handle ");
1660       g_string_append_printf (string, "%"G_GINT32_FORMAT,
1661                               g_variant_get_handle (value));
1662       break;
1663
1664     case G_VARIANT_CLASS_UINT32:
1665       if (type_annotate)
1666         g_string_append (string, "uint32 ");
1667       g_string_append_printf (string, "%"G_GUINT32_FORMAT,
1668                               g_variant_get_uint32 (value));
1669       break;
1670
1671     case G_VARIANT_CLASS_INT64:
1672       if (type_annotate)
1673         g_string_append (string, "int64 ");
1674       g_string_append_printf (string, "%"G_GINT64_FORMAT,
1675                               g_variant_get_int64 (value));
1676       break;
1677
1678     case G_VARIANT_CLASS_UINT64:
1679       if (type_annotate)
1680         g_string_append (string, "uint64 ");
1681       g_string_append_printf (string, "%"G_GUINT64_FORMAT,
1682                               g_variant_get_uint64 (value));
1683       break;
1684
1685     case G_VARIANT_CLASS_DOUBLE:
1686       {
1687         gchar buffer[100];
1688         gint i;
1689
1690         g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
1691
1692         for (i = 0; buffer[i]; i++)
1693           if (buffer[i] == '.' || buffer[i] == 'e' ||
1694               buffer[i] == 'n' || buffer[i] == 'N')
1695             break;
1696
1697         /* if there is no '.' or 'e' in the float then add one */
1698         if (buffer[i] == '\0')
1699           {
1700             buffer[i++] = '.';
1701             buffer[i++] = '0';
1702             buffer[i++] = '\0';
1703           }
1704
1705         g_string_append (string, buffer);
1706       }
1707       break;
1708
1709     case G_VARIANT_CLASS_OBJECT_PATH:
1710       if (type_annotate)
1711         g_string_append (string, "objectpath ");
1712       g_string_append_printf (string, "\"%s\"",
1713                               g_variant_get_string (value, NULL));
1714       break;
1715
1716     case G_VARIANT_CLASS_SIGNATURE:
1717       if (type_annotate)
1718         g_string_append (string, "signature ");
1719       g_string_append_printf (string, "\"%s\"",
1720                               g_variant_get_string (value, NULL));
1721       break;
1722
1723     default:
1724       g_assert_not_reached ();
1725   }
1726
1727   return string;
1728 }
1729
1730 /**
1731  * g_variant_print:
1732  * @value: a #GVariant
1733  * @type_annotate: %TRUE if type information should be included in
1734  *                 the output
1735  * @returns: a newly-allocated string holding the result.
1736  *
1737  * Pretty-prints @value in the format understood by g_variant_parse().
1738  *
1739  * If @type_annotate is %TRUE, then type information is included in
1740  * the output.
1741  */
1742 gchar *
1743 g_variant_print (GVariant *value,
1744                  gboolean  type_annotate)
1745 {
1746   return g_string_free (g_variant_print_string (value, NULL, type_annotate),
1747                         FALSE);
1748 };
1749
1750 /* Hash, Equal {{{1 */
1751 /**
1752  * g_variant_hash:
1753  * @value: a basic #GVariant value as a #gconstpointer
1754  * @returns: a hash value corresponding to @value
1755  *
1756  * Generates a hash value for a #GVariant instance.
1757  *
1758  * The output of this function is guaranteed to be the same for a given
1759  * value only per-process.  It may change between different processor
1760  * architectures or even different versions of GLib.  Do not use this
1761  * function as a basis for building protocols or file formats.
1762  *
1763  * The type of @value is #gconstpointer only to allow use of this
1764  * function with #GHashTable.  @value must be a #GVariant.
1765  *
1766  * Since: 2.24
1767  **/
1768 guint
1769 g_variant_hash (gconstpointer value_)
1770 {
1771   GVariant *value = (GVariant *) value_;
1772
1773   switch (g_variant_classify (value))
1774     {
1775     case G_VARIANT_CLASS_STRING:
1776     case G_VARIANT_CLASS_OBJECT_PATH:
1777     case G_VARIANT_CLASS_SIGNATURE:
1778       return g_str_hash (g_variant_get_string (value, NULL));
1779
1780     case G_VARIANT_CLASS_BOOLEAN:
1781       /* this is a very odd thing to hash... */
1782       return g_variant_get_boolean (value);
1783
1784     case G_VARIANT_CLASS_BYTE:
1785       return g_variant_get_byte (value);
1786
1787     case G_VARIANT_CLASS_INT16:
1788     case G_VARIANT_CLASS_UINT16:
1789       {
1790         const guint16 *ptr;
1791
1792         ptr = g_variant_get_data (value);
1793
1794         if (ptr)
1795           return *ptr;
1796         else
1797           return 0;
1798       }
1799
1800     case G_VARIANT_CLASS_INT32:
1801     case G_VARIANT_CLASS_UINT32:
1802     case G_VARIANT_CLASS_HANDLE:
1803       {
1804         const guint *ptr;
1805
1806         ptr = g_variant_get_data (value);
1807
1808         if (ptr)
1809           return *ptr;
1810         else
1811           return 0;
1812       }
1813
1814     case G_VARIANT_CLASS_INT64:
1815     case G_VARIANT_CLASS_UINT64:
1816     case G_VARIANT_CLASS_DOUBLE:
1817       /* need a separate case for these guys because otherwise
1818        * performance could be quite bad on big endian systems
1819        */
1820       {
1821         const guint *ptr;
1822
1823         ptr = g_variant_get_data (value);
1824
1825         if (ptr)
1826           return ptr[0] + ptr[1];
1827         else
1828           return 0;
1829       }
1830
1831     default:
1832       g_return_val_if_fail (!g_variant_is_container (value), 0);
1833       g_assert_not_reached ();
1834     }
1835 }
1836
1837 /**
1838  * g_variant_equal:
1839  * @one: a #GVariant instance
1840  * @two: a #GVariant instance
1841  * @returns: %TRUE if @one and @two are equal
1842  *
1843  * Checks if @one and @two have the same type and value.
1844  *
1845  * The types of @one and @two are #gconstpointer only to allow use of
1846  * this function with #GHashTable.  They must each be a #GVariant.
1847  *
1848  * Since: 2.24
1849  **/
1850 gboolean
1851 g_variant_equal (gconstpointer one,
1852                  gconstpointer two)
1853 {
1854   gboolean equal;
1855
1856   g_return_val_if_fail (one != NULL && two != NULL, FALSE);
1857
1858   if (g_variant_get_type_info ((GVariant *) one) !=
1859       g_variant_get_type_info ((GVariant *) two))
1860     return FALSE;
1861
1862   /* if both values are trusted to be in their canonical serialised form
1863    * then a simple memcmp() of their serialised data will answer the
1864    * question.
1865    *
1866    * if not, then this might generate a false negative (since it is
1867    * possible for two different byte sequences to represent the same
1868    * value).  for now we solve this by pretty-printing both values and
1869    * comparing the result.
1870    */
1871   if (g_variant_is_trusted ((GVariant *) one) &&
1872       g_variant_is_trusted ((GVariant *) two))
1873     {
1874       gconstpointer data_one, data_two;
1875       gsize size_one, size_two;
1876
1877       size_one = g_variant_get_size ((GVariant *) one);
1878       size_two = g_variant_get_size ((GVariant *) two);
1879
1880       if (size_one != size_two)
1881         return FALSE;
1882
1883       data_one = g_variant_get_data ((GVariant *) one);
1884       data_two = g_variant_get_data ((GVariant *) two);
1885
1886       equal = memcmp (data_one, data_two, size_one) == 0;
1887     }
1888   else
1889     {
1890       gchar *strone, *strtwo;
1891
1892       strone = g_variant_print ((GVariant *) one, FALSE);
1893       strtwo = g_variant_print ((GVariant *) two, FALSE);
1894       equal = strcmp (strone, strtwo) == 0;
1895       g_free (strone);
1896       g_free (strtwo);
1897     }
1898
1899   return equal;
1900 }
1901
1902 /* GVariantIter {{{1 */
1903 /**
1904  * GVariantIter:
1905  *
1906  * #GVariantIter is an opaque data structure and can only be accessed
1907  * using the following functions.
1908  **/
1909 struct stack_iter
1910 {
1911   GVariant *value;
1912   gssize n, i;
1913
1914   const gchar *loop_format;
1915
1916   gsize padding[3];
1917   gsize magic;
1918 };
1919
1920 struct heap_iter
1921 {
1922   struct stack_iter iter;
1923
1924   GVariant *value_ref;
1925   gsize magic;
1926 };
1927
1928 #define GVSI(i)                 ((struct stack_iter *) (i))
1929 #define GVHI(i)                 ((struct heap_iter *) (i))
1930 #define GVSI_MAGIC              ((gsize) 3579507750u)
1931 #define GVHI_MAGIC              ((gsize) 1450270775u)
1932 #define is_valid_iter(i)        (GVSI(i)->magic == GVSI_MAGIC)
1933 #define is_valid_heap_iter(i)   (GVHI(i)->magic == GVHI_MAGIC && \
1934                                  is_valid_iter(i))
1935
1936 /**
1937  * g_variant_iter_new:
1938  * @value: a container #GVariant
1939  * @returns: a new heap-allocated #GVariantIter
1940  *
1941  * Creates a heap-allocated #GVariantIter for iterating over the items
1942  * in @value.
1943  *
1944  * Use g_variant_iter_free() to free the return value when you no longer
1945  * need it.
1946  *
1947  * A reference is taken to @value and will be released only when
1948  * g_variant_iter_free() is called.
1949  *
1950  * Since: 2.24
1951  **/
1952 GVariantIter *
1953 g_variant_iter_new (GVariant *value)
1954 {
1955   GVariantIter *iter;
1956
1957   iter = (GVariantIter *) g_slice_new (struct heap_iter);
1958   GVHI(iter)->value_ref = g_variant_ref (value);
1959   GVHI(iter)->magic = GVHI_MAGIC;
1960
1961   g_variant_iter_init (iter, value);
1962
1963   return iter;
1964 }
1965
1966 /**
1967  * g_variant_iter_init:
1968  * @iter: a pointer to a #GVariantIter
1969  * @value: a container #GVariant
1970  * @returns: the number of items in @value
1971  *
1972  * Initialises (without allocating) a #GVariantIter.  @iter may be
1973  * completely uninitialised prior to this call; its old value is
1974  * ignored.
1975  *
1976  * The iterator remains valid for as long as @value exists, and need not
1977  * be freed in any way.
1978  *
1979  * Since: 2.24
1980  **/
1981 gsize
1982 g_variant_iter_init (GVariantIter *iter,
1983                      GVariant     *value)
1984 {
1985   g_assert (sizeof (GVariantIter) == sizeof (struct stack_iter));
1986
1987   GVSI(iter)->magic = GVSI_MAGIC;
1988   GVSI(iter)->value = value;
1989   GVSI(iter)->n = g_variant_n_children (value);
1990   GVSI(iter)->i = -1;
1991   GVSI(iter)->loop_format = NULL;
1992
1993   return GVSI(iter)->n;
1994 }
1995
1996 /**
1997  * g_variant_iter_copy:
1998  * @iter: a #GVariantIter
1999  * @returns: a new heap-allocated #GVariantIter
2000  *
2001  * Creates a new heap-allocated #GVariantIter to iterate over the
2002  * container that was being iterated over by @iter.  Iteration begins on
2003  * the new iterator from the current position of the old iterator but
2004  * the two copies are independent past that point.
2005  *
2006  * Use g_variant_iter_free() to free the return value when you no longer
2007  * need it.
2008  *
2009  * A reference is taken to the container that @iter is iterating over
2010  * and will be releated only when g_variant_iter_free() is called.
2011  *
2012  * Since: 2.24
2013  **/
2014 GVariantIter *
2015 g_variant_iter_copy (GVariantIter *iter)
2016 {
2017   GVariantIter *copy;
2018
2019   g_return_val_if_fail (is_valid_iter (iter), 0);
2020
2021   copy = g_variant_iter_new (GVSI(iter)->value);
2022   GVSI(copy)->i = GVSI(iter)->i;
2023
2024   return copy;
2025 }
2026
2027 /**
2028  * g_variant_iter_n_children:
2029  * @iter: a #GVariantIter
2030  * @returns: the number of children in the container
2031  *
2032  * Queries the number of child items in the container that we are
2033  * iterating over.  This is the total number of items -- not the number
2034  * of items remaining.
2035  *
2036  * This function might be useful for preallocation of arrays.
2037  *
2038  * Since: 2.24
2039  **/
2040 gsize
2041 g_variant_iter_n_children (GVariantIter *iter)
2042 {
2043   g_return_val_if_fail (is_valid_iter (iter), 0);
2044
2045   return GVSI(iter)->n;
2046 }
2047
2048 /**
2049  * g_variant_iter_free:
2050  * @iter: a heap-allocated #GVariantIter
2051  *
2052  * Frees a heap-allocated #GVariantIter.  Only call this function on
2053  * iterators that were returned by g_variant_iter_new() or
2054  * g_variant_iter_copy().
2055  *
2056  * Since: 2.24
2057  **/
2058 void
2059 g_variant_iter_free (GVariantIter *iter)
2060 {
2061   g_return_if_fail (is_valid_heap_iter (iter));
2062
2063   g_variant_unref (GVHI(iter)->value_ref);
2064   GVHI(iter)->magic = 0;
2065
2066   g_slice_free (struct heap_iter, GVHI(iter));
2067 }
2068
2069 /**
2070  * g_variant_iter_next_value:
2071  * @iter: a #GVariantIter
2072  * @returns: a #GVariant, or %NULL
2073  *
2074  * Gets the next item in the container.  If no more items remain then
2075  * %NULL is returned.
2076  *
2077  * Use g_variant_unref() to drop your reference on the return value when
2078  * you no longer need it.
2079  *
2080  * <example>
2081  *  <title>Iterating with g_variant_iter_next_value()</title>
2082  *  <programlisting>
2083  *   /<!-- -->* recursively iterate a container *<!-- -->/
2084  *   void
2085  *   iterate_container_recursive (GVariant *container)
2086  *   {
2087  *     GVariantIter iter;
2088  *     GVariant *child;
2089  *
2090  *     g_variant_iter_init (&iter, dictionary);
2091  *     while ((child = g_variant_iter_next_value (&iter)))
2092  *       {
2093  *         g_print ("type '%s'\n", g_variant_get_type_string (child));
2094  *
2095  *         if (g_variant_is_container (child))
2096  *           iterate_container_recursive (child);
2097  *
2098  *         g_variant_unref (child);
2099  *       }
2100  *   }
2101  * </programlisting>
2102  * </example>
2103  *
2104  * Since: 2.24
2105  **/
2106 GVariant *
2107 g_variant_iter_next_value (GVariantIter *iter)
2108 {
2109   g_return_val_if_fail (is_valid_iter (iter), FALSE);
2110
2111   if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2112     {
2113       g_critical ("g_variant_iter_next_value: must not be called again "
2114                   "after NULL has already been returned.");
2115       return NULL;
2116     }
2117
2118   GVSI(iter)->i++;
2119
2120   if (GVSI(iter)->i < GVSI(iter)->n)
2121     return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2122
2123   return NULL;
2124 }
2125
2126 /**
2127  * g_variant_iter_loop:
2128  * @iter: a #GVariantIter
2129  * @format_string: a GVariant format string
2130  * @...: the arguments to unpack the value into
2131  * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
2132  *           value
2133  *
2134  * Gets the next item in the container and unpacks it into the variable
2135  * argument list according to @format_string, returning %TRUE.
2136  *
2137  * If no more items remain then %FALSE is returned.
2138  *
2139  * On the first call to this function, the pointers appearing on the
2140  * variable argument list are assumed to point at uninitialised memory.
2141  * On the second and later calls, it is assumed that the same pointers
2142  * will be given and that they will point to the memory as set by the
2143  * previous call to this function.  This allows the previous values to
2144  * be freed, as appropriate.
2145  *
2146  * This function is intended to be used with a while loop as
2147  * demonstrated in the following example.  This function can only be
2148  * used when iterating over an array.  It is only valid to call this
2149  * function with a string constant for the format string and the same
2150  * string constant must be used each time.  Mixing calls to this
2151  * function and g_variant_iter_next() or g_variant_iter_next_value() on
2152  * the same iterator is not recommended.
2153  *
2154  * <example>
2155  *  <title>Memory management with g_variant_iter_loop()</title>
2156  *  <programlisting>
2157  *   /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
2158  *   void
2159  *   iterate_dictionary (GVariant *dictionary)
2160  *   {
2161  *     GVariantIter iter;
2162  *     GVariant *value;
2163  *     gchar *key;
2164  *
2165  *     g_variant_iter_init (&iter, dictionary);
2166  *     while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
2167  *       {
2168  *         g_print ("Item '%s' has type '%s'\n", key,
2169  *                  g_variant_get_type_string (value));
2170  *
2171  *         /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
2172  *       }
2173  *   }
2174  *  </programlisting>
2175  * </example>
2176  *
2177  * If you want a slightly less magical alternative that requires more
2178  * typing, see g_variant_iter_next().
2179  *
2180  * Since: 2.24
2181  **/
2182 gboolean
2183 g_variant_iter_loop (GVariantIter *iter,
2184                      const gchar  *format_string,
2185                      ...)
2186 {
2187   gboolean first_time = GVSI(iter)->loop_format == NULL;
2188   GVariant *value;
2189
2190   g_return_val_if_fail (first_time ||
2191                         format_string == GVSI(iter)->loop_format,
2192                         FALSE);
2193
2194   if (first_time)
2195     {
2196       TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
2197       GVSI(iter)->loop_format = format_string;
2198     }
2199
2200   value = g_variant_iter_next_value (iter);
2201
2202   if (value != NULL)
2203     {
2204       va_list ap;
2205
2206       va_start (ap, format_string);
2207       /* varargs get stuff */
2208       va_end (ap);
2209
2210       g_variant_unref (value);
2211     }
2212
2213   return value != NULL;
2214 }
2215
2216 /**
2217  * g_variant_iter_next:
2218  * @iter: a #GVariantIter
2219  * @format_string: a GVariant format string
2220  * @...: the arguments to unpack the value into
2221  * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
2222  *           value
2223  *
2224  * Gets the next item in the container and unpacks it into the variable
2225  * argument list according to @format_string, returning %TRUE.
2226  *
2227  * If no more items remain then %FALSE is returned.
2228  *
2229  * All of the pointers given on the variable arguments list of this
2230  * function are assumed to point at uninitialised memory.  It is the
2231  * responsibility of the caller to free all of the values returned by
2232  * the unpacking process.
2233  *
2234  * <example>
2235  *  <title>Memory management with g_variant_iter_next()</title>
2236  *  <programlisting>
2237  *   /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
2238  *   void
2239  *   iterate_dictionary (GVariant *dictionary)
2240  *   {
2241  *     GVariantIter iter;
2242  *     GVariant *value;
2243  *     gchar *key;
2244  *
2245  *     g_variant_iter_init (&iter, dictionary);
2246  *     while (g_variant_iter_next (&iter, "{sv}", &key, &value))
2247  *       {
2248  *         g_print ("Item '%s' has type '%s'\n", key,
2249  *                  g_variant_get_type_string (value));
2250  *
2251  *         /<!-- -->* must free data for ourselves *<!-- -->/
2252  *         g_variant_unref (value);
2253  *         g_free (key);
2254  *       }
2255  *   }
2256  *  </programlisting>
2257  * </example>
2258  *
2259  * For a solution that is likely to be more convenient to C programmers,
2260  * see g_variant_iter_loop().
2261  *
2262  * Since: 2.24
2263  **/
2264 gboolean
2265 g_variant_iter_next (GVariantIter *iter,
2266                      const gchar  *format_string,
2267                      ...)
2268 {
2269   GVariant *value;
2270
2271   value = g_variant_iter_next_value (iter);
2272
2273   if (value != NULL)
2274     {
2275       va_list ap;
2276
2277       va_start (ap, format_string);
2278       /* varargs get stuff */
2279       va_end (ap);
2280
2281       g_variant_unref (value);
2282     }
2283
2284   return value != NULL;
2285 }
2286
2287 /* GVariantBuilder {{{1 */
2288
2289 /**
2290  * GVariantBuilder:
2291  *
2292  * A utility class for constructing container-type #GVariant instances.
2293  *
2294  * This is an opaque structure and may only be accessed using the
2295  * following functions.
2296  *
2297  * #GVariantBuilder is not threadsafe in any way.  Do not attempt to
2298  * access it from more than one thread.
2299  **/
2300 struct _GVariantBuilder
2301 {
2302   GVariantBuilder *parent;
2303   GVariantType *type;
2304
2305   /* type constraint explicitly specified by 'type'.
2306    * for tuple types, this moves along as we add more items.
2307    */
2308   const GVariantType *expected_type;
2309
2310   /* type constraint implied by previous array item.
2311    */
2312   const GVariantType *prev_item_type;
2313
2314   /* constraints on the number of children.  max = -1 for unlimited. */
2315   gsize min_items;
2316   gsize max_items;
2317
2318   /* dynamically-growing pointer array */
2319   GVariant **children;
2320   gsize allocated_children;
2321   gsize offset;
2322
2323   /* set to '1' if all items in the container will have the same type
2324    * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
2325    */
2326   guint uniform_item_types : 1;
2327
2328   /* set to '1' until _end() or _close() is called. */
2329   guint is_active : 1;
2330
2331   /* set to '1' by _open() until _close() is called */
2332   guint has_child : 1;
2333
2334   /* set to '1' initially and changed to '0' if an untrusted value is
2335    * added
2336    */
2337   guint trusted : 1;
2338
2339   gint ref_count;
2340 };
2341
2342 /**
2343  * g_variant_builder_new:
2344  * @type: a container type
2345  * @returns: a #GVariantBuilder
2346  *
2347  * Creates a new #GVariantBuilder.
2348  *
2349  * @type must be non-%NULL.  It specifies the type of container to
2350  * construct.  It can be an indefinite type such as
2351  * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
2352  * Maybe, array, tuple, dictionary entry and variants may be
2353  * constructed.
2354  *
2355  * After the builder is created, values are added using
2356  * g_variant_builder_add_value() or g_variant_builder_add().
2357  *
2358  * After all the child values are added, g_variant_builder_end() frees
2359  * the builder and returns the #GVariant that was created.
2360  **/
2361 GVariantBuilder *
2362 g_variant_builder_new (const GVariantType *type)
2363 {
2364   GVariantBuilder *builder;
2365
2366   g_return_val_if_fail (type != NULL, NULL);
2367   g_return_val_if_fail (g_variant_type_is_container (type), NULL);
2368
2369   builder = g_slice_new (GVariantBuilder);
2370   builder->parent = NULL;
2371   builder->offset = 0;
2372
2373   builder->has_child = FALSE;
2374   builder->is_active = TRUE;
2375   builder->trusted = TRUE;
2376
2377   builder->type = g_variant_type_copy (type);
2378   builder->prev_item_type = NULL;
2379
2380   builder->ref_count = 1;
2381
2382   switch (*(const gchar *) type)
2383     {
2384     case G_VARIANT_CLASS_VARIANT:
2385       builder->uniform_item_types = TRUE;
2386       builder->allocated_children = 1;
2387       builder->expected_type = NULL;
2388       builder->min_items = 1;
2389       builder->max_items = 1;
2390       break;
2391
2392     case G_VARIANT_CLASS_ARRAY:
2393       builder->uniform_item_types = TRUE;
2394       builder->allocated_children = 8;
2395       builder->expected_type = g_variant_type_element (builder->type);
2396       builder->min_items = 0;
2397       builder->max_items = -1;
2398       break;
2399
2400     case G_VARIANT_CLASS_MAYBE:
2401       builder->uniform_item_types = TRUE;
2402       builder->allocated_children = 1;
2403       builder->expected_type = g_variant_type_element (builder->type);
2404       builder->min_items = 0;
2405       builder->max_items = 1;
2406       break;
2407
2408     case G_VARIANT_CLASS_DICT_ENTRY:
2409       builder->uniform_item_types = FALSE;
2410       builder->allocated_children = 2;
2411       builder->expected_type = g_variant_type_key (builder->type);
2412       builder->min_items = 2;
2413       builder->max_items = 2;
2414       break;
2415
2416     case 'r': /* G_VARIANT_TYPE_TUPLE was given */
2417       builder->uniform_item_types = FALSE;
2418       builder->allocated_children = 8;
2419       builder->expected_type = NULL;
2420       builder->min_items = 0;
2421       builder->max_items = -1;
2422       break;
2423
2424     case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
2425       builder->allocated_children = g_variant_type_n_items (type);
2426       builder->expected_type = g_variant_type_first (builder->type);
2427       builder->min_items = builder->allocated_children;
2428       builder->max_items = builder->allocated_children;
2429       builder->uniform_item_types = FALSE;
2430       break;
2431
2432     default:
2433       g_assert_not_reached ();
2434    }
2435
2436   builder->children = g_new (GVariant *, builder->allocated_children);
2437
2438   return builder;
2439 }
2440
2441 /**
2442  * g_variant_builder_unref:
2443  * @builder: a #GVariantBuilder
2444  *
2445  * Reduces the reference count on @builder.  If no other references are
2446  * held, the builder is freed.  If the builder was created using
2447  * g_variant_builder_open() then this may result in the destruction of
2448  * the parent builder too (if no other references are held on it).
2449  **/
2450 void
2451 g_variant_builder_unref (GVariantBuilder *builder)
2452 {
2453   GVariantBuilder *parent;
2454   gsize i;
2455
2456   if (--builder->ref_count)
2457     return;
2458
2459   for (i = 0; i < builder->offset; i++)
2460     g_variant_unref (builder->children[i]);
2461
2462   g_free (builder->children);
2463
2464   parent = builder->parent;
2465   g_slice_free (GVariantBuilder, builder);
2466
2467   g_variant_builder_unref (parent);
2468 }
2469
2470 /**
2471  * g_variant_builder_ref;
2472  * @builder: a #GVariantBuilder
2473  * @returns: the same #GVariantBuilder
2474  *
2475  * Increases the reference count on @builder by 1.
2476  **/
2477 GVariantBuilder *
2478 g_variant_builder_ref (GVariantBuilder *builder)
2479 {
2480   builder->ref_count++;
2481
2482   return builder;
2483 }
2484
2485 static void
2486 g_variant_builder_make_room (GVariantBuilder *builder)
2487 {
2488   if (builder->offset == builder->allocated_children)
2489     {
2490       builder->allocated_children *= 2;
2491       builder->children = g_renew (GVariant *, builder->children,
2492                                    builder->allocated_children);
2493     }
2494 }
2495
2496 /**
2497  * g_variant_builder_add_value:
2498  * @builder: a #GVariantBuilder
2499  * @value: a #GVariant
2500  *
2501  * Adds @value to @builder.
2502  *
2503  * It is an error to call this function in any way that would create an
2504  * inconsistent value to be constructed.  Some examples of this are
2505  * putting different types of items into an array, putting the wrong
2506  * types or number of items in a tuple, putting more than one value into
2507  * a variant, etc.
2508  **/
2509 void
2510 g_variant_builder_add_value (GVariantBuilder *builder,
2511                              GVariant        *value)
2512 {
2513   g_return_if_fail (builder != NULL && value != NULL);
2514   g_return_if_fail (builder->is_active && !builder->has_child);
2515   g_return_if_fail (builder->offset < builder->max_items);
2516   g_return_if_fail (!builder->expected_type ||
2517                     g_variant_is_of_type (value, builder->expected_type));
2518   g_return_if_fail (!builder->prev_item_type ||
2519                     g_variant_is_of_type (value, builder->prev_item_type));
2520
2521   builder->trusted &= g_variant_is_trusted (value);
2522
2523   if (!builder->uniform_item_types)
2524     {
2525       /* advance our expected type pointers */
2526       if (builder->expected_type)
2527         builder->expected_type =
2528           g_variant_type_next (builder->expected_type);
2529
2530       if (builder->prev_item_type)
2531         builder->prev_item_type =
2532           g_variant_type_next (builder->prev_item_type);
2533     }
2534   else
2535     builder->prev_item_type = g_variant_get_type (value);
2536
2537   g_variant_builder_make_room (builder);
2538
2539   builder->children[builder->offset++] = g_variant_ref_sink (value);
2540 }
2541
2542 /**
2543  * g_variant_builder_open:
2544  * @builder: a #GVariantBuilder
2545  * @type: a #GVariantType
2546  * @returns: a new #GVariantBuilder
2547  *
2548  * Opens a subcontainer inside the given @builder.
2549  *
2550  * This call consumes the caller's reference to @builder.
2551  * g_variant_builder_close() returns the reference.
2552  *
2553  * Even if additional references are held, it is not permissible to use
2554  * @builder in any way (except for further reference counting
2555  * operations) until g_variant_builder_close() is called on the return
2556  * value of this function.
2557  *
2558  * It is an error to call this function in any way that would create an
2559  * inconsistent value to be constructed.
2560  **/
2561 GVariantBuilder *
2562 g_variant_builder_open (GVariantBuilder    *builder,
2563                         const GVariantType *type)
2564 {
2565   GVariantBuilder *child;
2566
2567   g_return_val_if_fail (builder != NULL && type != NULL, NULL);
2568   g_return_val_if_fail (builder->is_active && !builder->has_child, NULL);
2569   g_return_val_if_fail (builder->offset < builder->max_items, NULL);
2570   g_return_val_if_fail (!builder->expected_type ||
2571                         g_variant_type_is_subtype_of (type,
2572                                                       builder->expected_type),
2573                         NULL);
2574   g_return_val_if_fail (!builder->prev_item_type ||
2575                         g_variant_type_is_subtype_of (builder->prev_item_type,
2576                                                       type), NULL);
2577   child = g_variant_builder_new (type);
2578   builder->has_child = TRUE;
2579   child->parent = builder;
2580
2581   /* push the prev_item_type down into the subcontainer */
2582   if (builder->prev_item_type)
2583     {
2584       if (!child->uniform_item_types)
2585         /* tuples and dict entries */
2586         child->prev_item_type =
2587           g_variant_type_first (builder->prev_item_type);
2588
2589       else if (!g_variant_type_is_variant (child->type))
2590         /* maybes and arrays */
2591         child->prev_item_type =
2592           g_variant_type_element (builder->prev_item_type);
2593     }
2594
2595   return child;
2596 }
2597
2598 /**
2599  * g_variant_builder_close:
2600  * @builder: a #GVariantBuilder
2601  * @returns: the original parent of @builder
2602  *
2603  * This function closes a builder that was created with a call to
2604  * g_variant_builder_open().
2605  *
2606  * This function consumes the caller's reference to @builder and drops
2607  * it.  The return result is the reference to the parent
2608  * #GVariantBuilder that was originally taken from the caller by
2609  * g_variant_builder_open().
2610  *
2611  * Even if additional references are held, it is not permissible to use
2612  * @builder in any way after this call except for further reference
2613  * counting operations.
2614  *
2615  * It is an error to call this function in any way that would create an
2616  * inconsistent value to be constructed (ie: insufficient number of
2617  * items added to a container with a specific number of children
2618  * required).  It is also an error to call this function if the builder
2619  * was created with an indefinite array or maybe type and no children
2620  * have been added; in this case it is impossible to infer the type of
2621  * the empty array.
2622  **/
2623 GVariantBuilder *
2624 g_variant_builder_close (GVariantBuilder *builder)
2625 {
2626   GVariantBuilder *parent;
2627
2628   g_return_val_if_fail (builder != NULL, NULL);
2629   g_return_val_if_fail (builder->parent != NULL, NULL);
2630   g_assert (builder->parent->has_child);
2631
2632   /* steal reference so _end() doesn't free it. */
2633   parent = builder->parent;
2634   builder->parent = NULL;
2635
2636   parent->has_child = FALSE;
2637
2638   g_variant_builder_add_value (parent, g_variant_builder_end (builder));
2639
2640   return parent;
2641 }
2642
2643 /*< private >
2644  * g_variant_make_maybe_type:
2645  * @element: a #GVariant
2646  *
2647  * Return the type of a maybe containing @element.
2648  */
2649 static GVariantType *
2650 g_variant_make_maybe_type (GVariant *element)
2651 {
2652   return g_variant_type_new_maybe (g_variant_get_type (element));
2653 }
2654
2655 /*< private >
2656  * g_variant_make_array_type:
2657  * @element: a #GVariant
2658  *
2659  * Return the type of an array containing @element.
2660  */
2661 static GVariantType *
2662 g_variant_make_array_type (GVariant *element)
2663 {
2664   return g_variant_type_new_array (g_variant_get_type (element));
2665 }
2666
2667 /**
2668  * g_variant_builder_end:
2669  * @builder: a #GVariantBuilder
2670  * @returns: a new, floating, #GVariant
2671  *
2672  * Ends the builder process and returns the constructed value.
2673  *
2674  * It is an error to call this function on a #GVariantBuilder created
2675  * by a call to g_variant_builder_open().  It is an error to call this
2676  * function if @builder has an outstanding child.  It is an error to
2677  * call this function in any case that g_variant_builder_check_end()
2678  * would return %FALSE.
2679  **/
2680 GVariant *
2681 g_variant_builder_end (GVariantBuilder *builder)
2682 {
2683   GVariantType *my_type;
2684   GVariant *value;
2685
2686   g_return_val_if_fail (builder != NULL, NULL);
2687   g_return_val_if_fail (builder->is_active && !builder->has_child, NULL);
2688   g_return_val_if_fail (builder->offset >= builder->min_items, NULL);
2689   g_return_val_if_fail (!builder->uniform_item_types ||
2690                         builder->prev_item_type != NULL ||
2691                         g_variant_type_is_definite (builder->type), NULL);
2692
2693   if (g_variant_type_is_definite (builder->type))
2694     my_type = g_variant_type_copy (builder->type);
2695
2696   else if (g_variant_type_is_maybe (builder->type))
2697     my_type = g_variant_make_maybe_type (builder->children[0]);
2698
2699   else if (g_variant_type_is_array (builder->type))
2700     my_type = g_variant_make_array_type (builder->children[0]);
2701
2702   else if (g_variant_type_is_tuple (builder->type))
2703     my_type = g_variant_make_tuple_type (builder->children, builder->offset);
2704
2705   else if (g_variant_type_is_dict_entry (builder->type))
2706     my_type = g_variant_make_dict_entry_type (builder->children[0],
2707                                               builder->children[1]);
2708   else
2709     g_assert_not_reached ();
2710
2711   value = g_variant_new_from_children (my_type,
2712                                        g_renew (GVariant *,
2713                                                 builder->children,
2714                                                 builder->offset),
2715                                        builder->offset,
2716                                        builder->trusted);
2717   builder->is_active = FALSE;
2718   builder->children = NULL;
2719
2720   g_variant_type_free (builder->type);
2721   g_slice_free (GVariantBuilder, builder);
2722   g_variant_type_free (my_type);
2723
2724   return value;
2725 }
2726
2727 /* Epilogue {{{1 */
2728 #define __G_VARIANT_C__
2729 #include "galiasdef.c"
2730
2731 /* vim:set foldmethod=marker: */