Coverage Report

Created: 2025-11-16 07:45

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