gvariant.c 173 KB
Newer Older
1
2
3
4
5
6
7
/*
 * Copyright © 2007, 2008 Ryan Lortie
 * Copyright © 2010 Codethink Limited
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
10
11
12
13
14
15
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
19
20
 *
 * Author: Ryan Lortie <desrt@desrt.ca>
 */

21
22
/* Prologue {{{1 */

23
24
25
#include "config.h"

#include <glib/gvariant-serialiser.h>
26
#include "gvariant-internal.h"
27
28
29
#include <glib/gvariant-core.h>
#include <glib/gtestutils.h>
#include <glib/gstrfuncs.h>
30
#include <glib/gslice.h>
31
32
33
34
35
#include <glib/ghash.h>
#include <glib/gmem.h>

#include <string.h>

36
#include "gstrfuncsprivate.h"
37
38

/**
Johan Dahlin's avatar
Johan Dahlin committed
39
 * SECTION:gvariant
40
41
42
43
 * @title: GVariant
 * @short_description: strongly typed value datatype
 * @see_also: GVariantType
 *
44
45
 * #GVariant is a variant datatype; it can contain one or more values
 * along with information about the type of the values.
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 *
 * A #GVariant may contain simple types, like an integer, or a boolean value;
 * or complex types, like an array of two strings, or a dictionary of key
 * value pairs. A #GVariant is also immutable: once it's been created neither
 * its type nor its content can be modified further.
 *
 * GVariant is useful whenever data needs to be serialized, for example when
 * sending method parameters in DBus, or when saving settings using GSettings.
 *
 * When creating a new #GVariant, you pass the data you want to store in it
 * along with a string representing the type of data you wish to pass to it.
 *
 * For instance, if you want to create a #GVariant holding an integer value you
 * can use:
 *
61
 * |[<!-- language="C" -->
62
 *   GVariant *v = g_variant_new ("u", 40);
63
 * ]|
64
 *
65
 * The string "u" in the first argument tells #GVariant that the data passed to
66
67
 * the constructor (40) is going to be an unsigned integer.
 *
68
69
 * More advanced examples of #GVariant in use can be found in documentation for
 * [GVariant format strings][gvariant-format-strings-pointers].
70
 *
71
 * The range of possible values is determined by the type.
72
 *
73
 * The type system used by #GVariant is #GVariantType. 
74
75
76
77
 *
 * #GVariant instances always have a type and a value (which are given
 * at construction time).  The type and value of a #GVariant instance
 * can never change other than by the #GVariant itself being
78
 * destroyed.  A #GVariant cannot contain a pointer.
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
 *
 * #GVariant is reference counted using g_variant_ref() and
 * g_variant_unref().  #GVariant also has floating reference counts --
 * see g_variant_ref_sink().
 *
 * #GVariant is completely threadsafe.  A #GVariant instance can be
 * concurrently accessed in any way from any number of threads without
 * problems.
 *
 * #GVariant is heavily optimised for dealing with data in serialised
 * form.  It works particularly well with data located in memory-mapped
 * files.  It can perform nearly all deserialisation operations in a
 * small constant time, usually touching only a single memory page.
 * Serialised #GVariant data can also be sent over the network.
 *
Murray Cumming's avatar
Murray Cumming committed
94
95
 * #GVariant is largely compatible with D-Bus.  Almost all types of
 * #GVariant instances can be sent over D-Bus.  See #GVariantType for
96
97
98
 * exceptions.  (However, #GVariant's serialisation format is not the same
 * as the serialisation format of a D-Bus message body: use #GDBusMessage,
 * in the gio library, for those.)
99
 *
100
 * For space-efficiency, the #GVariant serialisation format does not
101
102
103
104
105
 * automatically include the variant's length, type or endianness,
 * which must either be implied from context (such as knowledge that a
 * particular file format always contains a little-endian
 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
 * or supplied out-of-band (for instance, a length, type and/or endianness
106
107
108
 * indicator could be placed at the beginning of a file, network message
 * or network stream).
 *
Colin Walters's avatar
Colin Walters committed
109
 * A #GVariant's size is limited mainly by any lower level operating
110
111
112
113
 * system constraints, such as the number of bits in #gsize.  For
 * example, it is reasonable to have a 2GB file mapped into memory
 * with #GMappedFile, and call g_variant_new_from_data() on it.
 *
114
115
116
117
118
119
120
121
 * For convenience to C programmers, #GVariant features powerful
 * varargs-based value construction and destruction.  This feature is
 * designed to be embedded in other libraries.
 *
 * There is a Python-inspired text language for describing #GVariant
 * values.  #GVariant includes a printer for this language and a parser
 * with type inferencing.
 *
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
 * ## Memory Use
 *
 * #GVariant tries to be quite efficient with respect to memory use.
 * This section gives a rough idea of how much memory is used by the
 * current implementation.  The information here is subject to change
 * in the future.
 *
 * The memory allocated by #GVariant can be grouped into 4 broad
 * purposes: memory for serialised data, memory for the type
 * information cache, buffer management memory and memory for the
 * #GVariant structure itself.
 *
 * ## Serialised Data Memory
 *
 * This is the memory that is used for storing GVariant data in
 * serialised form.  This is what would be sent over the network or
138
139
 * what would end up on disk, not counting any indicator of the
 * endianness, or of the length or type of the top-level variant.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
 *
 * The amount of memory required to store a boolean is 1 byte. 16,
 * 32 and 64 bit integers and double precision floating point numbers
 * use their "natural" size.  Strings (including object path and
 * signature strings) are stored with a nul terminator, and as such
 * use the length of the string plus 1 byte.
 *
 * Maybe types use no space at all to represent the null value and
 * use the same amount of space (sometimes plus one byte) as the
 * equivalent non-maybe-typed value to represent the non-null case.
 *
 * Arrays use the amount of space required to store each of their
 * members, concatenated.  Additionally, if the items stored in an
 * array are not of a fixed-size (ie: strings, other arrays, etc)
 * then an additional framing offset is stored for each item.  The
 * size of this offset is either 1, 2 or 4 bytes depending on the
 * overall size of the container.  Additionally, extra padding bytes
 * are added as required for alignment of child values.
 *
 * Tuples (including dictionary entries) use the amount of space
 * required to store each of their members, concatenated, plus one
 * framing offset (as per arrays) for each non-fixed-sized item in
 * the tuple, except for the last one.  Additionally, extra padding
 * bytes are added as required for alignment of child values.
 *
 * Variants use the same amount of space as the item inside of the
 * variant, plus 1 byte, plus the length of the type string for the
 * item inside the variant.
 *
 * As an example, consider a dictionary mapping strings to variants.
 * In the case that the dictionary is empty, 0 bytes are required for
 * the serialisation.
 *
 * If we add an item "width" that maps to the int32 value of 500 then
 * we will use 4 byte to store the int32 (so 6 for the variant
 * containing it) and 6 bytes for the string.  The variant must be
 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
 * bytes.  6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
 * for the dictionary entry.  An additional 1 byte is added to the
 * array as a framing offset making a total of 15 bytes.
 *
 * If we add another entry, "title" that maps to a nullable string
 * that happens to have a value of null, then we use 0 bytes for the
 * null value (and 3 bytes for the variant to contain it along with
 * its type string) plus 6 bytes for the string.  Again, we need 2
 * padding bytes.  That makes a total of 6 + 2 + 3 = 11 bytes.
 *
 * We now require extra padding between the two items in the array.
188
189
190
191
 * After the 14 bytes of the first item, that's 2 bytes required.
 * We now require 2 framing offsets for an extra two
 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
 * dictionary.
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
 *
 * ## Type Information Cache
 *
 * For each GVariant type that currently exists in the program a type
 * information structure is kept in the type information cache.  The
 * type information structure is required for rapid deserialisation.
 *
 * Continuing with the above example, if a #GVariant exists with the
 * type "a{sv}" then a type information struct will exist for
 * "a{sv}", "{sv}", "s", and "v".  Multiple uses of the same type
 * will share the same type information.  Additionally, all
 * single-digit types are stored in read-only static memory and do
 * not contribute to the writable memory footprint of a program using
 * #GVariant.
 *
 * Aside from the type information structures stored in read-only
 * memory, there are two forms of type information.  One is used for
 * container types where there is a single element type: arrays and
 * maybe types.  The other is used for container types where there
 * are multiple element types: tuples and dictionary entries.
 *
 * Array type info structures are 6 * sizeof (void *), plus the
 * memory required to store the type string itself.  This means that
 * on 32-bit systems, the cache entry for "a{sv}" would require 30
 * bytes of memory (plus malloc overhead).
 *
 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
 * sizeof (void *) for each item in the tuple, plus the memory
 * required to store the type string itself.  A 2-item tuple, for
 * example, would have a type information structure that consumed
 * writable memory in the size of 14 * sizeof (void *) (plus type
 * string)  This means that on 32-bit systems, the cache entry for
 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
 *
 * This means that in total, for our "a{sv}" example, 91 bytes of
 * type information would be allocated.
 * 
 * The type information cache, additionally, uses a #GHashTable to
 * store and lookup the cached items and stores a pointer to this
 * hash table in static storage.  The hash table is freed when there
 * are zero items in the type cache.
 *
 * Although these sizes may seem large it is important to remember
 * that a program will probably only have a very small number of
 * different types of values in it and that only one type information
 * structure is required for many different values of the same type.
 *
 * ## Buffer Management Memory
 *
 * #GVariant uses an internal buffer management structure to deal
 * with the various different possible sources of serialised data
 * that it uses.  The buffer is responsible for ensuring that the
 * correct call is made when the data is no longer in use by
 * #GVariant.  This may involve a g_free() or a g_slice_free() or
 * even g_mapped_file_unref().
 *
 * One buffer management structure is used for each chunk of
 * serialised data.  The size of the buffer management structure
 * is 4 * (void *).  On 32-bit systems, that's 16 bytes.
 *
 * ## GVariant structure
 *
 * The size of a #GVariant structure is 6 * (void *).  On 32-bit
 * systems, that's 24 bytes.
 *
 * #GVariant structures only exist if they are explicitly created
 * with API calls.  For example, if a #GVariant is constructed out of
 * serialised data for the example given above (with the dictionary)
 * then although there are 9 individual values that comprise the
 * entire dictionary (two keys, two values, two variants containing
 * the values, two dictionary entries, plus the dictionary itself),
 * only 1 #GVariant instance exists -- the one referring to the
 * dictionary.
 *
 * If calls are made to start accessing the other values then
 * #GVariant instances will exist for those values only for as long
 * as they are in use (ie: until you call g_variant_unref()).  The
 * type information is shared.  The serialised data and the buffer
 * management structure for that serialised data is shared by the
 * child.
 *
 * ## Summary
 *
 * To put the entire example together, for our dictionary mapping
 * strings to variants (with two entries, as given above), we are
277
 * using 91 bytes of memory for type information, 29 bytes of memory
278
279
280
281
282
283
284
285
 * for the serialised data, 16 bytes for buffer management and 24
 * bytes for the #GVariant instance, or a total of 160 bytes, plus
 * malloc overhead.  If we were to use g_variant_get_child_value() to
 * access the two dictionary entries, we would use an additional 48
 * bytes.  If we were to have other dictionaries of the same type, we
 * would use more memory for the serialised data and buffer
 * management for those dictionaries, but the type information would
 * be shared.
286
287
288
289
290
291
292
293
294
 */

/* definition of GVariant structure is in gvariant-core.c */

/* this is a g_return_val_if_fail() for making
 * sure a (GVariant *) has the required type.
 */
#define TYPE_CHECK(value, TYPE, val) \
  if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) {           \
295
    g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC,            \
296
297
298
299
300
                              "g_variant_is_of_type (" #value     \
                              ", " #TYPE ")");                    \
    return val;                                                   \
  }

301
/* Numeric Type Constructor/Getters {{{1 */
302
303
304
305
306
307
308
309
/* < private >
 * g_variant_new_from_trusted:
 * @type: the #GVariantType
 * @data: the data to use
 * @size: the size of @data
 *
 * Constructs a new trusted #GVariant instance from the provided data.
 * This is used to implement g_variant_new_* for all the basic types.
310
311
 *
 * Returns: a new floating #GVariant
312
313
314
315
316
317
318
 */
static GVariant *
g_variant_new_from_trusted (const GVariantType *type,
                            gconstpointer       data,
                            gsize               size)
{
  GVariant *value;
319
  GBytes *bytes;
320

321
322
323
  bytes = g_bytes_new (data, size);
  value = g_variant_new_from_bytes (type, bytes, TRUE);
  g_bytes_unref (bytes);
324
325
326
327
328
329

  return value;
}

/**
 * g_variant_new_boolean:
330
 * @value: a #gboolean value
331
332
333
 *
 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
 *
334
335
 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
 *
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
 * Since: 2.24
 **/
GVariant *
g_variant_new_boolean (gboolean value)
{
  guchar v = value;

  return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
}

/**
 * g_variant_get_boolean:
 * @value: a boolean #GVariant instance
 *
 * Returns the boolean value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_BOOLEAN.
 *
355
356
 * Returns: %TRUE or %FALSE
 *
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
 * Since: 2.24
 **/
gboolean
g_variant_get_boolean (GVariant *value)
{
  const guchar *data;

  TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);

  data = g_variant_get_data (value);

  return data != NULL ? *data != 0 : FALSE;
}

/* the constructors and accessors for byte, int{16,32,64}, handles and
 * doubles all look pretty much exactly the same, so we reduce
 * copy/pasting here.
 */
#define NUMERIC_TYPE(TYPE, type, ctype) \
  GVariant *g_variant_new_##type (ctype value) {                \
    return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE,   \
                                       &value, sizeof value);   \
  }                                                             \
  ctype g_variant_get_##type (GVariant *value) {                \
    const ctype *data;                                          \
    TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0);             \
    data = g_variant_get_data (value);                          \
    return data != NULL ? *data : 0;                            \
  }


/**
 * g_variant_new_byte:
390
 * @value: a #guint8 value
391
392
393
 *
 * Creates a new byte #GVariant instance.
 *
394
395
 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
 *
396
397
398
399
400
401
402
403
404
405
406
 * Since: 2.24
 **/
/**
 * g_variant_get_byte:
 * @value: a byte #GVariant instance
 *
 * Returns the byte value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_BYTE.
 *
407
 * Returns: a #guint8
408
 *
409
410
 * Since: 2.24
 **/
411
NUMERIC_TYPE (BYTE, byte, guint8)
412
413
414

/**
 * g_variant_new_int16:
415
 * @value: a #gint16 value
416
417
418
 *
 * Creates a new int16 #GVariant instance.
 *
419
420
 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
 *
421
422
423
424
425
426
427
428
429
430
431
 * Since: 2.24
 **/
/**
 * g_variant_get_int16:
 * @value: a int16 #GVariant instance
 *
 * Returns the 16-bit signed integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_INT16.
 *
432
433
 * Returns: a #gint16
 *
434
435
436
437
438
439
 * Since: 2.24
 **/
NUMERIC_TYPE (INT16, int16, gint16)

/**
 * g_variant_new_uint16:
440
 * @value: a #guint16 value
441
442
443
 *
 * Creates a new uint16 #GVariant instance.
 *
444
445
 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
 *
446
447
448
449
450
451
452
453
454
455
456
 * Since: 2.24
 **/
/**
 * g_variant_get_uint16:
 * @value: a uint16 #GVariant instance
 *
 * Returns the 16-bit unsigned integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_UINT16.
 *
457
458
 * Returns: a #guint16
 *
459
460
461
462
463
464
 * Since: 2.24
 **/
NUMERIC_TYPE (UINT16, uint16, guint16)

/**
 * g_variant_new_int32:
465
 * @value: a #gint32 value
466
467
468
 *
 * Creates a new int32 #GVariant instance.
 *
469
470
 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
 *
471
472
473
474
475
476
477
478
479
480
481
 * Since: 2.24
 **/
/**
 * g_variant_get_int32:
 * @value: a int32 #GVariant instance
 *
 * Returns the 32-bit signed integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_INT32.
 *
482
483
 * Returns: a #gint32
 *
484
485
486
487
488
489
 * Since: 2.24
 **/
NUMERIC_TYPE (INT32, int32, gint32)

/**
 * g_variant_new_uint32:
490
 * @value: a #guint32 value
491
492
493
 *
 * Creates a new uint32 #GVariant instance.
 *
494
495
 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
 *
496
497
498
499
500
501
502
503
504
505
506
 * Since: 2.24
 **/
/**
 * g_variant_get_uint32:
 * @value: a uint32 #GVariant instance
 *
 * Returns the 32-bit unsigned integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_UINT32.
 *
507
508
 * Returns: a #guint32
 *
509
510
511
512
513
514
 * Since: 2.24
 **/
NUMERIC_TYPE (UINT32, uint32, guint32)

/**
 * g_variant_new_int64:
515
 * @value: a #gint64 value
516
517
518
 *
 * Creates a new int64 #GVariant instance.
 *
519
520
 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
 *
521
522
523
524
525
526
527
528
529
530
531
 * Since: 2.24
 **/
/**
 * g_variant_get_int64:
 * @value: a int64 #GVariant instance
 *
 * Returns the 64-bit signed integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_INT64.
 *
532
533
 * Returns: a #gint64
 *
534
535
536
537
538
539
 * Since: 2.24
 **/
NUMERIC_TYPE (INT64, int64, gint64)

/**
 * g_variant_new_uint64:
540
 * @value: a #guint64 value
541
542
543
 *
 * Creates a new uint64 #GVariant instance.
 *
544
545
 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
 *
546
547
548
549
550
551
552
553
554
555
556
 * Since: 2.24
 **/
/**
 * g_variant_get_uint64:
 * @value: a uint64 #GVariant instance
 *
 * Returns the 64-bit unsigned integer value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_UINT64.
 *
557
558
 * Returns: a #guint64
 *
559
560
561
562
563
564
 * Since: 2.24
 **/
NUMERIC_TYPE (UINT64, uint64, guint64)

/**
 * g_variant_new_handle:
565
 * @value: a #gint32 value
566
567
568
569
 *
 * Creates a new handle #GVariant instance.
 *
 * By convention, handles are indexes into an array of file descriptors
Murray Cumming's avatar
Murray Cumming committed
570
571
 * that are sent alongside a D-Bus message.  If you're not interacting
 * with D-Bus, you probably don't need them.
572
 *
573
574
 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
 *
575
576
577
578
579
580
581
582
583
584
585
586
 * Since: 2.24
 **/
/**
 * g_variant_get_handle:
 * @value: a handle #GVariant instance
 *
 * Returns the 32-bit signed integer value of @value.
 *
 * It is an error to call this function with a @value of any type other
 * than %G_VARIANT_TYPE_HANDLE.
 *
 * By convention, handles are indexes into an array of file descriptors
Murray Cumming's avatar
Murray Cumming committed
587
588
 * that are sent alongside a D-Bus message.  If you're not interacting
 * with D-Bus, you probably don't need them.
589
 *
590
591
 * Returns: a #gint32
 *
592
593
594
595
596
597
 * Since: 2.24
 **/
NUMERIC_TYPE (HANDLE, handle, gint32)

/**
 * g_variant_new_double:
598
 * @value: a #gdouble floating point value
599
600
601
 *
 * Creates a new double #GVariant instance.
 *
602
603
 * Returns: (transfer none): a floating reference to a new double #GVariant instance
 *
604
605
606
607
608
609
610
611
612
613
614
 * Since: 2.24
 **/
/**
 * g_variant_get_double:
 * @value: a double #GVariant instance
 *
 * Returns the double precision floating point value of @value.
 *
 * It is an error to call this function with a @value of any type
 * other than %G_VARIANT_TYPE_DOUBLE.
 *
615
616
 * Returns: a #gdouble
 *
617
618
619
620
 * Since: 2.24
 **/
NUMERIC_TYPE (DOUBLE, double, gdouble)

621
/* Container type Constructor / Deconstructors {{{1 */
622
623
/**
 * g_variant_new_maybe:
624
625
 * @child_type: (nullable): the #GVariantType of the child, or %NULL
 * @child: (nullable): the child value, or %NULL
626
 *
627
 * Depending on if @child is %NULL, either wraps @child inside of a
628
629
 * maybe container or creates a Nothing instance for the given @type.
 *
630
631
632
633
 * At least one of @child_type and @child must be non-%NULL.
 * If @child_type is non-%NULL then it must be a definite type.
 * If they are both non-%NULL then @child_type must be the type
 * of @child.
634
 *
635
636
637
 * If @child is a floating reference (see g_variant_ref_sink()), the new
 * instance takes ownership of @child.
 *
638
639
 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
 *
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
 * Since: 2.24
 **/
GVariant *
g_variant_new_maybe (const GVariantType *child_type,
                     GVariant           *child)
{
  GVariantType *maybe_type;
  GVariant *value;

  g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
                        (child_type), 0);
  g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
  g_return_val_if_fail (child_type == NULL || child == NULL ||
                        g_variant_is_of_type (child, child_type),
                        NULL);

  if (child_type == NULL)
    child_type = g_variant_get_type (child);

  maybe_type = g_variant_type_new_maybe (child_type);

  if (child != NULL)
    {
      GVariant **children;
      gboolean trusted;

      children = g_new (GVariant *, 1);
      children[0] = g_variant_ref_sink (child);
      trusted = g_variant_is_trusted (children[0]);

      value = g_variant_new_from_children (maybe_type, children, 1, trusted);
    }
  else
    value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);

  g_variant_type_free (maybe_type);

  return value;
}

/**
 * g_variant_get_maybe:
 * @value: a maybe-typed value
 *
 * Given a maybe-typed #GVariant instance, extract its value.  If the
 * value is Nothing, then this function returns %NULL.
 *
687
 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
688
 *
689
690
691
692
693
694
695
696
697
698
699
700
701
702
 * Since: 2.24
 **/
GVariant *
g_variant_get_maybe (GVariant *value)
{
  TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);

  if (g_variant_n_children (value))
    return g_variant_get_child_value (value, 0);

  return NULL;
}

/**
703
 * g_variant_new_variant: (constructor)
Allison Karlitskaya's avatar
Allison Karlitskaya committed
704
 * @value: a #GVariant instance
705
706
707
708
 *
 * Boxes @value.  The result is a #GVariant instance representing a
 * variant containing the original value.
 *
709
710
711
 * If @child is a floating reference (see g_variant_ref_sink()), the new
 * instance takes ownership of @child.
 *
712
713
 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
 *
714
715
716
717
718
719
720
 * Since: 2.24
 **/
GVariant *
g_variant_new_variant (GVariant *value)
{
  g_return_val_if_fail (value != NULL, NULL);

721
722
  g_variant_ref_sink (value);

723
  return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
724
                                      g_memdup2 (&value, sizeof value),
725
726
727
728
729
                                      1, g_variant_is_trusted (value));
}

/**
 * g_variant_get_variant:
Allison Karlitskaya's avatar
Allison Karlitskaya committed
730
 * @value: a variant #GVariant instance
731
732
733
734
 *
 * Unboxes @value.  The result is the #GVariant instance that was
 * contained in @value.
 *
735
736
 * Returns: (transfer full): the item contained in the variant
 *
737
738
739
740
741
742
743
744
745
746
747
 * Since: 2.24
 **/
GVariant *
g_variant_get_variant (GVariant *value)
{
  TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);

  return g_variant_get_child_value (value, 0);
}

/**
748
 * g_variant_new_array:
749
750
 * @child_type: (nullable): the element type of the new array
 * @children: (nullable) (array length=n_children): an array of
751
 *            #GVariant pointers, the children
752
 * @n_children: the length of @children
753
 *
754
755
756
757
758
759
760
761
762
763
764
765
 * Creates a new #GVariant array from @children.
 *
 * @child_type must be non-%NULL if @n_children is zero.  Otherwise, the
 * child type is determined by inspecting the first element of the
 * @children array.  If @child_type is non-%NULL then it must be a
 * definite type.
 *
 * The items of the array are taken from the @children array.  No entry
 * in the @children array may be %NULL.
 *
 * All items in the array must have the same type, which must be the
 * same as @child_type, if given.
766
 *
767
768
769
 * If the @children are floating references (see g_variant_ref_sink()), the
 * new instance takes ownership of them as if via g_variant_ref_sink().
 *
770
771
 * Returns: (transfer none): a floating reference to a new #GVariant array
 *
772
773
774
 * Since: 2.24
 **/
GVariant *
775
776
777
g_variant_new_array (const GVariantType *child_type,
                     GVariant * const   *children,
                     gsize               n_children)
778
{
779
780
781
782
783
  GVariantType *array_type;
  GVariant **my_children;
  gboolean trusted;
  GVariant *value;
  gsize i;
784

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
  g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
  g_return_val_if_fail (child_type == NULL ||
                        g_variant_type_is_definite (child_type), NULL);

  my_children = g_new (GVariant *, n_children);
  trusted = TRUE;

  if (child_type == NULL)
    child_type = g_variant_get_type (children[0]);
  array_type = g_variant_type_new_array (child_type);

  for (i = 0; i < n_children; i++)
    {
      TYPE_CHECK (children[i], child_type, NULL);
      my_children[i] = g_variant_ref_sink (children[i]);
      trusted &= g_variant_is_trusted (children[i]);
    }

  value = g_variant_new_from_children (array_type, my_children,
                                       n_children, trusted);
  g_variant_type_free (array_type);

  return value;
809
810
}

811
812
/*< private >
 * g_variant_make_tuple_type:
813
 * @children: (array length=n_children): an array of GVariant *
814
 * @n_children: the length of @children
815
 *
816
 * Return the type of a tuple containing @children as its items.
817
 **/
818
819
820
static GVariantType *
g_variant_make_tuple_type (GVariant * const *children,
                           gsize             n_children)
821
{
822
823
824
  const GVariantType **types;
  GVariantType *type;
  gsize i;
825

826
827
828
829
830
831
832
833
834
  types = g_new (const GVariantType *, n_children);

  for (i = 0; i < n_children; i++)
    types[i] = g_variant_get_type (children[i]);

  type = g_variant_type_new_tuple (types, n_children);
  g_free (types);

  return type;
835
836
837
}

/**
838
 * g_variant_new_tuple:
839
 * @children: (array length=n_children): the items to make the tuple out of
840
 * @n_children: the length of @children
841
 *
842
843
844
 * Creates a new tuple #GVariant out of the items in @children.  The
 * type is determined from the types of @children.  No entry in the
 * @children array may be %NULL.
845
 *
846
 * If @n_children is 0 then the unit tuple is constructed.
847
 *
848
849
850
 * If the @children are floating references (see g_variant_ref_sink()), the
 * new instance takes ownership of them as if via g_variant_ref_sink().
 *
851
852
 * Returns: (transfer none): a floating reference to a new #GVariant tuple
 *
853
854
 * Since: 2.24
 **/
855
856
857
GVariant *
g_variant_new_tuple (GVariant * const *children,
                     gsize             n_children)
858
{
859
860
861
862
863
  GVariantType *tuple_type;
  GVariant **my_children;
  gboolean trusted;
  GVariant *value;
  gsize i;
864

865
866
867
868
  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);

  my_children = g_new (GVariant *, n_children);
  trusted = TRUE;
869

870
871
872
873
874
  for (i = 0; i < n_children; i++)
    {
      my_children[i] = g_variant_ref_sink (children[i]);
      trusted &= g_variant_is_trusted (children[i]);
    }
875

876
877
878
879
880
881
882
883
884
885
886
887
  tuple_type = g_variant_make_tuple_type (children, n_children);
  value = g_variant_new_from_children (tuple_type, my_children,
                                       n_children, trusted);
  g_variant_type_free (tuple_type);

  return value;
}

/*< private >
 * g_variant_make_dict_entry_type:
 * @key: a #GVariant, the key
 * @val: a #GVariant, the value
888
 *
889
890
 * Return the type of a dictionary entry containing @key and @val as its
 * children.
891
 **/
892
893
894
static GVariantType *
g_variant_make_dict_entry_type (GVariant *key,
                                GVariant *val)
895
{
896
897
  return g_variant_type_new_dict_entry (g_variant_get_type (key),
                                        g_variant_get_type (val));
898
899
900
}

/**
901
 * g_variant_new_dict_entry: (constructor)
902
903
 * @key: a basic #GVariant, the key
 * @value: a #GVariant, the value
904
 *
905
906
 * Creates a new dictionary entry #GVariant. @key and @value must be
 * non-%NULL. @key must be a value of a basic type (ie: not a container).
907
 *
908
909
910
 * If the @key or @value are floating references (see g_variant_ref_sink()),
 * the new instance takes ownership of them as if via g_variant_ref_sink().
 *
911
912
 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
 *
913
914
 * Since: 2.24
 **/
915
916
917
GVariant *
g_variant_new_dict_entry (GVariant *key,
                          GVariant *value)
918
{
919
920
921
  GVariantType *dict_type;
  GVariant **children;
  gboolean trusted;
922

923
924
  g_return_val_if_fail (key != NULL && value != NULL, NULL);
  g_return_val_if_fail (!g_variant_is_container (key), NULL);
925

926
927
928
929
930
931
932
933
934
935
936
937
  children = g_new (GVariant *, 2);
  children[0] = g_variant_ref_sink (key);
  children[1] = g_variant_ref_sink (value);
  trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);

  dict_type = g_variant_make_dict_entry_type (key, value);
  value = g_variant_new_from_children (dict_type, children, 2, trusted);
  g_variant_type_free (dict_type);

  return value;
}

938
/**
939
 * g_variant_lookup: (skip)
940
941
942
943
944
945
946
947
948
949
950
951
 * @dictionary: a dictionary #GVariant
 * @key: the key to lookup in the dictionary
 * @format_string: a GVariant format string
 * @...: the arguments to unpack the value into
 *
 * Looks up a value in a dictionary #GVariant.
 *
 * This function is a wrapper around g_variant_lookup_value() and
 * g_variant_get().  In the case that %NULL would have been returned,
 * this function returns %FALSE.  Otherwise, it unpacks the returned
 * value and returns %TRUE.
 *
952
953
954
 * @format_string determines the C types that are used for unpacking
 * the values and also determines if the values are copied or borrowed,
 * see the section on
Matthias Clasen's avatar
Matthias Clasen committed
955
 * [GVariant format strings][gvariant-format-strings-pointers].
956
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
957
958
959
 * This function is currently implemented with a linear scan.  If you
 * plan to do many lookups then #GVariantDict may be more efficient.
 *
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
 * Returns: %TRUE if a value was unpacked
 *
 * Since: 2.28
 */
gboolean
g_variant_lookup (GVariant    *dictionary,
                  const gchar *key,
                  const gchar *format_string,
                  ...)
{
  GVariantType *type;
  GVariant *value;

  /* flatten */
  g_variant_get_data (dictionary);

  type = g_variant_format_string_scan_type (format_string, NULL, NULL);
  value = g_variant_lookup_value (dictionary, key, type);
  g_variant_type_free (type);

  if (value)
    {
      va_list ap;

      va_start (ap, format_string);
      g_variant_get_va (value, format_string, NULL, &ap);
      g_variant_unref (value);
      va_end (ap);

      return TRUE;
    }

  else
    return FALSE;
}

/**
Christian Persch's avatar
Christian Persch committed
997
 * g_variant_lookup_value:
998
999
 * @dictionary: a dictionary #GVariant
 * @key: the key to lookup in the dictionary
1000
 * @expected_type: (nullable): a #GVariantType, or %NULL
1001
1002
1003
 *
 * Looks up a value in a dictionary #GVariant.
 *
1004
1005
 * This function works with dictionaries of the type a{s*} (and equally
 * well with type a{o*}, but we only further discuss the string case
1006
1007
 * for sake of clarity).
 *
1008
1009
1010
1011
1012
1013
 * In the event that @dictionary has the type a{sv}, the @expected_type
 * string specifies what type of value is expected to be inside of the
 * variant. If the value inside the variant has a different type then
 * %NULL is returned. In the event that @dictionary has a value type other
 * than v then @expected_type must directly match the key type and it is
 * used to unpack the value directly or an error occurs.
1014
 *
1015
 * In either case, if @key is not found in @dictionary, %NULL is returned.
1016
1017
1018
1019
1020
 *
 * If the key is found and the value has the correct type, it is
 * returned.  If @expected_type was specified then any non-%NULL return
 * value will have this type.
 *
Allison Karlitskaya's avatar
Allison Karlitskaya committed
1021
1022
1023
 * This function is currently implemented with a linear scan.  If you
 * plan to do many lookups then #GVariantDict may be more efficient.
 *
1024
 * Returns: (transfer full): the value of the dictionary key, or %NULL
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
 *
 * Since: 2.28
 */
GVariant *
g_variant_lookup_value (GVariant           *dictionary,
                        const gchar        *key,
                        const GVariantType *expected_type)
{
  GVariantIter iter;
  GVariant *entry;
  GVariant *value;

  g_return_val_if_fail (g_variant_is_of_type (dictionary,
                                              G_VARIANT_TYPE ("a{s*}")) ||
                        g_variant_is_of_type (dictionary,
                                              G_VARIANT_TYPE ("a{o*}")),
                        NULL);

  g_variant_iter_init (&iter, dictionary);

  while ((entry = g_variant_iter_next_value (&iter)))
    {
      GVariant *entry_key;
      gboolean matches;

      entry_key = g_variant_get_child_value (entry, 0);
      matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
      g_variant_unref (entry_key);

      if (matches)
        break;

      g_variant_unref (entry);
    }

  if (entry == NULL)
    return NULL;

  value = g_variant_get_child_value (entry, 1);
  g_variant_unref (entry);

  if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
    {
      GVariant *tmp;

      tmp = g_variant_get_variant (value);
      g_variant_unref (value);

      if (expected_type && !g_variant_is_of_type (tmp, expected_type))
        {
          g_variant_unref (tmp);
          tmp = NULL;
        }

      value = tmp;
    }

  g_return_val_if_fail (expected_type == NULL || value == NULL ||
                        g_variant_is_of_type (value, expected_type), NULL);

  return value;
}

1088
1089
1090
/**
 * g_variant_get_fixed_array:
 * @value: a #GVariant array with fixed-sized elements
1091
 * @n_elements: (out): a pointer to the location to store the number of items
1092
1093
1094
1095
1096
1097
 * @element_size: the size of each element
 *
 * Provides access to the serialised data for an array of fixed-sized
 * items.
 *
 * @value must be an array with fixed-sized elements.  Numeric types are
1098
1099
1100
1101
 * fixed-size, as are tuples containing only other fixed-sized types.
 *
 * @element_size must be the size of a single element in the array,
 * as given by the section on
Matthias Clasen's avatar
Matthias Clasen committed
1102
 * [serialized data memory][gvariant-serialised-data-memory].
1103
1104
 *
 * In particular, arrays of these fixed-sized types can be interpreted
1105
1106
 * as an array of the given C type, with @element_size set to the size
 * the appropriate type:
1107
1108
 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1109
 * - %G_VARIANT_TYPE_BYTE: #guint8
1110
1111
 * - %G_VARIANT_TYPE_HANDLE: #guint32
 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1112
 *
1113
 * For example, if calling this function for an array of 32-bit integers,
1114
 * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1115
1116
 * of a double-check that the form of the serialised data matches the caller's
 * expectation.
1117
 *
1118
 * @n_elements, which must be non-%NULL, is set equal to the number of
1119
1120
 * items in the array.
 *
1121
 * Returns: (array length=n_elements) (transfer none): a pointer to
1122
 *     the fixed array
1123
 *
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
 * Since: 2.24
 **/
gconstpointer
g_variant_get_fixed_array (GVariant *value,
                           gsize    *n_elements,
                           gsize     element_size)
{
  GVariantTypeInfo *array_info;
  gsize array_element_size;
  gconstpointer data;
  gsize size;

  TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);

  g_return_val_if_fail (n_elements != NULL, NULL);
  g_return_val_if_fail (element_size > 0, NULL);

  array_info = g_variant_get_type_info (value);
  g_variant_type_info_query_element (array_info, NULL, &array_element_size);

  g_return_val_if_fail (array_element_size, NULL);

  if G_UNLIKELY (array_element_size != element_size)
    {
      if (array_element_size)
        g_critical ("g_variant_get_fixed_array: assertion "
1150
                    "'g_variant_array_has_fixed_size (value, element_size)' "
1151
1152
1153
1154
1155
                    "failed: array size %"G_GSIZE_FORMAT" does not match "
                    "given element_size %"G_GSIZE_FORMAT".",
                    array_element_size, element_size);
      else
        g_critical ("g_variant_get_fixed_array: assertion "
1156
                    "'g_variant_array_has_fixed_size (value, element_size)' "
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
                    "failed: array does not have fixed size.");
    }

  data = g_variant_get_data (value);
  size = g_variant_get_size (value);

  if (size % element_size)
    *n_elements = 0;
  else
    *n_elements = size / element_size;

  if (*n_elements)
    return data;

  return NULL;
}

1174
1175
1176
1177
1178
1179
1180
/**
 * g_variant_new_fixed_array:
 * @element_type: the #GVariantType of each element
 * @elements: a pointer to the fixed array of contiguous elements
 * @n_elements: the number of elements
 * @element_size: the size of each element
 *
1181
1182
 * Constructs a new array #GVariant instance, where the elements are
 * of @element_type type.
1183
 *
1184
 * @elements must be an array with fixed-sized elements.  Numeric types are
1185
1186
 * fixed-size as are tuples containing only other fixed-sized types.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1187
1188
1189
1190
1191
 * @element_size must be the size of a single element in the array.
 * For example, if calling this function for an array of 32-bit integers,
 * you might say sizeof(gint32). This value isn't used except for the purpose
 * of a double-check that the form of the serialised data matches the caller's
 * expectation.
1192
 *
1193
 * @n_elements must be the length of the @elements array.
1194
 *
1195
1196
 * Returns: (transfer none): a floating reference to a new array #GVariant instance
 *
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
 * Since: 2.32
 **/
GVariant *
g_variant_new_fixed_array (const GVariantType  *element_type,
                           gconstpointer        elements,
                           gsize                n_elements,
                           gsize                element_size)
{
  GVariantType *array_type;
  gsize array_element_size;
  GVariantTypeInfo *array_info;
  GVariant *value;
  gpointer data;

  g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
  g_return_val_if_fail (element_size > 0, NULL);

  array_type = g_variant_type_new_array (element_type);
  array_info = g_variant_type_info_get (array_type);
  g_variant_type_info_query_element (array_info, NULL, &array_element_size);
  if G_UNLIKELY (array_element_size != element_size)
    {
      if (array_element_size)
        g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
                    " does not match given element_size %" G_GSIZE_FORMAT ".",
                    array_element_size, element_size);
      else
        g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
      return NULL;
    }

1228
  data = g_memdup2 (elements, n_elements * element_size);
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
  value = g_variant_new_from_data (array_type, data,
                                   n_elements * element_size,
                                   FALSE, g_free, data);

  g_variant_type_free (array_type);
  g_variant_type_info_unref (array_info);

  return value;
}

1239
1240
1241
/* String type constructor/getters/validation {{{1 */
/**
 * g_variant_new_string:
1242
 * @string: a normal UTF-8 nul-terminated string
1243
1244
1245
 *
 * Creates a string #GVariant with the contents of @string.
 *
1246
1247
1248
 * @string must be valid UTF-8, and must not be %NULL. To encode
 * potentially-%NULL strings, use g_variant_new() with `ms` as the
 * [format string][gvariant-format-strings-maybe-types].
1249
 *
1250
1251
 * Returns: (transfer none): a floating reference to a new string #GVariant instance
 *
1252
1253
1254
1255
1256
1257
 * Since: 2.24
 **/
GVariant *
g_variant_new_string (const gchar *string)
{
  g_return_val_if_fail (string != NULL, NULL);
1258
  g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1259
1260
1261
1262
1263

  return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
                                     string, strlen (string) + 1);
}

1264
1265
/**
 * g_variant_new_take_string: (skip)
1266
 * @string: a normal UTF-8 nul-terminated string
1267
1268
1269
 *
 * Creates a string #GVariant with the contents of @string.
 *
1270
1271
 * @string must be valid UTF-8, and must not be %NULL. To encode
 * potentially-%NULL strings, use this with g_variant_new_maybe().
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
 *
 * This function consumes @string.  g_free() will be called on @string
 * when it is no longer required.
 *
 * You must not modify or access @string in any other way after passing
 * it to this function.  It is even possible that @string is immediately
 * freed.
 *
 * Returns: (transfer none): a floating reference to a new string
 *   #GVariant instance
 *
 * Since: 2.38
 **/
GVariant *
g_variant_new_take_string (gchar *string)
{
  GVariant *value;
  GBytes *bytes;

  g_return_val_if_fail (string != NULL, NULL);
  g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);

  bytes = g_bytes_new_take (string, strlen (string) + 1);
  value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
  g_bytes_unref (bytes);

  return value;
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
/**
 * g_variant_new_printf: (skip)
 * @format_string: a printf-style format string
 * @...: arguments for @format_string
 *
 * Creates a string-type GVariant using printf formatting.
 *
 * This is similar to calling g_strdup_printf() and then
 * g_variant_new_string() but it saves a temporary variable and an
 * unnecessary copy.
 *
 * Returns: (transfer none): a floating reference to a new string
 *   #GVariant instance
 *
 * Since: 2.38
 **/
GVariant *
g_variant_new_printf (const gchar *format_string,
                      ...)
{
  GVariant *value;
  GBytes *bytes;
  gchar *string;
  va_list ap;

  g_return_val_if_fail (format_string != NULL, NULL);

  va_start (ap, format_string);
  string = g_strdup_vprintf (format_string, ap);
  va_end (ap);

  bytes = g_bytes_new_take (string, strlen (string) + 1);
  value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
  g_bytes_unref (bytes);

  return value;
}

1339
1340
1341
1342
/**
 * g_variant_new_object_path:
 * @object_path: a normal C nul-terminated string
 *
Murray Cumming's avatar
Murray Cumming committed
1343
1344
 * Creates a D-Bus object path #GVariant with the contents of @string.
 * @string must be a valid D-Bus object path.  Use
1345
1346
 * g_variant_is_object_path() if you're not sure.
 *
1347
1348
 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
 *
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
 * Since: 2.24
 **/
GVariant *
g_variant_new_object_path (const gchar *object_path)
{
  g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);

  return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
                                     object_path, strlen (object_path) + 1);
}

/**
 * g_variant_is_object_path:
 * @string: a normal C nul-terminated string
 *
Murray Cumming's avatar
Murray Cumming committed
1364
1365
 * Determines if a given string is a valid D-Bus object path.  You
 * should ensure that a string is a valid D-Bus object path before
1366
1367
 * passing it to g_variant_new_object_path().
 *
1368
1369
1370
1371
 * A valid object path starts with `/` followed by zero or more
 * sequences of characters separated by `/` characters.  Each sequence
 * must contain only the characters `[A-Z][a-z][0-9]_`.  No sequence
 * (including the one following the final `/` character) may be empty.
1372
 *
1373
1374
 * Returns: %TRUE if @string is a D-Bus object path
 *
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
 * Since: 2.24
 **/
gboolean
g_variant_is_object_path (const gchar *string)
{
  g_return_val_if_fail (string != NULL, FALSE);

  return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
}

/**
 * g_variant_new_signature:
 * @signature: a normal C nul-terminated string
 *
Murray Cumming's avatar
Murray Cumming committed
1389
1390
 * Creates a D-Bus type signature #GVariant with the contents of
 * @string.  @string must be a valid D-Bus type signature.  Use
1391
1392
 * g_variant_is_signature() if you're not sure.
 *
1393
1394
 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
 *
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
 * Since: 2.24
 **/
GVariant *
g_variant_new_signature (const gchar *signature)
{
  g_return_val_if_fail (g_variant_is_signature (signature), NULL);

  return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
                                     signature, strlen (signature) + 1);
}

/**
 * g_variant_is_signature:
 * @string: a normal C nul-terminated string
 *
Murray Cumming's avatar
Murray Cumming committed
1410
1411
 * Determines if a given string is a valid D-Bus type signature.  You
 * should ensure that a string is a valid D-Bus type signature before
1412
1413
 * passing it to g_variant_new_signature().
 *
Murray Cumming's avatar
Murray Cumming committed
1414
 * D-Bus type signatures consist of zero or more definite #GVariantType
1415
1416
 * strings in sequence.
 *
1417
1418
 * Returns: %TRUE if @string is a D-Bus type signature
 *
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
 * Since: 2.24
 **/
gboolean
g_variant_is_signature (const gchar *string)
{
  g_return_val_if_fail (string != NULL, FALSE);

  return g_variant_serialiser_is_signature (string, strlen (string) + 1);
}

/**
 * g_variant_get_string:
 * @value: a string #GVariant instance
1432
 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1433
 *          to store the length
1434
1435
1436
 *
 * Returns the string value of a #GVariant instance with a string
 * type.  This includes the types %G_VARIANT_TYPE_STRING,
1437
1438
 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
 *
1439
 * The string will always be UTF-8 encoded, and will never be %NULL.
1440
 *
1441
1442
1443
1444
1445
1446
1447
1448
1449
 * If @length is non-%NULL then the length of the string (in bytes) is
 * returned there.  For trusted values, this information is already
 * known.  For untrusted values, a strlen() will be performed.
 *
 * It is an error to call this function with a @value of any type
 * other than those three.
 *
 * The return value remains valid as long as @value exists.
 *
1450
 * Returns: (transfer none): the constant string, UTF-8 encoded
1451
 *
1452
1453
1454
1455
1456
1457
 * Since: 2.24
 **/
const gchar *
g_variant_get_string (GVariant *value,
                      gsize    *length)
{
1458
1459
1460
  gconstpointer data;
  gsize size;

1461
1462
1463
1464
1465
  g_return_val_if_fail (value != NULL, NULL);
  g_return_val_if_fail (
    g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
    g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
    g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1466
1467
1468

  data = g_variant_get_data (value);
  size = g_variant_get_size (value);
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511

  if (!g_variant_is_trusted (value))
    {
      switch (g_variant_classify (value))
        {
        case G_VARIANT_CLASS_STRING:
          if (g_variant_serialiser_is_string (data, size))
            break;

          data = "";
          size = 1;
          break;

        case G_VARIANT_CLASS_OBJECT_PATH:
          if (g_variant_serialiser_is_object_path (data, size))
            break;

          data = "/";
          size = 2;
          break;

        case G_VARIANT_CLASS_SIGNATURE:
          if (g_variant_serialiser_is_signature (data, size))
            break;

          data = "";
          size = 1;
          break;

        default:
          g_assert_not_reached ();
        }
    }

  if (length)
    *length = size - 1;

  return data;
}

/**
 * g_variant_dup_string:
 * @value: a string #GVariant instance
1512
 * @length: (out): a pointer to a #gsize, to store the length
1513
1514
1515
1516
 *
 * Similar to g_variant_get_string() except that instead of returning
 * a constant string, the string is duplicated.
 *
1517
 * The string will always be UTF-8 encoded.
1518
 *
1519
1520
 * The return value must be freed using g_free().
 *
1521
 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1522
 *
1523
1524
1525
1526
1527
1528
1529
1530
1531
 * Since: 2.24
 **/
gchar *
g_variant_dup_string (GVariant *value,
                      gsize    *length)
{
  return g_strdup (g_variant_get_string (value, length));
}

1532
/**
1533
 * g_variant_new_strv:
1534
 * @strv: (array length=length) (element-type utf8): an array of strings
1535
 * @length: the length of @strv, or -1
1536
 *
1537
1538
 * Constructs an array of strings #GVariant from the given array of
 * strings.
1539
 *
1540
 * If @length is -1 then @strv is %NULL-terminated.
1541
 *
1542
1543
 * Returns: (transfer none): a new floating #GVariant instance
 *
1544
 * Since: 2.24
1545
1546
 **/
GVariant *
1547
1548
g_variant_new_strv (const gchar * const *strv,
                    gssize               length)
1549
{
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
  GVariant **strings;
  gsize i;

  g_return_val_if_fail (length == 0 || strv != NULL, NULL);

  if (length < 0)
    length = g_strv_length ((gchar **) strv);

  strings = g_new (GVariant *, length);
  for (i = 0; i < length; i++)
    strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));

  return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
                                      strings, length, TRUE);
}

/**
 * g_variant_get_strv:
 * @value: an array of strings #GVariant
1569
 * @length: (out) (optional): the length of the result, or %NULL
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
 *
 * Gets the contents of an array of strings #GVariant.  This call
 * makes a shallow copy; the return result should be released with
 * g_free(), but the individual strings must not be modified.
 *
 * If @length is non-%NULL then the number of elements in the result
 * is stored there.  In any case, the resulting array will be
 * %NULL-terminated.
 *
 * For an empty array, @length will be set to 0 and a pointer to a
 * %NULL pointer will be returned.
 *
1582
1583
 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
 *
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
 * Since: 2.24
 **/
const gchar **
g_variant_get_strv (GVariant *value,
                    gsize    *length)
{
  const gchar **strv;
  gsize n;
  gsize i;

  TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);

  g_variant_get_data (value);
  n = g_variant_n_children (value);
  strv = g_new (const gchar *, n + 1);

  for (i = 0; i < n; i++)
1601
    {
1602
      GVariant *string;
1603

1604
1605
1606
      string = g_variant_get_child_value (value, i);
      strv[i] = g_variant_get_string (string, NULL);
      g_variant_unref (string);
1607
    }
1608
  strv[i] = NULL;
1609

1610
1611
1612
1613
  if (length)
    *length = n;

  return strv;
1614
1615
1616
}

/**
1617
1618
 * g_variant_dup_strv:
 * @value: an array of strings #GVariant
1619
 * @length: (out) (optional): the length of the result, or %NULL
1620
1621
1622
1623
1624