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