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