Coverage Report

Created: 2025-07-12 07:07

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