Add gdbus-proxy-well-known-name to the ignore file
[glib.git] / glib / gvariant.c
blob3b5fd8c92577eeb7cb53677648bb671c9f46b806
1 /*
2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the licence, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: Ryan Lortie <desrt@desrt.ca>
23 /* Prologue {{{1 */
25 #include "config.h"
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/ghash.h>
33 #include <glib/gmem.h>
35 #include <string.h>
37 #include "galias.h"
39 /**
40 * SECTION: gvariant
41 * @title: GVariant
42 * @short_description: strongly typed value datatype
43 * @see_also: GVariantType
45 * #GVariant is a variant datatype; it stores a value along with
46 * information about the type of that value. The range of possible
47 * values is determined by the type. The type system used by #GVariant
48 * is #GVariantType.
50 * #GVariant instances always have a type and a value (which are given
51 * at construction time). The type and value of a #GVariant instance
52 * can never change other than by the #GVariant itself being
53 * destroyed. A #GVariant can not contain a pointer.
55 * #GVariant is reference counted using g_variant_ref() and
56 * g_variant_unref(). #GVariant also has floating reference counts --
57 * see g_variant_ref_sink().
59 * #GVariant is completely threadsafe. A #GVariant instance can be
60 * concurrently accessed in any way from any number of threads without
61 * problems.
63 * #GVariant is heavily optimised for dealing with data in serialised
64 * form. It works particularly well with data located in memory-mapped
65 * files. It can perform nearly all deserialisation operations in a
66 * small constant time, usually touching only a single memory page.
67 * Serialised #GVariant data can also be sent over the network.
69 * #GVariant is largely compatible with DBus. Almost all types of
70 * #GVariant instances can be sent over DBus. See #GVariantType for
71 * exceptions.
73 * For convenience to C programmers, #GVariant features powerful
74 * varargs-based value construction and destruction. This feature is
75 * designed to be embedded in other libraries.
77 * There is a Python-inspired text language for describing #GVariant
78 * values. #GVariant includes a printer for this language and a parser
79 * with type inferencing.
81 * <refsect2>
82 * <title>Memory Use</title>
83 * <para>
84 * #GVariant tries to be quite efficient with respect to memory use.
85 * This section gives a rough idea of how much memory is used by the
86 * current implementation. The information here is subject to change
87 * in the future.
88 * </para>
89 * <para>
90 * The memory allocated by #GVariant can be grouped into 4 broad
91 * purposes: memory for serialised data, memory for the type
92 * information cache, buffer management memory and memory for the
93 * #GVariant structure itself.
94 * </para>
95 * <refsect3>
96 * <title>Serialised Data Memory</title>
97 * <para>
98 * This is the memory that is used for storing GVariant data in
99 * serialised form. This is what would be sent over the network or
100 * what would end up on disk.
101 * </para>
102 * <para>
103 * The amount of memory required to store a boolean is 1 byte. 16,
104 * 32 and 64 bit integers and double precision floating point numbers
105 * use their "natural" size. Strings (including object path and
106 * signature strings) are stored with a nul terminator, and as such
107 * use the length of the string plus 1 byte.
108 * </para>
109 * <para>
110 * Maybe types use no space at all to represent the null value and
111 * use the same amount of space (sometimes plus one byte) as the
112 * equivalent non-maybe-typed value to represent the non-null case.
113 * </para>
114 * <para>
115 * Arrays use the amount of space required to store each of their
116 * members, concatenated. Additionally, if the items stored in an
117 * array are not of a fixed-size (ie: strings, other arrays, etc)
118 * then an additional framing offset is stored for each item. The
119 * size of this offset is either 1, 2 or 4 bytes depending on the
120 * overall size of the container. Additionally, extra padding bytes
121 * are added as required for alignment of child values.
122 * </para>
123 * <para>
124 * Tuples (including dictionary entries) use the amount of space
125 * required to store each of their members, concatenated, plus one
126 * framing offset (as per arrays) for each non-fixed-sized item in
127 * the tuple, except for the last one. Additionally, extra padding
128 * bytes are added as required for alignment of child values.
129 * </para>
130 * <para>
131 * Variants use the same amount of space as the item inside of the
132 * variant, plus 1 byte, plus the length of the type string for the
133 * item inside the variant.
134 * </para>
135 * <para>
136 * As an example, consider a dictionary mapping strings to variants.
137 * In the case that the dictionary is empty, 0 bytes are required for
138 * the serialisation.
139 * </para>
140 * <para>
141 * If we add an item "width" that maps to the int32 value of 500 then
142 * we will use 4 byte to store the int32 (so 6 for the variant
143 * containing it) and 6 bytes for the string. The variant must be
144 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
145 * bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
146 * for the dictionary entry. An additional 1 byte is added to the
147 * array as a framing offset making a total of 15 bytes.
148 * </para>
149 * <para>
150 * If we add another entry, "title" that maps to a nullable string
151 * that happens to have a value of null, then we use 0 bytes for the
152 * null value (and 3 bytes for the variant to contain it along with
153 * its type string) plus 6 bytes for the string. Again, we need 2
154 * padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
155 * </para>
156 * <para>
157 * We now require extra padding between the two items in the array.
158 * After the 14 bytes of the first item, that's 2 bytes required. We
159 * now require 2 framing offsets for an extra two bytes. 14 + 2 + 11
160 * + 2 = 29 bytes to encode the entire two-item dictionary.
161 * </para>
162 * </refsect3>
163 * <refsect3>
164 * <title>Type Information Cache</title>
165 * <para>
166 * For each GVariant type that currently exists in the program a type
167 * information structure is kept in the type information cache. The
168 * type information structure is required for rapid deserialisation.
169 * </para>
170 * <para>
171 * Continuing with the above example, if a #GVariant exists with the
172 * type "a{sv}" then a type information struct will exist for
173 * "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
174 * will share the same type information. Additionally, all
175 * single-digit types are stored in read-only static memory and do
176 * not contribute to the writable memory footprint of a program using
177 * #GVariant.
178 * </para>
179 * <para>
180 * Aside from the type information structures stored in read-only
181 * memory, there are two forms of type information. One is used for
182 * container types where there is a single element type: arrays and
183 * maybe types. The other is used for container types where there
184 * are multiple element types: tuples and dictionary entries.
185 * </para>
186 * <para>
187 * Array type info structures are 6 * sizeof (void *), plus the
188 * memory required to store the type string itself. This means that
189 * on 32bit systems, the cache entry for "a{sv}" would require 30
190 * bytes of memory (plus malloc overhead).
191 * </para>
192 * <para>
193 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
194 * sizeof (void *) for each item in the tuple, plus the memory
195 * required to store the type string itself. A 2-item tuple, for
196 * example, would have a type information structure that consumed
197 * writable memory in the size of 14 * sizeof (void *) (plus type
198 * string) This means that on 32bit systems, the cache entry for
199 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
200 * </para>
201 * <para>
202 * This means that in total, for our "a{sv}" example, 91 bytes of
203 * type information would be allocated.
204 * </para>
205 * <para>
206 * The type information cache, additionally, uses a #GHashTable to
207 * store and lookup the cached items and stores a pointer to this
208 * hash table in static storage. The hash table is freed when there
209 * are zero items in the type cache.
210 * </para>
211 * <para>
212 * Although these sizes may seem large it is important to remember
213 * that a program will probably only have a very small number of
214 * different types of values in it and that only one type information
215 * structure is required for many different values of the same type.
216 * </para>
217 * </refsect3>
218 * <refsect3>
219 * <title>Buffer Management Memory</title>
220 * <para>
221 * #GVariant uses an internal buffer management structure to deal
222 * with the various different possible sources of serialised data
223 * that it uses. The buffer is responsible for ensuring that the
224 * correct call is made when the data is no longer in use by
225 * #GVariant. This may involve a g_free() or a g_slice_free() or
226 * even g_mapped_file_unref().
227 * </para>
228 * <para>
229 * One buffer management structure is used for each chunk of
230 * serialised data. The size of the buffer management structure is 4
231 * * (void *). On 32bit systems, that's 16 bytes.
232 * </para>
233 * </refsect3>
234 * <refsect3>
235 * <title>GVariant structure</title>
236 * <para>
237 * The size of a #GVariant structure is 6 * (void *). On 32 bit
238 * systems, that's 24 bytes.
239 * </para>
240 * <para>
241 * #GVariant structures only exist if they are explicitly created
242 * with API calls. For example, if a #GVariant is constructed out of
243 * serialised data for the example given above (with the dictionary)
244 * then although there are 9 individual values that comprise the
245 * entire dictionary (two keys, two values, two variants containing
246 * the values, two dictionary entries, plus the dictionary itself),
247 * only 1 #GVariant instance exists -- the one refering to the
248 * dictionary.
249 * </para>
250 * <para>
251 * If calls are made to start accessing the other values then
252 * #GVariant instances will exist for those values only for as long
253 * as they are in use (ie: until you call g_variant_unref()). The
254 * type information is shared. The serialised data and the buffer
255 * management structure for that serialised data is shared by the
256 * child.
257 * </para>
258 * </refsect3>
259 * <refsect3>
260 * <title>Summary</title>
261 * <para>
262 * To put the entire example together, for our dictionary mapping
263 * strings to variants (with two entries, as given above), we are
264 * using 91 bytes of memory for type information, 29 byes of memory
265 * for the serialised data, 16 bytes for buffer management and 24
266 * bytes for the #GVariant instance, or a total of 160 bytes, plus
267 * malloc overhead. If we were to use g_variant_get_child_value() to
268 * access the two dictionary entries, we would use an additional 48
269 * bytes. If we were to have other dictionaries of the same type, we
270 * would use more memory for the serialised data and buffer
271 * management for those dictionaries, but the type information would
272 * be shared.
273 * </para>
274 * </refsect3>
275 * </refsect2>
278 /* definition of GVariant structure is in gvariant-core.c */
280 /* this is a g_return_val_if_fail() for making
281 * sure a (GVariant *) has the required type.
283 #define TYPE_CHECK(value, TYPE, val) \
284 if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) { \
285 g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, \
286 "g_variant_is_of_type (" #value \
287 ", " #TYPE ")"); \
288 return val; \
291 /* Numeric Type Constructor/Getters {{{1 */
292 /* < private >
293 * g_variant_new_from_trusted:
294 * @type: the #GVariantType
295 * @data: the data to use
296 * @size: the size of @data
297 * @returns: a new floating #GVariant
299 * Constructs a new trusted #GVariant instance from the provided data.
300 * This is used to implement g_variant_new_* for all the basic types.
302 static GVariant *
303 g_variant_new_from_trusted (const GVariantType *type,
304 gconstpointer data,
305 gsize size)
307 GVariant *value;
308 GBuffer *buffer;
310 buffer = g_buffer_new_from_data (data, size);
311 value = g_variant_new_from_buffer (type, buffer, TRUE);
312 g_buffer_unref (buffer);
314 return value;
318 * g_variant_new_boolean:
319 * @boolean: a #gboolean value
320 * @returns: a new boolean #GVariant instance
322 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
324 * Since: 2.24
326 GVariant *
327 g_variant_new_boolean (gboolean value)
329 guchar v = value;
331 return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
335 * g_variant_get_boolean:
336 * @value: a boolean #GVariant instance
337 * @returns: %TRUE or %FALSE
339 * Returns the boolean value of @value.
341 * It is an error to call this function with a @value of any type
342 * other than %G_VARIANT_TYPE_BOOLEAN.
344 * Since: 2.24
346 gboolean
347 g_variant_get_boolean (GVariant *value)
349 const guchar *data;
351 TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
353 data = g_variant_get_data (value);
355 return data != NULL ? *data != 0 : FALSE;
358 /* the constructors and accessors for byte, int{16,32,64}, handles and
359 * doubles all look pretty much exactly the same, so we reduce
360 * copy/pasting here.
362 #define NUMERIC_TYPE(TYPE, type, ctype) \
363 GVariant *g_variant_new_##type (ctype value) { \
364 return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE, \
365 &value, sizeof value); \
367 ctype g_variant_get_##type (GVariant *value) { \
368 const ctype *data; \
369 TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0); \
370 data = g_variant_get_data (value); \
371 return data != NULL ? *data : 0; \
376 * g_variant_new_byte:
377 * @byte: a #guint8 value
378 * @returns: a new byte #GVariant instance
380 * Creates a new byte #GVariant instance.
382 * Since: 2.24
385 * g_variant_get_byte:
386 * @value: a byte #GVariant instance
387 * @returns: a #guchar
389 * Returns the byte value of @value.
391 * It is an error to call this function with a @value of any type
392 * other than %G_VARIANT_TYPE_BYTE.
394 * Since: 2.24
396 NUMERIC_TYPE (BYTE, byte, guchar)
399 * g_variant_new_int16:
400 * @int16: a #gint16 value
401 * @returns: a new int16 #GVariant instance
403 * Creates a new int16 #GVariant instance.
405 * Since: 2.24
408 * g_variant_get_int16:
409 * @value: a int16 #GVariant instance
410 * @returns: a #gint16
412 * Returns the 16-bit signed integer value of @value.
414 * It is an error to call this function with a @value of any type
415 * other than %G_VARIANT_TYPE_INT16.
417 * Since: 2.24
419 NUMERIC_TYPE (INT16, int16, gint16)
422 * g_variant_new_uint16:
423 * @uint16: a #guint16 value
424 * @returns: a new uint16 #GVariant instance
426 * Creates a new uint16 #GVariant instance.
428 * Since: 2.24
431 * g_variant_get_uint16:
432 * @value: a uint16 #GVariant instance
433 * @returns: a #guint16
435 * Returns the 16-bit unsigned integer value of @value.
437 * It is an error to call this function with a @value of any type
438 * other than %G_VARIANT_TYPE_UINT16.
440 * Since: 2.24
442 NUMERIC_TYPE (UINT16, uint16, guint16)
445 * g_variant_new_int32:
446 * @int32: a #gint32 value
447 * @returns: a new int32 #GVariant instance
449 * Creates a new int32 #GVariant instance.
451 * Since: 2.24
454 * g_variant_get_int32:
455 * @value: a int32 #GVariant instance
456 * @returns: a #gint32
458 * Returns the 32-bit signed integer value of @value.
460 * It is an error to call this function with a @value of any type
461 * other than %G_VARIANT_TYPE_INT32.
463 * Since: 2.24
465 NUMERIC_TYPE (INT32, int32, gint32)
468 * g_variant_new_uint32:
469 * @uint32: a #guint32 value
470 * @returns: a new uint32 #GVariant instance
472 * Creates a new uint32 #GVariant instance.
474 * Since: 2.24
477 * g_variant_get_uint32:
478 * @value: a uint32 #GVariant instance
479 * @returns: a #guint32
481 * Returns the 32-bit unsigned integer value of @value.
483 * It is an error to call this function with a @value of any type
484 * other than %G_VARIANT_TYPE_UINT32.
486 * Since: 2.24
488 NUMERIC_TYPE (UINT32, uint32, guint32)
491 * g_variant_new_int64:
492 * @int64: a #gint64 value
493 * @returns: a new int64 #GVariant instance
495 * Creates a new int64 #GVariant instance.
497 * Since: 2.24
500 * g_variant_get_int64:
501 * @value: a int64 #GVariant instance
502 * @returns: a #gint64
504 * Returns the 64-bit signed integer value of @value.
506 * It is an error to call this function with a @value of any type
507 * other than %G_VARIANT_TYPE_INT64.
509 * Since: 2.24
511 NUMERIC_TYPE (INT64, int64, gint64)
514 * g_variant_new_uint64:
515 * @uint64: a #guint64 value
516 * @returns: a new uint64 #GVariant instance
518 * Creates a new uint64 #GVariant instance.
520 * Since: 2.24
523 * g_variant_get_uint64:
524 * @value: a uint64 #GVariant instance
525 * @returns: a #guint64
527 * Returns the 64-bit unsigned integer value of @value.
529 * It is an error to call this function with a @value of any type
530 * other than %G_VARIANT_TYPE_UINT64.
532 * Since: 2.24
534 NUMERIC_TYPE (UINT64, uint64, guint64)
537 * g_variant_new_handle:
538 * @handle: a #gint32 value
539 * @returns: a new handle #GVariant instance
541 * Creates a new handle #GVariant instance.
543 * By convention, handles are indexes into an array of file descriptors
544 * that are sent alongside a DBus message. If you're not interacting
545 * with DBus, you probably don't need them.
547 * Since: 2.24
550 * g_variant_get_handle:
551 * @value: a handle #GVariant instance
552 * @returns: a #gint32
554 * Returns the 32-bit signed integer value of @value.
556 * It is an error to call this function with a @value of any type other
557 * than %G_VARIANT_TYPE_HANDLE.
559 * By convention, handles are indexes into an array of file descriptors
560 * that are sent alongside a DBus message. If you're not interacting
561 * with DBus, you probably don't need them.
563 * Since: 2.24
565 NUMERIC_TYPE (HANDLE, handle, gint32)
568 * g_variant_new_double:
569 * @floating: a #gdouble floating point value
570 * @returns: a new double #GVariant instance
572 * Creates a new double #GVariant instance.
574 * Since: 2.24
577 * g_variant_get_double:
578 * @value: a double #GVariant instance
579 * @returns: a #gdouble
581 * Returns the double precision floating point value of @value.
583 * It is an error to call this function with a @value of any type
584 * other than %G_VARIANT_TYPE_DOUBLE.
586 * Since: 2.24
588 NUMERIC_TYPE (DOUBLE, double, gdouble)
590 /* Container type Constructor / Deconstructors {{{1 */
592 * g_variant_new_maybe:
593 * @child_type: the #GVariantType of the child
594 * @child: the child value, or %NULL
595 * @returns: a new #GVariant maybe instance
597 * Depending on if @value is %NULL, either wraps @value inside of a
598 * maybe container or creates a Nothing instance for the given @type.
600 * At least one of @type and @value must be non-%NULL. If @type is
601 * non-%NULL then it must be a definite type. If they are both
602 * non-%NULL then @type must be the type of @value.
604 * Since: 2.24
606 GVariant *
607 g_variant_new_maybe (const GVariantType *child_type,
608 GVariant *child)
610 GVariantType *maybe_type;
611 GVariant *value;
613 g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
614 (child_type), 0);
615 g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
616 g_return_val_if_fail (child_type == NULL || child == NULL ||
617 g_variant_is_of_type (child, child_type),
618 NULL);
620 if (child_type == NULL)
621 child_type = g_variant_get_type (child);
623 maybe_type = g_variant_type_new_maybe (child_type);
625 if (child != NULL)
627 GVariant **children;
628 gboolean trusted;
630 children = g_new (GVariant *, 1);
631 children[0] = g_variant_ref_sink (child);
632 trusted = g_variant_is_trusted (children[0]);
634 value = g_variant_new_from_children (maybe_type, children, 1, trusted);
636 else
637 value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
639 g_variant_type_free (maybe_type);
641 return value;
645 * g_variant_get_maybe:
646 * @value: a maybe-typed value
647 * @returns: the contents of @value, or %NULL
649 * Given a maybe-typed #GVariant instance, extract its value. If the
650 * value is Nothing, then this function returns %NULL.
652 * Since: 2.24
654 GVariant *
655 g_variant_get_maybe (GVariant *value)
657 TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
659 if (g_variant_n_children (value))
660 return g_variant_get_child_value (value, 0);
662 return NULL;
666 * g_variant_new_variant:
667 * @value: a #GVariance instance
668 * @returns: a new variant #GVariant instance
670 * Boxes @value. The result is a #GVariant instance representing a
671 * variant containing the original value.
673 * Since: 2.24
675 GVariant *
676 g_variant_new_variant (GVariant *value)
678 g_return_val_if_fail (value != NULL, NULL);
680 g_variant_ref_sink (value);
682 return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
683 g_memdup (&value, sizeof value),
684 1, g_variant_is_trusted (value));
688 * g_variant_get_variant:
689 * @value: a variant #GVariance instance
690 * @returns: the item contained in the variant
692 * Unboxes @value. The result is the #GVariant instance that was
693 * contained in @value.
695 * Since: 2.24
697 GVariant *
698 g_variant_get_variant (GVariant *value)
700 TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
702 return g_variant_get_child_value (value, 0);
706 * g_variant_new_array:
707 * @child_type: the element type of the new array
708 * @children: an array of #GVariant pointers, the children
709 * @n_children: the length of @children
710 * @returns: a new #GVariant array
712 * Creates a new #GVariant array from @children.
714 * @child_type must be non-%NULL if @n_children is zero. Otherwise, the
715 * child type is determined by inspecting the first element of the
716 * @children array. If @child_type is non-%NULL then it must be a
717 * definite type.
719 * The items of the array are taken from the @children array. No entry
720 * in the @children array may be %NULL.
722 * All items in the array must have the same type, which must be the
723 * same as @child_type, if given.
725 * Since: 2.24
727 GVariant *
728 g_variant_new_array (const GVariantType *child_type,
729 GVariant * const *children,
730 gsize n_children)
732 GVariantType *array_type;
733 GVariant **my_children;
734 gboolean trusted;
735 GVariant *value;
736 gsize i;
738 g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
739 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
740 g_return_val_if_fail (child_type == NULL ||
741 g_variant_type_is_definite (child_type), NULL);
743 my_children = g_new (GVariant *, n_children);
744 trusted = TRUE;
746 if (child_type == NULL)
747 child_type = g_variant_get_type (children[0]);
748 array_type = g_variant_type_new_array (child_type);
750 for (i = 0; i < n_children; i++)
752 TYPE_CHECK (children[i], child_type, NULL);
753 my_children[i] = g_variant_ref_sink (children[i]);
754 trusted &= g_variant_is_trusted (children[i]);
757 value = g_variant_new_from_children (array_type, my_children,
758 n_children, trusted);
759 g_variant_type_free (array_type);
761 return value;
764 /*< private >
765 * g_variant_make_tuple_type:
766 * @children: an array of GVariant *
767 * @n_children: the length of @children
769 * Return the type of a tuple containing @children as its items.
771 static GVariantType *
772 g_variant_make_tuple_type (GVariant * const *children,
773 gsize n_children)
775 const GVariantType **types;
776 GVariantType *type;
777 gsize i;
779 types = g_new (const GVariantType *, n_children);
781 for (i = 0; i < n_children; i++)
782 types[i] = g_variant_get_type (children[i]);
784 type = g_variant_type_new_tuple (types, n_children);
785 g_free (types);
787 return type;
791 * g_variant_new_tuple:
792 * @children: the items to make the tuple out of
793 * @n_children: the length of @children
794 * @returns: a new #GVariant tuple
796 * Creates a new tuple #GVariant out of the items in @children. The
797 * type is determined from the types of @children. No entry in the
798 * @children array may be %NULL.
800 * If @n_children is 0 then the unit tuple is constructed.
802 * Since: 2.24
804 GVariant *
805 g_variant_new_tuple (GVariant * const *children,
806 gsize n_children)
808 GVariantType *tuple_type;
809 GVariant **my_children;
810 gboolean trusted;
811 GVariant *value;
812 gsize i;
814 g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
816 my_children = g_new (GVariant *, n_children);
817 trusted = TRUE;
819 for (i = 0; i < n_children; i++)
821 my_children[i] = g_variant_ref_sink (children[i]);
822 trusted &= g_variant_is_trusted (children[i]);
825 tuple_type = g_variant_make_tuple_type (children, n_children);
826 value = g_variant_new_from_children (tuple_type, my_children,
827 n_children, trusted);
828 g_variant_type_free (tuple_type);
830 return value;
833 /*< private >
834 * g_variant_make_dict_entry_type:
835 * @key: a #GVariant, the key
836 * @val: a #GVariant, the value
838 * Return the type of a dictionary entry containing @key and @val as its
839 * children.
841 static GVariantType *
842 g_variant_make_dict_entry_type (GVariant *key,
843 GVariant *val)
845 return g_variant_type_new_dict_entry (g_variant_get_type (key),
846 g_variant_get_type (val));
850 * g_variant_new_dict_entry:
851 * @key: a basic #GVariant, the key
852 * @value: a #GVariant, the value
853 * @returns: a new dictionary entry #GVariant
855 * Creates a new dictionary entry #GVariant. @key and @value must be
856 * non-%NULL.
858 * @key must be a value of a basic type (ie: not a container).
860 * Since: 2.24
862 GVariant *
863 g_variant_new_dict_entry (GVariant *key,
864 GVariant *value)
866 GVariantType *dict_type;
867 GVariant **children;
868 gboolean trusted;
870 g_return_val_if_fail (key != NULL && value != NULL, NULL);
871 g_return_val_if_fail (!g_variant_is_container (key), NULL);
873 children = g_new (GVariant *, 2);
874 children[0] = g_variant_ref_sink (key);
875 children[1] = g_variant_ref_sink (value);
876 trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
878 dict_type = g_variant_make_dict_entry_type (key, value);
879 value = g_variant_new_from_children (dict_type, children, 2, trusted);
880 g_variant_type_free (dict_type);
882 return value;
886 * g_variant_get_fixed_array:
887 * @value: a #GVariant array with fixed-sized elements
888 * @n_elements: a pointer to the location to store the number of items
889 * @element_size: the size of each element
890 * @returns: a pointer to the fixed array
892 * Provides access to the serialised data for an array of fixed-sized
893 * items.
895 * @value must be an array with fixed-sized elements. Numeric types are
896 * fixed-size as are tuples containing only other fixed-sized types.
898 * @element_size must be the size of a single element in the array. For
899 * example, if calling this function for an array of 32 bit integers,
900 * you might say <code>sizeof (gint32)</code>. This value isn't used
901 * except for the purpose of a double-check that the form of the
902 * seralised data matches the caller's expectation.
904 * @n_elements, which must be non-%NULL is set equal to the number of
905 * items in the array.
907 * Since: 2.24
909 gconstpointer
910 g_variant_get_fixed_array (GVariant *value,
911 gsize *n_elements,
912 gsize element_size)
914 GVariantTypeInfo *array_info;
915 gsize array_element_size;
916 gconstpointer data;
917 gsize size;
919 TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
921 g_return_val_if_fail (n_elements != NULL, NULL);
922 g_return_val_if_fail (element_size > 0, NULL);
924 array_info = g_variant_get_type_info (value);
925 g_variant_type_info_query_element (array_info, NULL, &array_element_size);
927 g_return_val_if_fail (array_element_size, NULL);
929 if G_UNLIKELY (array_element_size != element_size)
931 if (array_element_size)
932 g_critical ("g_variant_get_fixed_array: assertion "
933 "`g_variant_array_has_fixed_size (value, element_size)' "
934 "failed: array size %"G_GSIZE_FORMAT" does not match "
935 "given element_size %"G_GSIZE_FORMAT".",
936 array_element_size, element_size);
937 else
938 g_critical ("g_variant_get_fixed_array: assertion "
939 "`g_variant_array_has_fixed_size (value, element_size)' "
940 "failed: array does not have fixed size.");
943 data = g_variant_get_data (value);
944 size = g_variant_get_size (value);
946 if (size % element_size)
947 *n_elements = 0;
948 else
949 *n_elements = size / element_size;
951 if (*n_elements)
952 return data;
954 return NULL;
957 /* String type constructor/getters/validation {{{1 */
959 * g_variant_new_string:
960 * @string: a normal utf8 nul-terminated string
961 * @returns: a new string #GVariant instance
963 * Creates a string #GVariant with the contents of @string.
965 * @string must be valid utf8.
967 * Since: 2.24
969 GVariant *
970 g_variant_new_string (const gchar *string)
972 g_return_val_if_fail (string != NULL, NULL);
974 return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
975 string, strlen (string) + 1);
979 * g_variant_new_object_path:
980 * @object_path: a normal C nul-terminated string
981 * @returns: a new object path #GVariant instance
983 * Creates a DBus object path #GVariant with the contents of @string.
984 * @string must be a valid DBus object path. Use
985 * g_variant_is_object_path() if you're not sure.
987 * Since: 2.24
989 GVariant *
990 g_variant_new_object_path (const gchar *object_path)
992 g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
994 return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
995 object_path, strlen (object_path) + 1);
999 * g_variant_is_object_path:
1000 * @string: a normal C nul-terminated string
1001 * @returns: %TRUE if @string is a DBus object path
1003 * Determines if a given string is a valid DBus object path. You
1004 * should ensure that a string is a valid DBus object path before
1005 * passing it to g_variant_new_object_path().
1007 * A valid object path starts with '/' followed by zero or more
1008 * sequences of characters separated by '/' characters. Each sequence
1009 * must contain only the characters "[A-Z][a-z][0-9]_". No sequence
1010 * (including the one following the final '/' character) may be empty.
1012 * Since: 2.24
1014 gboolean
1015 g_variant_is_object_path (const gchar *string)
1017 g_return_val_if_fail (string != NULL, FALSE);
1019 return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1023 * g_variant_new_signature:
1024 * @signature: a normal C nul-terminated string
1025 * @returns: a new signature #GVariant instance
1027 * Creates a DBus type signature #GVariant with the contents of
1028 * @string. @string must be a valid DBus type signature. Use
1029 * g_variant_is_signature() if you're not sure.
1031 * Since: 2.24
1033 GVariant *
1034 g_variant_new_signature (const gchar *signature)
1036 g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1038 return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1039 signature, strlen (signature) + 1);
1043 * g_variant_is_signature:
1044 * @string: a normal C nul-terminated string
1045 * @returns: %TRUE if @string is a DBus type signature
1047 * Determines if a given string is a valid DBus type signature. You
1048 * should ensure that a string is a valid DBus object path before
1049 * passing it to g_variant_new_signature().
1051 * DBus type signatures consist of zero or more definite #GVariantType
1052 * strings in sequence.
1054 * Since: 2.24
1056 gboolean
1057 g_variant_is_signature (const gchar *string)
1059 g_return_val_if_fail (string != NULL, FALSE);
1061 return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1065 * g_variant_get_string:
1066 * @value: a string #GVariant instance
1067 * @length: a pointer to a #gsize, to store the length
1068 * @returns: the constant string, utf8 encoded
1070 * Returns the string value of a #GVariant instance with a string
1071 * type. This includes the types %G_VARIANT_TYPE_STRING,
1072 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1074 * The string will always be utf8 encoded.
1076 * If @length is non-%NULL then the length of the string (in bytes) is
1077 * returned there. For trusted values, this information is already
1078 * known. For untrusted values, a strlen() will be performed.
1080 * It is an error to call this function with a @value of any type
1081 * other than those three.
1083 * The return value remains valid as long as @value exists.
1085 * Since: 2.24
1087 const gchar *
1088 g_variant_get_string (GVariant *value,
1089 gsize *length)
1091 gconstpointer data;
1092 gsize size;
1094 g_return_val_if_fail (value != NULL, NULL);
1095 g_return_val_if_fail (
1096 g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1097 g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1098 g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1100 data = g_variant_get_data (value);
1101 size = g_variant_get_size (value);
1103 if (!g_variant_is_trusted (value))
1105 switch (g_variant_classify (value))
1107 case G_VARIANT_CLASS_STRING:
1108 if (g_variant_serialiser_is_string (data, size))
1109 break;
1111 data = "";
1112 size = 1;
1113 break;
1115 case G_VARIANT_CLASS_OBJECT_PATH:
1116 if (g_variant_serialiser_is_object_path (data, size))
1117 break;
1119 data = "/";
1120 size = 2;
1121 break;
1123 case G_VARIANT_CLASS_SIGNATURE:
1124 if (g_variant_serialiser_is_signature (data, size))
1125 break;
1127 data = "";
1128 size = 1;
1129 break;
1131 default:
1132 g_assert_not_reached ();
1136 if (length)
1137 *length = size - 1;
1139 return data;
1143 * g_variant_dup_string:
1144 * @value: a string #GVariant instance
1145 * @length: a pointer to a #gsize, to store the length
1146 * @returns: a newly allocated string, utf8 encoded
1148 * Similar to g_variant_get_string() except that instead of returning
1149 * a constant string, the string is duplicated.
1151 * The string will always be utf8 encoded.
1153 * The return value must be freed using g_free().
1155 * Since: 2.24
1157 gchar *
1158 g_variant_dup_string (GVariant *value,
1159 gsize *length)
1161 return g_strdup (g_variant_get_string (value, length));
1165 * g_variant_new_byte_array:
1166 * @array: a pointer to an array of bytes
1167 * @length: the length of @array, or -1
1168 * @returns: a new floating #GVariant instance
1170 * Constructs an array of bytes #GVariant from the given array of bytes.
1172 * If @length is -1 then @array is taken to be a normal C string (in the
1173 * sense that it is terminated by a nul character). The nul character
1174 * is included in the array. If length is not -1 then it gives the
1175 * length of @array which may then contain nul chracters with no special
1176 * meaning.
1178 * Since: 2.26
1180 GVariant *
1181 g_variant_new_byte_array (gconstpointer array,
1182 gssize length)
1184 if (length == -1)
1186 const gchar *bytes = array;
1188 length = 0;
1189 while (bytes[length++]);
1192 return g_variant_new_from_trusted (G_VARIANT_TYPE ("ay"),
1193 array, length);
1197 * g_variant_get_byte_array:
1198 * @value: an array of bytes #GVariant
1199 * @length: the length of the result, or %NULL
1200 * @returns: a pointer to the byte data, or %NULL
1202 * Gets the contents of an array of bytes #GVariant.
1204 * If @length is non-%NULL then it points to a location at which to
1205 * store the length of the array and nul bytes contained within the
1206 * array have no special meaning.
1208 * If @length is %NULL then the caller has no way to determine what the
1209 * length of the returned data might be. In this case, the function
1210 * ensures that the last byte of the array is a nul byte and, if it is
1211 * not, returns %NULL instead. In this way, the caller is assured that
1212 * any non-%NULL pointer that is returned will be nul-terminated.
1214 * The return value remains valid as long as @value exists.
1216 * Since: 2.26
1218 gconstpointer
1219 g_variant_get_byte_array (GVariant *value,
1220 gsize *length)
1222 gconstpointer data;
1223 gsize size;
1225 TYPE_CHECK (value, G_VARIANT_TYPE ("ay"), NULL);
1227 data = g_variant_get_data (value);
1228 size = g_variant_get_size (value);
1230 if (length == NULL)
1232 const gchar *bytes = data;
1234 if (bytes[size - 1] != '\0')
1235 return NULL;
1237 else
1238 *length = size;
1240 return data;
1244 * g_variant_new_strv:
1245 * @strv: an array of strings
1246 * @length: the length of @strv, or -1
1247 * @returns: (array length=length): a new floating #GVariant instance
1249 * Constructs an array of strings #GVariant from the given array of
1250 * strings.
1252 * If @length is not -1 then it gives the maximum length of @strv. In
1253 * any case, a %NULL pointer in @strv is taken as a terminator.
1255 * Since: 2.24
1257 GVariant *
1258 g_variant_new_strv (const gchar * const *strv,
1259 gssize length)
1261 GVariant **strings;
1262 gsize i;
1264 g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1266 if (length < 0)
1267 length = g_strv_length ((gchar **) strv);
1269 strings = g_new (GVariant *, length);
1270 for (i = 0; i < length; i++)
1271 strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1273 return g_variant_new_from_children (G_VARIANT_TYPE ("as"),
1274 strings, length, TRUE);
1278 * g_variant_get_strv:
1279 * @value: an array of strings #GVariant
1280 * @length: (allow-none): the length of the result, or %NULL
1281 * @returns: (array length=length): an array of constant strings
1283 * Gets the contents of an array of strings #GVariant. This call
1284 * makes a shallow copy; the return result should be released with
1285 * g_free(), but the individual strings must not be modified.
1287 * If @length is non-%NULL then the number of elements in the result
1288 * is stored there. In any case, the resulting array will be
1289 * %NULL-terminated.
1291 * For an empty array, @length will be set to 0 and a pointer to a
1292 * %NULL pointer will be returned.
1294 * Since: 2.24
1296 const gchar **
1297 g_variant_get_strv (GVariant *value,
1298 gsize *length)
1300 const gchar **strv;
1301 gsize n;
1302 gsize i;
1304 g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1305 g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1306 g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1307 NULL);
1309 g_variant_get_data (value);
1310 n = g_variant_n_children (value);
1311 strv = g_new (const gchar *, n + 1);
1313 for (i = 0; i < n; i++)
1315 GVariant *string;
1317 string = g_variant_get_child_value (value, i);
1318 strv[i] = g_variant_get_string (string, NULL);
1319 g_variant_unref (string);
1321 strv[i] = NULL;
1323 if (length)
1324 *length = n;
1326 return strv;
1330 * g_variant_dup_strv:
1331 * @value: an array of strings #GVariant
1332 * @length: (allow-none): the length of the result, or %NULL
1333 * @returns: (array length=length): an array of constant strings
1335 * Gets the contents of an array of strings #GVariant. This call
1336 * makes a deep copy; the return result should be released with
1337 * g_strfreev().
1339 * If @length is non-%NULL then the number of elements in the result
1340 * is stored there. In any case, the resulting array will be
1341 * %NULL-terminated.
1343 * For an empty array, @length will be set to 0 and a pointer to a
1344 * %NULL pointer will be returned.
1346 * Since: 2.24
1348 gchar **
1349 g_variant_dup_strv (GVariant *value,
1350 gsize *length)
1352 gchar **strv;
1353 gsize n;
1354 gsize i;
1356 g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("as")) ||
1357 g_variant_is_of_type (value, G_VARIANT_TYPE ("ao")) ||
1358 g_variant_is_of_type (value, G_VARIANT_TYPE ("ag")),
1359 NULL);
1361 n = g_variant_n_children (value);
1362 strv = g_new (gchar *, n + 1);
1364 for (i = 0; i < n; i++)
1366 GVariant *string;
1368 string = g_variant_get_child_value (value, i);
1369 strv[i] = g_variant_dup_string (string, NULL);
1370 g_variant_unref (string);
1372 strv[i] = NULL;
1374 if (length)
1375 *length = n;
1377 return strv;
1380 /* Type checking and querying {{{1 */
1382 * g_variant_get_type:
1383 * @value: a #GVariant
1384 * @returns: a #GVariantType
1386 * Determines the type of @value.
1388 * The return value is valid for the lifetime of @value and must not
1389 * be freed.
1391 * Since: 2.24
1393 const GVariantType *
1394 g_variant_get_type (GVariant *value)
1396 GVariantTypeInfo *type_info;
1398 g_return_val_if_fail (value != NULL, NULL);
1400 type_info = g_variant_get_type_info (value);
1402 return (GVariantType *) g_variant_type_info_get_type_string (type_info);
1406 * g_variant_get_type_string:
1407 * @value: a #GVariant
1408 * @returns: the type string for the type of @value
1410 * Returns the type string of @value. Unlike the result of calling
1411 * g_variant_type_peek_string(), this string is nul-terminated. This
1412 * string belongs to #GVariant and must not be freed.
1414 * Since: 2.24
1416 const gchar *
1417 g_variant_get_type_string (GVariant *value)
1419 GVariantTypeInfo *type_info;
1421 g_return_val_if_fail (value != NULL, NULL);
1423 type_info = g_variant_get_type_info (value);
1425 return g_variant_type_info_get_type_string (type_info);
1429 * g_variant_is_of_type:
1430 * @value: a #GVariant instance
1431 * @type: a #GVariantType
1432 * @returns: %TRUE if the type of @value matches @type
1434 * Checks if a value has a type matching the provided type.
1436 * Since: 2.24
1438 gboolean
1439 g_variant_is_of_type (GVariant *value,
1440 const GVariantType *type)
1442 return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
1446 * g_variant_is_container:
1447 * @value: a #GVariant instance
1448 * @returns: %TRUE if @value is a container
1450 * Checks if @value is a container.
1452 gboolean
1453 g_variant_is_container (GVariant *value)
1455 return g_variant_type_is_container (g_variant_get_type (value));
1460 * g_variant_classify:
1461 * @value: a #GVariant
1462 * @returns: the #GVariantClass of @value
1464 * Classifies @value according to its top-level type.
1466 * Since: 2.24
1469 * GVariantClass:
1470 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
1471 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
1472 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
1473 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
1474 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
1475 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
1476 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
1477 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
1478 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
1479 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
1480 * point value.
1481 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
1482 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a DBus object path
1483 * string.
1484 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a DBus signature string.
1485 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
1486 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
1487 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
1488 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
1489 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
1491 * The range of possible top-level types of #GVariant instances.
1493 * Since: 2.24
1495 GVariantClass
1496 g_variant_classify (GVariant *value)
1498 g_return_val_if_fail (value != NULL, 0);
1500 return *g_variant_get_type_string (value);
1503 /* Pretty printer {{{1 */
1505 * g_variant_print_string:
1506 * @value: a #GVariant
1507 * @string: a #GString, or %NULL
1508 * @type_annotate: %TRUE if type information should be included in
1509 * the output
1510 * @returns: a #GString containing the string
1512 * Behaves as g_variant_print(), but operates on a #GString.
1514 * If @string is non-%NULL then it is appended to and returned. Else,
1515 * a new empty #GString is allocated and it is returned.
1517 * Since: 2.24
1519 GString *
1520 g_variant_print_string (GVariant *value,
1521 GString *string,
1522 gboolean type_annotate)
1524 if G_UNLIKELY (string == NULL)
1525 string = g_string_new (NULL);
1527 switch (g_variant_classify (value))
1529 case G_VARIANT_CLASS_MAYBE:
1530 if (type_annotate)
1531 g_string_append_printf (string, "@%s ",
1532 g_variant_get_type_string (value));
1534 if (g_variant_n_children (value))
1536 gchar *printed_child;
1537 GVariant *element;
1539 /* Nested maybes:
1541 * Consider the case of the type "mmi". In this case we could
1542 * write "just just 4", but "4" alone is totally unambiguous,
1543 * so we try to drop "just" where possible.
1545 * We have to be careful not to always drop "just", though,
1546 * since "nothing" needs to be distinguishable from "just
1547 * nothing". The case where we need to ensure we keep the
1548 * "just" is actually exactly the case where we have a nested
1549 * Nothing.
1551 * Instead of searching for that nested Nothing, we just print
1552 * the contained value into a separate string and see if we
1553 * end up with "nothing" at the end of it. If so, we need to
1554 * add "just" at our level.
1556 element = g_variant_get_child_value (value, 0);
1557 printed_child = g_variant_print (element, FALSE);
1558 g_variant_unref (element);
1560 if (g_str_has_suffix (printed_child, "nothing"))
1561 g_string_append (string, "just ");
1562 g_string_append (string, printed_child);
1563 g_free (printed_child);
1565 else
1566 g_string_append (string, "nothing");
1568 break;
1570 case G_VARIANT_CLASS_ARRAY:
1571 /* it's an array so the first character of the type string is 'a'
1573 * if the first two characters are 'a{' then it's an array of
1574 * dictionary entries (ie: a dictionary) so we print that
1575 * differently.
1577 if (g_variant_get_type_string (value)[1] == '{')
1578 /* dictionary */
1580 const gchar *comma = "";
1581 gsize n, i;
1583 if ((n = g_variant_n_children (value)) == 0)
1585 if (type_annotate)
1586 g_string_append_printf (string, "@%s ",
1587 g_variant_get_type_string (value));
1588 g_string_append (string, "{}");
1589 break;
1592 g_string_append_c (string, '{');
1593 for (i = 0; i < n; i++)
1595 GVariant *entry, *key, *val;
1597 g_string_append (string, comma);
1598 comma = ", ";
1600 entry = g_variant_get_child_value (value, i);
1601 key = g_variant_get_child_value (entry, 0);
1602 val = g_variant_get_child_value (entry, 1);
1603 g_variant_unref (entry);
1605 g_variant_print_string (key, string, type_annotate);
1606 g_variant_unref (key);
1607 g_string_append (string, ": ");
1608 g_variant_print_string (val, string, type_annotate);
1609 g_variant_unref (val);
1610 type_annotate = FALSE;
1612 g_string_append_c (string, '}');
1614 else
1615 /* normal (non-dictionary) array */
1617 const gchar *comma = "";
1618 gsize n, i;
1620 if ((n = g_variant_n_children (value)) == 0)
1622 if (type_annotate)
1623 g_string_append_printf (string, "@%s ",
1624 g_variant_get_type_string (value));
1625 g_string_append (string, "[]");
1626 break;
1629 g_string_append_c (string, '[');
1630 for (i = 0; i < n; i++)
1632 GVariant *element;
1634 g_string_append (string, comma);
1635 comma = ", ";
1637 element = g_variant_get_child_value (value, i);
1639 g_variant_print_string (element, string, type_annotate);
1640 g_variant_unref (element);
1641 type_annotate = FALSE;
1643 g_string_append_c (string, ']');
1646 break;
1648 case G_VARIANT_CLASS_TUPLE:
1650 gsize n, i;
1652 n = g_variant_n_children (value);
1654 g_string_append_c (string, '(');
1655 for (i = 0; i < n; i++)
1657 GVariant *element;
1659 element = g_variant_get_child_value (value, i);
1660 g_variant_print_string (element, string, type_annotate);
1661 g_string_append (string, ", ");
1662 g_variant_unref (element);
1665 /* for >1 item: remove final ", "
1666 * for 1 item: remove final " ", but leave the ","
1667 * for 0 items: there is only "(", so remove nothing
1669 g_string_truncate (string, string->len - (n > 0) - (n > 1));
1670 g_string_append_c (string, ')');
1672 break;
1674 case G_VARIANT_CLASS_DICT_ENTRY:
1676 GVariant *element;
1678 g_string_append_c (string, '{');
1680 element = g_variant_get_child_value (value, 0);
1681 g_variant_print_string (element, string, type_annotate);
1682 g_variant_unref (element);
1684 g_string_append (string, ", ");
1686 element = g_variant_get_child_value (value, 1);
1687 g_variant_print_string (element, string, type_annotate);
1688 g_variant_unref (element);
1690 g_string_append_c (string, '}');
1692 break;
1694 case G_VARIANT_CLASS_VARIANT:
1696 GVariant *child = g_variant_get_variant (value);
1698 /* Always annotate types in nested variants, because they are
1699 * (by nature) of variable type.
1701 g_string_append_c (string, '<');
1702 g_variant_print_string (child, string, TRUE);
1703 g_string_append_c (string, '>');
1705 g_variant_unref (child);
1707 break;
1709 case G_VARIANT_CLASS_BOOLEAN:
1710 if (g_variant_get_boolean (value))
1711 g_string_append (string, "true");
1712 else
1713 g_string_append (string, "false");
1714 break;
1716 case G_VARIANT_CLASS_STRING:
1718 const gchar *str = g_variant_get_string (value, NULL);
1719 gunichar quote = strchr (str, '\'') ? '"' : '\'';
1721 g_string_append_c (string, quote);
1723 while (*str)
1725 gunichar c = g_utf8_get_char (str);
1727 if (c == quote || c == '\\')
1728 g_string_append_c (string, '\\');
1730 if (g_unichar_isprint (c))
1731 g_string_append_unichar (string, c);
1733 else
1735 g_string_append_c (string, '\\');
1736 if (c < 0x10000)
1737 switch (c)
1739 case '\a':
1740 g_string_append_c (string, 'a');
1741 break;
1743 case '\b':
1744 g_string_append_c (string, 'b');
1745 break;
1747 case '\f':
1748 g_string_append_c (string, 'f');
1749 break;
1751 case '\n':
1752 g_string_append_c (string, 'n');
1753 break;
1755 case '\r':
1756 g_string_append_c (string, 'r');
1757 break;
1759 case '\t':
1760 g_string_append_c (string, 't');
1761 break;
1763 case '\v':
1764 g_string_append_c (string, 'v');
1765 break;
1767 default:
1768 g_string_append_printf (string, "u%04x", c);
1769 break;
1771 else
1772 g_string_append_printf (string, "U%08x", c);
1775 str = g_utf8_next_char (str);
1778 g_string_append_c (string, quote);
1780 break;
1782 case G_VARIANT_CLASS_BYTE:
1783 if (type_annotate)
1784 g_string_append (string, "byte ");
1785 g_string_append_printf (string, "0x%02x",
1786 g_variant_get_byte (value));
1787 break;
1789 case G_VARIANT_CLASS_INT16:
1790 if (type_annotate)
1791 g_string_append (string, "int16 ");
1792 g_string_append_printf (string, "%"G_GINT16_FORMAT,
1793 g_variant_get_int16 (value));
1794 break;
1796 case G_VARIANT_CLASS_UINT16:
1797 if (type_annotate)
1798 g_string_append (string, "uint16 ");
1799 g_string_append_printf (string, "%"G_GUINT16_FORMAT,
1800 g_variant_get_uint16 (value));
1801 break;
1803 case G_VARIANT_CLASS_INT32:
1804 /* Never annotate this type because it is the default for numbers
1805 * (and this is a *pretty* printer)
1807 g_string_append_printf (string, "%"G_GINT32_FORMAT,
1808 g_variant_get_int32 (value));
1809 break;
1811 case G_VARIANT_CLASS_HANDLE:
1812 if (type_annotate)
1813 g_string_append (string, "handle ");
1814 g_string_append_printf (string, "%"G_GINT32_FORMAT,
1815 g_variant_get_handle (value));
1816 break;
1818 case G_VARIANT_CLASS_UINT32:
1819 if (type_annotate)
1820 g_string_append (string, "uint32 ");
1821 g_string_append_printf (string, "%"G_GUINT32_FORMAT,
1822 g_variant_get_uint32 (value));
1823 break;
1825 case G_VARIANT_CLASS_INT64:
1826 if (type_annotate)
1827 g_string_append (string, "int64 ");
1828 g_string_append_printf (string, "%"G_GINT64_FORMAT,
1829 g_variant_get_int64 (value));
1830 break;
1832 case G_VARIANT_CLASS_UINT64:
1833 if (type_annotate)
1834 g_string_append (string, "uint64 ");
1835 g_string_append_printf (string, "%"G_GUINT64_FORMAT,
1836 g_variant_get_uint64 (value));
1837 break;
1839 case G_VARIANT_CLASS_DOUBLE:
1841 gchar buffer[100];
1842 gint i;
1844 g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
1846 for (i = 0; buffer[i]; i++)
1847 if (buffer[i] == '.' || buffer[i] == 'e' ||
1848 buffer[i] == 'n' || buffer[i] == 'N')
1849 break;
1851 /* if there is no '.' or 'e' in the float then add one */
1852 if (buffer[i] == '\0')
1854 buffer[i++] = '.';
1855 buffer[i++] = '0';
1856 buffer[i++] = '\0';
1859 g_string_append (string, buffer);
1861 break;
1863 case G_VARIANT_CLASS_OBJECT_PATH:
1864 if (type_annotate)
1865 g_string_append (string, "objectpath ");
1866 g_string_append_printf (string, "\'%s\'",
1867 g_variant_get_string (value, NULL));
1868 break;
1870 case G_VARIANT_CLASS_SIGNATURE:
1871 if (type_annotate)
1872 g_string_append (string, "signature ");
1873 g_string_append_printf (string, "\'%s\'",
1874 g_variant_get_string (value, NULL));
1875 break;
1877 default:
1878 g_assert_not_reached ();
1881 return string;
1885 * g_variant_print:
1886 * @value: a #GVariant
1887 * @type_annotate: %TRUE if type information should be included in
1888 * the output
1889 * @returns: a newly-allocated string holding the result.
1891 * Pretty-prints @value in the format understood by g_variant_parse().
1893 * If @type_annotate is %TRUE, then type information is included in
1894 * the output.
1896 gchar *
1897 g_variant_print (GVariant *value,
1898 gboolean type_annotate)
1900 return g_string_free (g_variant_print_string (value, NULL, type_annotate),
1901 FALSE);
1904 /* Hash, Equal, Compare {{{1 */
1906 * g_variant_hash:
1907 * @value: a basic #GVariant value as a #gconstpointer
1908 * @returns: a hash value corresponding to @value
1910 * Generates a hash value for a #GVariant instance.
1912 * The output of this function is guaranteed to be the same for a given
1913 * value only per-process. It may change between different processor
1914 * architectures or even different versions of GLib. Do not use this
1915 * function as a basis for building protocols or file formats.
1917 * The type of @value is #gconstpointer only to allow use of this
1918 * function with #GHashTable. @value must be a #GVariant.
1920 * Since: 2.24
1922 guint
1923 g_variant_hash (gconstpointer value_)
1925 GVariant *value = (GVariant *) value_;
1927 switch (g_variant_classify (value))
1929 case G_VARIANT_CLASS_STRING:
1930 case G_VARIANT_CLASS_OBJECT_PATH:
1931 case G_VARIANT_CLASS_SIGNATURE:
1932 return g_str_hash (g_variant_get_string (value, NULL));
1934 case G_VARIANT_CLASS_BOOLEAN:
1935 /* this is a very odd thing to hash... */
1936 return g_variant_get_boolean (value);
1938 case G_VARIANT_CLASS_BYTE:
1939 return g_variant_get_byte (value);
1941 case G_VARIANT_CLASS_INT16:
1942 case G_VARIANT_CLASS_UINT16:
1944 const guint16 *ptr;
1946 ptr = g_variant_get_data (value);
1948 if (ptr)
1949 return *ptr;
1950 else
1951 return 0;
1954 case G_VARIANT_CLASS_INT32:
1955 case G_VARIANT_CLASS_UINT32:
1956 case G_VARIANT_CLASS_HANDLE:
1958 const guint *ptr;
1960 ptr = g_variant_get_data (value);
1962 if (ptr)
1963 return *ptr;
1964 else
1965 return 0;
1968 case G_VARIANT_CLASS_INT64:
1969 case G_VARIANT_CLASS_UINT64:
1970 case G_VARIANT_CLASS_DOUBLE:
1971 /* need a separate case for these guys because otherwise
1972 * performance could be quite bad on big endian systems
1975 const guint *ptr;
1977 ptr = g_variant_get_data (value);
1979 if (ptr)
1980 return ptr[0] + ptr[1];
1981 else
1982 return 0;
1985 default:
1986 g_return_val_if_fail (!g_variant_is_container (value), 0);
1987 g_assert_not_reached ();
1992 * g_variant_equal:
1993 * @one: a #GVariant instance
1994 * @two: a #GVariant instance
1995 * @returns: %TRUE if @one and @two are equal
1997 * Checks if @one and @two have the same type and value.
1999 * The types of @one and @two are #gconstpointer only to allow use of
2000 * this function with #GHashTable. They must each be a #GVariant.
2002 * Since: 2.24
2004 gboolean
2005 g_variant_equal (gconstpointer one,
2006 gconstpointer two)
2008 gboolean equal;
2010 g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2012 if (g_variant_get_type_info ((GVariant *) one) !=
2013 g_variant_get_type_info ((GVariant *) two))
2014 return FALSE;
2016 /* if both values are trusted to be in their canonical serialised form
2017 * then a simple memcmp() of their serialised data will answer the
2018 * question.
2020 * if not, then this might generate a false negative (since it is
2021 * possible for two different byte sequences to represent the same
2022 * value). for now we solve this by pretty-printing both values and
2023 * comparing the result.
2025 if (g_variant_is_trusted ((GVariant *) one) &&
2026 g_variant_is_trusted ((GVariant *) two))
2028 gconstpointer data_one, data_two;
2029 gsize size_one, size_two;
2031 size_one = g_variant_get_size ((GVariant *) one);
2032 size_two = g_variant_get_size ((GVariant *) two);
2034 if (size_one != size_two)
2035 return FALSE;
2037 data_one = g_variant_get_data ((GVariant *) one);
2038 data_two = g_variant_get_data ((GVariant *) two);
2040 equal = memcmp (data_one, data_two, size_one) == 0;
2042 else
2044 gchar *strone, *strtwo;
2046 strone = g_variant_print ((GVariant *) one, FALSE);
2047 strtwo = g_variant_print ((GVariant *) two, FALSE);
2048 equal = strcmp (strone, strtwo) == 0;
2049 g_free (strone);
2050 g_free (strtwo);
2053 return equal;
2057 * g_variant_compare:
2058 * @one: a basic-typed #GVariant instance
2059 * @two: a #GVariant instance of the same type
2060 * @returns: negative value if a &lt; b;
2061 * zero if a = b;
2062 * positive value if a &gt; b.
2064 * Compares @one and @two.
2066 * The types of @one and @two are #gconstpointer only to allow use of
2067 * this function with #GTree, #GPtrArray, etc. They must each be a
2068 * #GVariant.
2070 * Comparison is only defined for basic types (ie: booleans, numbers,
2071 * strings). For booleans, %FALSE is less than %TRUE. Numbers are
2072 * ordered in the usual way. Strings are in ASCII lexographical order.
2074 * It is a programmer error to attempt to compare container values or
2075 * two values that have types that are not exactly equal. For example,
2076 * you can not compare a 32-bit signed integer with a 32-bit unsigned
2077 * integer. Also note that this function is not particularly
2078 * well-behaved when it comes to comparison of doubles; in particular,
2079 * the handling of incomparable values (ie: NaN) is undefined.
2081 * If you only require an equality comparison, g_variant_equal() is more
2082 * general.
2084 * Since: 2.26
2086 gint
2087 g_variant_compare (gconstpointer one,
2088 gconstpointer two)
2090 GVariant *a = (GVariant *) one;
2091 GVariant *b = (GVariant *) two;
2093 g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2095 switch (g_variant_classify (a))
2097 case G_VARIANT_CLASS_BYTE:
2098 return ((gint) g_variant_get_byte (a)) -
2099 ((gint) g_variant_get_byte (b));
2101 case G_VARIANT_CLASS_INT16:
2102 return ((gint) g_variant_get_int16 (a)) -
2103 ((gint) g_variant_get_int16 (b));
2105 case G_VARIANT_CLASS_UINT16:
2106 return ((gint) g_variant_get_uint16 (a)) -
2107 ((gint) g_variant_get_uint16 (b));
2109 case G_VARIANT_CLASS_INT32:
2111 gint32 a_val = g_variant_get_int32 (a);
2112 gint32 b_val = g_variant_get_int32 (b);
2114 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2117 case G_VARIANT_CLASS_UINT32:
2119 guint32 a_val = g_variant_get_uint32 (a);
2120 guint32 b_val = g_variant_get_uint32 (b);
2122 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2125 case G_VARIANT_CLASS_INT64:
2127 gint64 a_val = g_variant_get_int64 (a);
2128 gint64 b_val = g_variant_get_int64 (b);
2130 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2133 case G_VARIANT_CLASS_UINT64:
2135 guint64 a_val = g_variant_get_int32 (a);
2136 guint64 b_val = g_variant_get_int32 (b);
2138 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2141 case G_VARIANT_CLASS_DOUBLE:
2143 gdouble a_val = g_variant_get_double (a);
2144 gdouble b_val = g_variant_get_double (b);
2146 return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2149 case G_VARIANT_CLASS_STRING:
2150 case G_VARIANT_CLASS_OBJECT_PATH:
2151 case G_VARIANT_CLASS_SIGNATURE:
2152 return strcmp (g_variant_get_string (a, NULL),
2153 g_variant_get_string (b, NULL));
2155 default:
2156 g_return_val_if_fail (!g_variant_is_container (a), 0);
2157 g_assert_not_reached ();
2161 /* GVariantIter {{{1 */
2163 * GVariantIter:
2165 * #GVariantIter is an opaque data structure and can only be accessed
2166 * using the following functions.
2168 struct stack_iter
2170 GVariant *value;
2171 gssize n, i;
2173 const gchar *loop_format;
2175 gsize padding[3];
2176 gsize magic;
2179 G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2181 struct heap_iter
2183 struct stack_iter iter;
2185 GVariant *value_ref;
2186 gsize magic;
2189 #define GVSI(i) ((struct stack_iter *) (i))
2190 #define GVHI(i) ((struct heap_iter *) (i))
2191 #define GVSI_MAGIC ((gsize) 3579507750u)
2192 #define GVHI_MAGIC ((gsize) 1450270775u)
2193 #define is_valid_iter(i) (i != NULL && \
2194 GVSI(i)->magic == GVSI_MAGIC)
2195 #define is_valid_heap_iter(i) (GVHI(i)->magic == GVHI_MAGIC && \
2196 is_valid_iter(i))
2199 * g_variant_iter_new:
2200 * @value: a container #GVariant
2201 * @returns: a new heap-allocated #GVariantIter
2203 * Creates a heap-allocated #GVariantIter for iterating over the items
2204 * in @value.
2206 * Use g_variant_iter_free() to free the return value when you no longer
2207 * need it.
2209 * A reference is taken to @value and will be released only when
2210 * g_variant_iter_free() is called.
2212 * Since: 2.24
2214 GVariantIter *
2215 g_variant_iter_new (GVariant *value)
2217 GVariantIter *iter;
2219 iter = (GVariantIter *) g_slice_new (struct heap_iter);
2220 GVHI(iter)->value_ref = g_variant_ref (value);
2221 GVHI(iter)->magic = GVHI_MAGIC;
2223 g_variant_iter_init (iter, value);
2225 return iter;
2229 * g_variant_iter_init:
2230 * @iter: a pointer to a #GVariantIter
2231 * @value: a container #GVariant
2232 * @returns: the number of items in @value
2234 * Initialises (without allocating) a #GVariantIter. @iter may be
2235 * completely uninitialised prior to this call; its old value is
2236 * ignored.
2238 * The iterator remains valid for as long as @value exists, and need not
2239 * be freed in any way.
2241 * Since: 2.24
2243 gsize
2244 g_variant_iter_init (GVariantIter *iter,
2245 GVariant *value)
2247 GVSI(iter)->magic = GVSI_MAGIC;
2248 GVSI(iter)->value = value;
2249 GVSI(iter)->n = g_variant_n_children (value);
2250 GVSI(iter)->i = -1;
2251 GVSI(iter)->loop_format = NULL;
2253 return GVSI(iter)->n;
2257 * g_variant_iter_copy:
2258 * @iter: a #GVariantIter
2259 * @returns: a new heap-allocated #GVariantIter
2261 * Creates a new heap-allocated #GVariantIter to iterate over the
2262 * container that was being iterated over by @iter. Iteration begins on
2263 * the new iterator from the current position of the old iterator but
2264 * the two copies are independent past that point.
2266 * Use g_variant_iter_free() to free the return value when you no longer
2267 * need it.
2269 * A reference is taken to the container that @iter is iterating over
2270 * and will be releated only when g_variant_iter_free() is called.
2272 * Since: 2.24
2274 GVariantIter *
2275 g_variant_iter_copy (GVariantIter *iter)
2277 GVariantIter *copy;
2279 g_return_val_if_fail (is_valid_iter (iter), 0);
2281 copy = g_variant_iter_new (GVSI(iter)->value);
2282 GVSI(copy)->i = GVSI(iter)->i;
2284 return copy;
2288 * g_variant_iter_n_children:
2289 * @iter: a #GVariantIter
2290 * @returns: the number of children in the container
2292 * Queries the number of child items in the container that we are
2293 * iterating over. This is the total number of items -- not the number
2294 * of items remaining.
2296 * This function might be useful for preallocation of arrays.
2298 * Since: 2.24
2300 gsize
2301 g_variant_iter_n_children (GVariantIter *iter)
2303 g_return_val_if_fail (is_valid_iter (iter), 0);
2305 return GVSI(iter)->n;
2309 * g_variant_iter_free:
2310 * @iter: a heap-allocated #GVariantIter
2312 * Frees a heap-allocated #GVariantIter. Only call this function on
2313 * iterators that were returned by g_variant_iter_new() or
2314 * g_variant_iter_copy().
2316 * Since: 2.24
2318 void
2319 g_variant_iter_free (GVariantIter *iter)
2321 g_return_if_fail (is_valid_heap_iter (iter));
2323 g_variant_unref (GVHI(iter)->value_ref);
2324 GVHI(iter)->magic = 0;
2326 g_slice_free (struct heap_iter, GVHI(iter));
2330 * g_variant_iter_next_value:
2331 * @iter: a #GVariantIter
2332 * @returns: a #GVariant, or %NULL
2334 * Gets the next item in the container. If no more items remain then
2335 * %NULL is returned.
2337 * Use g_variant_unref() to drop your reference on the return value when
2338 * you no longer need it.
2340 * <example>
2341 * <title>Iterating with g_variant_iter_next_value()</title>
2342 * <programlisting>
2343 * /<!-- -->* recursively iterate a container *<!-- -->/
2344 * void
2345 * iterate_container_recursive (GVariant *container)
2347 * GVariantIter iter;
2348 * GVariant *child;
2350 * g_variant_iter_init (&iter, dictionary);
2351 * while ((child = g_variant_iter_next_value (&iter)))
2353 * g_print ("type '%s'\n", g_variant_get_type_string (child));
2355 * if (g_variant_is_container (child))
2356 * iterate_container_recursive (child);
2358 * g_variant_unref (child);
2361 * </programlisting>
2362 * </example>
2364 * Since: 2.24
2366 GVariant *
2367 g_variant_iter_next_value (GVariantIter *iter)
2369 g_return_val_if_fail (is_valid_iter (iter), FALSE);
2371 if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
2373 g_critical ("g_variant_iter_next_value: must not be called again "
2374 "after NULL has already been returned.");
2375 return NULL;
2378 GVSI(iter)->i++;
2380 if (GVSI(iter)->i < GVSI(iter)->n)
2381 return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
2383 return NULL;
2386 /* GVariantBuilder {{{1 */
2388 * GVariantBuilder:
2390 * A utility type for constructing container-type #GVariant instances.
2392 * This is an opaque structure and may only be accessed using the
2393 * following functions.
2395 * #GVariantBuilder is not threadsafe in any way. Do not attempt to
2396 * access it from more than one thread.
2399 struct stack_builder
2401 GVariantBuilder *parent;
2402 GVariantType *type;
2404 /* type constraint explicitly specified by 'type'.
2405 * for tuple types, this moves along as we add more items.
2407 const GVariantType *expected_type;
2409 /* type constraint implied by previous array item.
2411 const GVariantType *prev_item_type;
2413 /* constraints on the number of children. max = -1 for unlimited. */
2414 gsize min_items;
2415 gsize max_items;
2417 /* dynamically-growing pointer array */
2418 GVariant **children;
2419 gsize allocated_children;
2420 gsize offset;
2422 /* set to '1' if all items in the container will have the same type
2423 * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
2425 guint uniform_item_types : 1;
2427 /* set to '1' initially and changed to '0' if an untrusted value is
2428 * added
2430 guint trusted : 1;
2432 gsize magic;
2435 G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
2437 struct heap_builder
2439 GVariantBuilder builder;
2440 gsize magic;
2442 gint ref_count;
2445 #define GVSB(b) ((struct stack_builder *) (b))
2446 #define GVHB(b) ((struct heap_builder *) (b))
2447 #define GVSB_MAGIC ((gsize) 1033660112u)
2448 #define GVHB_MAGIC ((gsize) 3087242682u)
2449 #define is_valid_builder(b) (b != NULL && \
2450 GVSB(b)->magic == GVSB_MAGIC)
2451 #define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
2454 * g_variant_builder_new:
2455 * @type: a container type
2456 * @returns: a #GVariantBuilder
2458 * Allocates and initialises a new #GVariantBuilder.
2460 * You should call g_variant_builder_unref() on the return value when it
2461 * is no longer needed. The memory will not be automatically freed by
2462 * any other call.
2464 * In most cases it is easier to place a #GVariantBuilder directly on
2465 * the stack of the calling function and initialise it with
2466 * g_variant_builder_init().
2468 * Since: 2.24
2470 GVariantBuilder *
2471 g_variant_builder_new (const GVariantType *type)
2473 GVariantBuilder *builder;
2475 builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
2476 g_variant_builder_init (builder, type);
2477 GVHB(builder)->magic = GVHB_MAGIC;
2478 GVHB(builder)->ref_count = 1;
2480 return builder;
2484 * g_variant_builder_unref:
2485 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2487 * Decreases the reference count on @builder.
2489 * In the event that there are no more references, releases all memory
2490 * associated with the #GVariantBuilder.
2492 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2493 * things will happen.
2495 * Since: 2.24
2497 void
2498 g_variant_builder_unref (GVariantBuilder *builder)
2500 g_return_if_fail (is_valid_heap_builder (builder));
2502 if (--GVHB(builder)->ref_count)
2503 return;
2505 g_variant_builder_clear (builder);
2506 GVHB(builder)->magic = 0;
2508 g_slice_free (struct heap_builder, GVHB(builder));
2512 * g_variant_builder_ref:
2513 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
2514 * @returns: a new reference to @builder
2516 * Increases the reference count on @builder.
2518 * Don't call this on stack-allocated #GVariantBuilder instances or bad
2519 * things will happen.
2521 * Since: 2.24
2523 GVariantBuilder *
2524 g_variant_builder_ref (GVariantBuilder *builder)
2526 g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
2528 GVHB(builder)->ref_count++;
2530 return builder;
2534 * g_variant_builder_clear:
2535 * @builder: a #GVariantBuilder
2537 * Releases all memory associated with a #GVariantBuilder without
2538 * freeing the #GVariantBuilder structure itself.
2540 * It typically only makes sense to do this on a stack-allocated
2541 * #GVariantBuilder if you want to abort building the value part-way
2542 * through. This function need not be called if you call
2543 * g_variant_builder_end() and it also doesn't need to be called on
2544 * builders allocated with g_variant_builder_new (see
2545 * g_variant_builder_free() for that).
2547 * This function leaves the #GVariantBuilder structure set to all-zeros.
2548 * It is valid to call this function on either an initialised
2549 * #GVariantBuilder or one that is set to all-zeros but it is not valid
2550 * to call this function on uninitialised memory.
2552 * Since: 2.24
2554 void
2555 g_variant_builder_clear (GVariantBuilder *builder)
2557 gsize i;
2559 if (GVSB(builder)->magic == 0)
2560 /* all-zeros case */
2561 return;
2563 g_return_if_fail (is_valid_builder (builder));
2565 g_variant_type_free (GVSB(builder)->type);
2567 for (i = 0; i < GVSB(builder)->offset; i++)
2568 g_variant_unref (GVSB(builder)->children[i]);
2570 g_free (GVSB(builder)->children);
2572 if (GVSB(builder)->parent)
2574 g_variant_builder_clear (GVSB(builder)->parent);
2575 g_slice_free (GVariantBuilder, GVSB(builder)->parent);
2578 memset (builder, 0, sizeof (GVariantBuilder));
2582 * g_variant_builder_init:
2583 * @builder: a #GVariantBuilder
2584 * @type: a container type
2586 * Initialises a #GVariantBuilder structure.
2588 * @type must be non-%NULL. It specifies the type of container to
2589 * construct. It can be an indefinite type such as
2590 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
2591 * Maybe, array, tuple, dictionary entry and variant-typed values may be
2592 * constructed.
2594 * After the builder is initialised, values are added using
2595 * g_variant_builder_add_value() or g_variant_builder_add().
2597 * After all the child values are added, g_variant_builder_end() frees
2598 * the memory associated with the builder and returns the #GVariant that
2599 * was created.
2601 * This function completely ignores the previous contents of @builder.
2602 * On one hand this means that it is valid to pass in completely
2603 * uninitialised memory. On the other hand, this means that if you are
2604 * initialising over top of an existing #GVariantBuilder you need to
2605 * first call g_variant_builder_clear() in order to avoid leaking
2606 * memory.
2608 * You must not call g_variant_builder_ref() or
2609 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
2610 * with this function. If you ever pass a reference to a
2611 * #GVariantBuilder outside of the control of your own code then you
2612 * should assume that the person receiving that reference may try to use
2613 * reference counting; you should use g_variant_builder_new() instead of
2614 * this function.
2616 * Since: 2.24
2618 void
2619 g_variant_builder_init (GVariantBuilder *builder,
2620 const GVariantType *type)
2622 g_return_if_fail (type != NULL);
2623 g_return_if_fail (g_variant_type_is_container (type));
2625 memset (builder, 0, sizeof (GVariantBuilder));
2627 GVSB(builder)->type = g_variant_type_copy (type);
2628 GVSB(builder)->magic = GVSB_MAGIC;
2629 GVSB(builder)->trusted = TRUE;
2631 switch (*(const gchar *) type)
2633 case G_VARIANT_CLASS_VARIANT:
2634 GVSB(builder)->uniform_item_types = TRUE;
2635 GVSB(builder)->allocated_children = 1;
2636 GVSB(builder)->expected_type = NULL;
2637 GVSB(builder)->min_items = 1;
2638 GVSB(builder)->max_items = 1;
2639 break;
2641 case G_VARIANT_CLASS_ARRAY:
2642 GVSB(builder)->uniform_item_types = TRUE;
2643 GVSB(builder)->allocated_children = 8;
2644 GVSB(builder)->expected_type =
2645 g_variant_type_element (GVSB(builder)->type);
2646 GVSB(builder)->min_items = 0;
2647 GVSB(builder)->max_items = -1;
2648 break;
2650 case G_VARIANT_CLASS_MAYBE:
2651 GVSB(builder)->uniform_item_types = TRUE;
2652 GVSB(builder)->allocated_children = 1;
2653 GVSB(builder)->expected_type =
2654 g_variant_type_element (GVSB(builder)->type);
2655 GVSB(builder)->min_items = 0;
2656 GVSB(builder)->max_items = 1;
2657 break;
2659 case G_VARIANT_CLASS_DICT_ENTRY:
2660 GVSB(builder)->uniform_item_types = FALSE;
2661 GVSB(builder)->allocated_children = 2;
2662 GVSB(builder)->expected_type =
2663 g_variant_type_key (GVSB(builder)->type);
2664 GVSB(builder)->min_items = 2;
2665 GVSB(builder)->max_items = 2;
2666 break;
2668 case 'r': /* G_VARIANT_TYPE_TUPLE was given */
2669 GVSB(builder)->uniform_item_types = FALSE;
2670 GVSB(builder)->allocated_children = 8;
2671 GVSB(builder)->expected_type = NULL;
2672 GVSB(builder)->min_items = 0;
2673 GVSB(builder)->max_items = -1;
2674 break;
2676 case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
2677 GVSB(builder)->allocated_children = g_variant_type_n_items (type);
2678 GVSB(builder)->expected_type =
2679 g_variant_type_first (GVSB(builder)->type);
2680 GVSB(builder)->min_items = GVSB(builder)->allocated_children;
2681 GVSB(builder)->max_items = GVSB(builder)->allocated_children;
2682 GVSB(builder)->uniform_item_types = FALSE;
2683 break;
2685 default:
2686 g_assert_not_reached ();
2689 GVSB(builder)->children = g_new (GVariant *,
2690 GVSB(builder)->allocated_children);
2693 static void
2694 g_variant_builder_make_room (struct stack_builder *builder)
2696 if (builder->offset == builder->allocated_children)
2698 builder->allocated_children *= 2;
2699 builder->children = g_renew (GVariant *, builder->children,
2700 builder->allocated_children);
2705 * g_variant_builder_add_value:
2706 * @builder: a #GVariantBuilder
2707 * @value: a #GVariant
2709 * Adds @value to @builder.
2711 * It is an error to call this function in any way that would create an
2712 * inconsistent value to be constructed. Some examples of this are
2713 * putting different types of items into an array, putting the wrong
2714 * types or number of items in a tuple, putting more than one value into
2715 * a variant, etc.
2717 * Since: 2.24
2719 void
2720 g_variant_builder_add_value (GVariantBuilder *builder,
2721 GVariant *value)
2723 g_return_if_fail (is_valid_builder (builder));
2724 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2725 g_return_if_fail (!GVSB(builder)->expected_type ||
2726 g_variant_is_of_type (value,
2727 GVSB(builder)->expected_type));
2728 g_return_if_fail (!GVSB(builder)->prev_item_type ||
2729 g_variant_is_of_type (value,
2730 GVSB(builder)->prev_item_type));
2732 GVSB(builder)->trusted &= g_variant_is_trusted (value);
2734 if (!GVSB(builder)->uniform_item_types)
2736 /* advance our expected type pointers */
2737 if (GVSB(builder)->expected_type)
2738 GVSB(builder)->expected_type =
2739 g_variant_type_next (GVSB(builder)->expected_type);
2741 if (GVSB(builder)->prev_item_type)
2742 GVSB(builder)->prev_item_type =
2743 g_variant_type_next (GVSB(builder)->prev_item_type);
2745 else
2746 GVSB(builder)->prev_item_type = g_variant_get_type (value);
2748 g_variant_builder_make_room (GVSB(builder));
2750 GVSB(builder)->children[GVSB(builder)->offset++] =
2751 g_variant_ref_sink (value);
2755 * g_variant_builder_open:
2756 * @builder: a #GVariantBuilder
2757 * @type: a #GVariantType
2759 * Opens a subcontainer inside the given @builder. When done adding
2760 * items to the subcontainer, g_variant_builder_close() must be called.
2762 * It is an error to call this function in any way that would cause an
2763 * inconsistent value to be constructed (ie: adding too many values or
2764 * a value of an incorrect type).
2766 * Since: 2.24
2768 void
2769 g_variant_builder_open (GVariantBuilder *builder,
2770 const GVariantType *type)
2772 GVariantBuilder *parent;
2774 g_return_if_fail (is_valid_builder (builder));
2775 g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
2776 g_return_if_fail (!GVSB(builder)->expected_type ||
2777 g_variant_type_is_subtype_of (type,
2778 GVSB(builder)->expected_type));
2779 g_return_if_fail (!GVSB(builder)->prev_item_type ||
2780 g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
2781 type));
2783 parent = g_slice_dup (GVariantBuilder, builder);
2784 g_variant_builder_init (builder, type);
2785 GVSB(builder)->parent = parent;
2787 /* push the prev_item_type down into the subcontainer */
2788 if (GVSB(parent)->prev_item_type)
2790 if (!GVSB(builder)->uniform_item_types)
2791 /* tuples and dict entries */
2792 GVSB(builder)->prev_item_type =
2793 g_variant_type_first (GVSB(parent)->prev_item_type);
2795 else if (!g_variant_type_is_variant (GVSB(builder)->type))
2796 /* maybes and arrays */
2797 GVSB(builder)->prev_item_type =
2798 g_variant_type_element (GVSB(parent)->prev_item_type);
2803 * g_variant_builder_close:
2804 * @builder: a #GVariantBuilder
2806 * Closes the subcontainer inside the given @builder that was opened by
2807 * the most recent call to g_variant_builder_open().
2809 * It is an error to call this function in any way that would create an
2810 * inconsistent value to be constructed (ie: too few values added to the
2811 * subcontainer).
2813 * Since: 2.24
2815 void
2816 g_variant_builder_close (GVariantBuilder *builder)
2818 GVariantBuilder *parent;
2820 g_return_if_fail (is_valid_builder (builder));
2821 g_return_if_fail (GVSB(builder)->parent != NULL);
2823 parent = GVSB(builder)->parent;
2824 GVSB(builder)->parent = NULL;
2826 g_variant_builder_add_value (parent, g_variant_builder_end (builder));
2827 *builder = *parent;
2829 g_slice_free (GVariantBuilder, parent);
2832 /*< private >
2833 * g_variant_make_maybe_type:
2834 * @element: a #GVariant
2836 * Return the type of a maybe containing @element.
2838 static GVariantType *
2839 g_variant_make_maybe_type (GVariant *element)
2841 return g_variant_type_new_maybe (g_variant_get_type (element));
2844 /*< private >
2845 * g_variant_make_array_type:
2846 * @element: a #GVariant
2848 * Return the type of an array containing @element.
2850 static GVariantType *
2851 g_variant_make_array_type (GVariant *element)
2853 return g_variant_type_new_array (g_variant_get_type (element));
2857 * g_variant_builder_end:
2858 * @builder: a #GVariantBuilder
2859 * @returns: a new, floating, #GVariant
2861 * Ends the builder process and returns the constructed value.
2863 * It is not permissible to use @builder in any way after this call
2864 * except for reference counting operations (in the case of a
2865 * heap-allocated #GVariantBuilder) or by reinitialising it with
2866 * g_variant_builder_init() (in the case of stack-allocated).
2868 * It is an error to call this function in any way that would create an
2869 * inconsistent value to be constructed (ie: insufficient number of
2870 * items added to a container with a specific number of children
2871 * required). It is also an error to call this function if the builder
2872 * was created with an indefinite array or maybe type and no children
2873 * have been added; in this case it is impossible to infer the type of
2874 * the empty array.
2876 * Since: 2.24
2878 GVariant *
2879 g_variant_builder_end (GVariantBuilder *builder)
2881 GVariantType *my_type;
2882 GVariant *value;
2884 g_return_val_if_fail (is_valid_builder (builder), NULL);
2885 g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
2886 NULL);
2887 g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
2888 GVSB(builder)->prev_item_type != NULL ||
2889 g_variant_type_is_definite (GVSB(builder)->type),
2890 NULL);
2892 if (g_variant_type_is_definite (GVSB(builder)->type))
2893 my_type = g_variant_type_copy (GVSB(builder)->type);
2895 else if (g_variant_type_is_maybe (GVSB(builder)->type))
2896 my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
2898 else if (g_variant_type_is_array (GVSB(builder)->type))
2899 my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
2901 else if (g_variant_type_is_tuple (GVSB(builder)->type))
2902 my_type = g_variant_make_tuple_type (GVSB(builder)->children,
2903 GVSB(builder)->offset);
2905 else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
2906 my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
2907 GVSB(builder)->children[1]);
2908 else
2909 g_assert_not_reached ();
2911 value = g_variant_new_from_children (my_type,
2912 g_renew (GVariant *,
2913 GVSB(builder)->children,
2914 GVSB(builder)->offset),
2915 GVSB(builder)->offset,
2916 GVSB(builder)->trusted);
2917 GVSB(builder)->children = NULL;
2918 GVSB(builder)->offset = 0;
2920 g_variant_builder_clear (builder);
2921 g_variant_type_free (my_type);
2923 return value;
2926 /* Format strings {{{1 */
2927 /*< private >
2928 * g_variant_format_string_scan:
2929 * @string: a string that may be prefixed with a format string
2930 * @limit: a pointer to the end of @string, or %NULL
2931 * @endptr: location to store the end pointer, or %NULL
2932 * @returns: %TRUE if there was a valid format string
2934 * Checks the string pointed to by @string for starting with a properly
2935 * formed #GVariant varargs format string. If no valid format string is
2936 * found then %FALSE is returned.
2938 * If @string does start with a valid format string then %TRUE is
2939 * returned. If @endptr is non-%NULL then it is updated to point to the
2940 * first character after the format string.
2942 * If @limit is non-%NULL then @limit (and any charater after it) will
2943 * not be accessed and the effect is otherwise equivalent to if the
2944 * character at @limit were nul.
2946 * See the section on <link linkend='gvariant-format-strings'>GVariant
2947 * Format Strings</link>.
2949 * Since: 2.24
2951 gboolean
2952 g_variant_format_string_scan (const gchar *string,
2953 const gchar *limit,
2954 const gchar **endptr)
2956 #define next_char() (string == limit ? '\0' : *string++)
2957 #define peek_char() (string == limit ? '\0' : *string)
2958 char c;
2960 switch (next_char())
2962 case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
2963 case 'x': case 't': case 'h': case 'd': case 's': case 'o':
2964 case 'g': case 'v': case '*': case '?': case 'r':
2965 break;
2967 case 'm':
2968 return g_variant_format_string_scan (string, limit, endptr);
2970 case 'a':
2971 case '@':
2972 return g_variant_type_string_scan (string, limit, endptr);
2974 case '(':
2975 while (peek_char() != ')')
2976 if (!g_variant_format_string_scan (string, limit, &string))
2977 return FALSE;
2979 next_char(); /* consume ')' */
2980 break;
2982 case '{':
2983 c = next_char();
2985 if (c == '&')
2987 c = next_char ();
2989 if (c != 's' && c != 'o' && c != 'g')
2990 return FALSE;
2992 else
2994 if (c == '@')
2995 c = next_char ();
2997 /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
2998 * The terminating null character is considered to be
2999 * part of the string.
3001 if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
3002 return FALSE;
3005 if (!g_variant_format_string_scan (string, limit, &string))
3006 return FALSE;
3008 if (next_char() != '}')
3009 return FALSE;
3011 break;
3013 case '^': /* '^as' or '^a&s' only */
3014 if (next_char() != 'a')
3015 return FALSE;
3017 if (peek_char() == '&')
3018 next_char ();
3020 c = next_char ();
3022 if (c != 's' && c != 'o' && c != 'g')
3023 return FALSE;
3025 break;
3027 case '&':
3028 c = next_char();
3030 if (c != 's' && c != 'o' && c != 'g')
3031 return FALSE;
3033 break;
3035 default:
3036 return FALSE;
3039 if (endptr != NULL)
3040 *endptr = string;
3042 #undef next_char
3043 #undef peek_char
3045 return TRUE;
3048 /*< private >
3049 * g_variant_format_string_scan_type:
3050 * @string: a string that may be prefixed with a format string
3051 * @limit: a pointer to the end of @string
3052 * @endptr: location to store the end pointer, or %NULL
3053 * @returns: a #GVariantType if there was a valid format string
3055 * If @string starts with a valid format string then this function will
3056 * return the type that the format string corresponds to. Otherwise
3057 * this function returns %NULL.
3059 * Use g_variant_type_free() to free the return value when you no longer
3060 * need it.
3062 * This function is otherwise exactly like
3063 * g_variant_format_string_scan().
3065 * Since: 2.24
3067 GVariantType *
3068 g_variant_format_string_scan_type (const gchar *string,
3069 const gchar *limit,
3070 const gchar **endptr)
3072 const gchar *my_end;
3073 gchar *dest;
3074 gchar *new;
3076 if (endptr == NULL)
3077 endptr = &my_end;
3079 if (!g_variant_format_string_scan (string, limit, endptr))
3080 return NULL;
3082 dest = new = g_malloc (*endptr - string + 1);
3083 while (string != *endptr)
3085 if (*string != '@' && *string != '&' && *string != '^')
3086 *dest++ = *string;
3087 string++;
3089 *dest = '\0';
3091 return (GVariantType *) G_VARIANT_TYPE (new);
3094 static gboolean
3095 valid_format_string (const gchar *format_string,
3096 gboolean single,
3097 GVariant *value)
3099 const gchar *endptr;
3100 GVariantType *type;
3102 type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
3104 if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
3106 if (single)
3107 g_critical ("`%s' is not a valid GVariant format string",
3108 format_string);
3109 else
3110 g_critical ("`%s' does not have a valid GVariant format "
3111 "string as a prefix", format_string);
3113 if (type != NULL)
3114 g_variant_type_free (type);
3116 return FALSE;
3119 if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
3121 gchar *fragment;
3122 gchar *typestr;
3124 fragment = g_strndup (format_string, endptr - format_string);
3125 typestr = g_variant_type_dup_string (type);
3127 g_critical ("the GVariant format string `%s' has a type of "
3128 "`%s' but the given value has a type of `%s'",
3129 fragment, typestr, g_variant_get_type_string (value));
3131 g_variant_type_free (type);
3133 return FALSE;
3136 g_variant_type_free (type);
3138 return TRUE;
3141 /* Variable Arguments {{{1 */
3142 /* We consider 2 main classes of format strings:
3144 * - recursive format strings
3145 * these are ones that result in recursion and the collection of
3146 * possibly more than one argument. Maybe types, tuples,
3147 * dictionary entries.
3149 * - leaf format string
3150 * these result in the collection of a single argument.
3152 * Leaf format strings are further subdivided into two categories:
3154 * - single non-null pointer ("nnp")
3155 * these either collect or return a single non-null pointer.
3157 * - other
3158 * these collect or return something else (bool, number, etc).
3160 * Based on the above, the varargs handling code is split into 4 main parts:
3162 * - nnp handling code
3163 * - leaf handling code (which may invoke nnp code)
3164 * - generic handling code (may be recursive, may invoke leaf code)
3165 * - user-facing API (which invokes the generic code)
3167 * Each section implements some of the following functions:
3169 * - skip:
3170 * collect the arguments for the format string as if
3171 * g_variant_new() had been called, but do nothing with them. used
3172 * for skipping over arguments when constructing a Nothing maybe
3173 * type.
3175 * - new:
3176 * create a GVariant *
3178 * - get:
3179 * unpack a GVariant *
3181 * - free (nnp only):
3182 * free a previously allocated item
3185 static gboolean
3186 g_variant_format_string_is_leaf (const gchar *str)
3188 return str[0] != 'm' && str[0] != '(' && str[0] != '{';
3191 static gboolean
3192 g_variant_format_string_is_nnp (const gchar *str)
3194 return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
3195 str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
3196 str[0] == 'r' || str[0] == 'v' || str[0] == '&';
3199 /* Single non-null pointer ("nnp") {{{2 */
3200 static void
3201 g_variant_valist_free_nnp (const gchar *str,
3202 gpointer ptr)
3204 switch (*str)
3206 case 'a':
3207 g_variant_iter_free (ptr);
3208 break;
3210 case '^':
3211 if (str[2] != '&') /* '^as' */
3212 g_strfreev (ptr);
3213 else /* '^a&s' */
3214 g_free (ptr);
3215 break;
3217 case 's':
3218 case 'o':
3219 case 'g':
3220 g_free (ptr);
3221 break;
3223 case '@':
3224 case '*':
3225 case '?':
3226 case 'v':
3227 g_variant_unref (ptr);
3228 break;
3230 case '&':
3231 break;
3233 default:
3234 g_assert_not_reached ();
3238 static GVariant *
3239 g_variant_valist_new_nnp (const gchar **str,
3240 gpointer ptr)
3242 if (**str == '&')
3243 (*str)++;
3245 switch (*(*str)++)
3247 case 'a':
3249 const GVariantType *type;
3250 GVariant *value;
3252 value = g_variant_builder_end (ptr);
3253 type = g_variant_get_type (value);
3255 if G_UNLIKELY (!g_variant_type_is_array (type))
3256 g_error ("g_variant_new: expected array GVariantBuilder but "
3257 "the built value has type `%s'",
3258 g_variant_get_type_string (value));
3260 type = g_variant_type_element (type);
3262 if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
3263 g_error ("g_variant_new: expected GVariantBuilder array element "
3264 "type `%s' but the built value has element type `%s'",
3265 g_variant_type_dup_string ((GVariantType *) *str),
3266 g_variant_get_type_string (value) + 1);
3268 g_variant_type_string_scan (*str, NULL, str);
3270 return value;
3273 case 's':
3274 return g_variant_new_string (ptr);
3276 case 'o':
3277 return g_variant_new_object_path (ptr);
3279 case 'g':
3280 return g_variant_new_signature (ptr);
3282 case '^':
3284 const GVariantType *type;
3285 GVariantType *array_type;
3286 GVariant **children;
3287 gchar **strv = ptr;
3288 GVariant *value;
3289 guint length, i;
3291 if ((*str)[1] == '&') /* '^a&s' */
3292 (*str) += 2;
3293 else /* '^as' */
3294 (*str)++;
3296 type = (GVariantType *) (*str)++;
3297 array_type = g_variant_type_new_array (type);
3298 length = g_strv_length (strv);
3299 children = g_new (GVariant *, length);
3300 for (i = 0; i < length; i++)
3301 children[i] = g_variant_ref_sink (
3302 g_variant_new_from_trusted (type, strv[i], strlen (strv[i]) + 1));
3304 value = g_variant_new_from_children (array_type, children,
3305 length, TRUE);
3306 g_variant_type_free (array_type);
3308 return value;
3311 case '@':
3312 if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
3313 g_error ("g_variant_new: expected GVariant of type `%s' but "
3314 "received value has type `%s'",
3315 g_variant_type_dup_string ((GVariantType *) *str),
3316 g_variant_get_type_string (ptr));
3318 g_variant_type_string_scan (*str, NULL, str);
3320 return ptr;
3322 case '*':
3323 return ptr;
3325 case '?':
3326 if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
3327 g_error ("g_variant_new: format string `?' expects basic-typed "
3328 "GVariant, but received value has type `%s'",
3329 g_variant_get_type_string (ptr));
3331 return ptr;
3333 case 'r':
3334 if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
3335 g_error ("g_variant_new: format string `r` expects tuple-typed "
3336 "GVariant, but received value has type `%s'",
3337 g_variant_get_type_string (ptr));
3339 return ptr;
3341 case 'v':
3342 return g_variant_new_variant (ptr);
3344 default:
3345 g_assert_not_reached ();
3349 static gpointer
3350 g_variant_valist_get_nnp (const gchar **str,
3351 GVariant *value)
3353 switch (*(*str)++)
3355 case 'a':
3356 g_variant_type_string_scan (*str, NULL, str);
3357 return g_variant_iter_new (value);
3359 case '&':
3360 (*str)++;
3361 return (gchar *) g_variant_get_string (value, NULL);
3363 case 's':
3364 case 'o':
3365 case 'g':
3366 return g_variant_dup_string (value, NULL);
3368 case '^':
3369 if ((*str)[1] == '&') /* '^a&s' */
3371 (*str) += 3;
3372 return g_variant_get_strv (value, NULL);
3374 else /* '^as' */
3376 (*str) += 2;
3377 return g_variant_dup_strv (value, NULL);
3380 case '@':
3381 g_variant_type_string_scan (*str, NULL, str);
3382 /* fall through */
3384 case '*':
3385 case '?':
3386 case 'r':
3387 return g_variant_ref (value);
3389 case 'v':
3390 return g_variant_get_variant (value);
3392 default:
3393 g_assert_not_reached ();
3397 /* Leaves {{{2 */
3398 static void
3399 g_variant_valist_skip_leaf (const gchar **str,
3400 va_list *app)
3402 if (g_variant_format_string_is_nnp (*str))
3404 g_variant_format_string_scan (*str, NULL, str);
3405 va_arg (*app, gpointer);
3406 return;
3409 switch (*(*str)++)
3411 case 'b':
3412 case 'y':
3413 case 'n':
3414 case 'q':
3415 case 'i':
3416 case 'u':
3417 case 'h':
3418 va_arg (*app, int);
3419 return;
3421 case 'x':
3422 case 't':
3423 va_arg (*app, guint64);
3424 return;
3426 case 'd':
3427 va_arg (*app, gdouble);
3428 return;
3430 default:
3431 g_assert_not_reached ();
3435 static GVariant *
3436 g_variant_valist_new_leaf (const gchar **str,
3437 va_list *app)
3439 if (g_variant_format_string_is_nnp (*str))
3440 return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
3442 switch (*(*str)++)
3444 case 'b':
3445 return g_variant_new_boolean (va_arg (*app, gboolean));
3447 case 'y':
3448 return g_variant_new_byte (va_arg (*app, guint));
3450 case 'n':
3451 return g_variant_new_int16 (va_arg (*app, gint));
3453 case 'q':
3454 return g_variant_new_uint16 (va_arg (*app, guint));
3456 case 'i':
3457 return g_variant_new_int32 (va_arg (*app, gint));
3459 case 'u':
3460 return g_variant_new_uint32 (va_arg (*app, guint));
3462 case 'x':
3463 return g_variant_new_int64 (va_arg (*app, gint64));
3465 case 't':
3466 return g_variant_new_uint64 (va_arg (*app, guint64));
3468 case 'h':
3469 return g_variant_new_handle (va_arg (*app, gint));
3471 case 'd':
3472 return g_variant_new_double (va_arg (*app, gdouble));
3474 default:
3475 g_assert_not_reached ();
3479 /* The code below assumes this */
3480 G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
3481 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
3483 static void
3484 g_variant_valist_get_leaf (const gchar **str,
3485 GVariant *value,
3486 gboolean free,
3487 va_list *app)
3489 gpointer ptr = va_arg (*app, gpointer);
3491 if (ptr == NULL)
3493 g_variant_format_string_scan (*str, NULL, str);
3494 return;
3497 if (g_variant_format_string_is_nnp (*str))
3499 gpointer *nnp = (gpointer *) ptr;
3501 if (free && *nnp != NULL)
3502 g_variant_valist_free_nnp (*str, *nnp);
3504 *nnp = NULL;
3506 if (value != NULL)
3507 *nnp = g_variant_valist_get_nnp (str, value);
3508 else
3509 g_variant_format_string_scan (*str, NULL, str);
3511 return;
3514 if (value != NULL)
3516 switch (*(*str)++)
3518 case 'b':
3519 *(gboolean *) ptr = g_variant_get_boolean (value);
3520 return;
3522 case 'y':
3523 *(guchar *) ptr = g_variant_get_byte (value);
3524 return;
3526 case 'n':
3527 *(gint16 *) ptr = g_variant_get_int16 (value);
3528 return;
3530 case 'q':
3531 *(guint16 *) ptr = g_variant_get_uint16 (value);
3532 return;
3534 case 'i':
3535 *(gint32 *) ptr = g_variant_get_int32 (value);
3536 return;
3538 case 'u':
3539 *(guint32 *) ptr = g_variant_get_uint32 (value);
3540 return;
3542 case 'x':
3543 *(gint64 *) ptr = g_variant_get_int64 (value);
3544 return;
3546 case 't':
3547 *(guint64 *) ptr = g_variant_get_uint64 (value);
3548 return;
3550 case 'h':
3551 *(gint32 *) ptr = g_variant_get_handle (value);
3552 return;
3554 case 'd':
3555 *(gdouble *) ptr = g_variant_get_double (value);
3556 return;
3559 else
3561 switch (*(*str)++)
3563 case 'y':
3564 *(guchar *) ptr = 0;
3565 return;
3567 case 'n':
3568 case 'q':
3569 *(guint16 *) ptr = 0;
3570 return;
3572 case 'i':
3573 case 'u':
3574 case 'h':
3575 case 'b':
3576 *(guint32 *) ptr = 0;
3577 return;
3579 case 'x':
3580 case 't':
3581 case 'd':
3582 *(guint64 *) ptr = 0;
3583 return;
3587 g_assert_not_reached ();
3590 /* Generic (recursive) {{{2 */
3591 static void
3592 g_variant_valist_skip (const gchar **str,
3593 va_list *app)
3595 if (g_variant_format_string_is_leaf (*str))
3596 g_variant_valist_skip_leaf (str, app);
3598 else if (**str == 'm') /* maybe */
3600 (*str)++;
3602 if (!g_variant_format_string_is_nnp (*str))
3603 va_arg (*app, gboolean);
3605 g_variant_valist_skip (str, app);
3607 else /* tuple, dictionary entry */
3609 g_assert (**str == '(' || **str == '{');
3610 (*str)++;
3611 while (**str != ')' && **str != '}')
3612 g_variant_valist_skip (str, app);
3613 (*str)++;
3617 static GVariant *
3618 g_variant_valist_new (const gchar **str,
3619 va_list *app)
3621 if (g_variant_format_string_is_leaf (*str))
3622 return g_variant_valist_new_leaf (str, app);
3624 if (**str == 'm') /* maybe */
3626 GVariantType *type = NULL;
3627 GVariant *value = NULL;
3629 (*str)++;
3631 if (g_variant_format_string_is_nnp (*str))
3633 gpointer nnp = va_arg (*app, gpointer);
3635 if (nnp != NULL)
3636 value = g_variant_valist_new_nnp (str, nnp);
3637 else
3638 type = g_variant_format_string_scan_type (*str, NULL, str);
3640 else
3642 gboolean just = va_arg (*app, gboolean);
3644 if (just)
3645 value = g_variant_valist_new (str, app);
3646 else
3648 type = g_variant_format_string_scan_type (*str, NULL, NULL);
3649 g_variant_valist_skip (str, app);
3653 value = g_variant_new_maybe (type, value);
3655 if (type != NULL)
3656 g_variant_type_free (type);
3658 return value;
3660 else /* tuple, dictionary entry */
3662 GVariantBuilder b;
3664 if (**str == '(')
3665 g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
3666 else
3668 g_assert (**str == '{');
3669 g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
3672 (*str)++; /* '(' */
3673 while (**str != ')' && **str != '}')
3674 g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
3675 (*str)++; /* ')' */
3677 return g_variant_builder_end (&b);
3681 static void
3682 g_variant_valist_get (const gchar **str,
3683 GVariant *value,
3684 gboolean free,
3685 va_list *app)
3687 if (g_variant_format_string_is_leaf (*str))
3688 g_variant_valist_get_leaf (str, value, free, app);
3690 else if (**str == 'm')
3692 (*str)++;
3694 if (value != NULL)
3695 value = g_variant_get_maybe (value);
3697 if (!g_variant_format_string_is_nnp (*str))
3699 gboolean *ptr = va_arg (*app, gboolean *);
3701 if (ptr != NULL)
3702 *ptr = value != NULL;
3705 g_variant_valist_get (str, value, free, app);
3707 if (value != NULL)
3708 g_variant_unref (value);
3711 else /* tuple, dictionary entry */
3713 gint index = 0;
3715 g_assert (**str == '(' || **str == '{');
3717 (*str)++;
3718 while (**str != ')' && **str != '}')
3720 if (value != NULL)
3722 GVariant *child = g_variant_get_child_value (value, index++);
3723 g_variant_valist_get (str, child, free, app);
3724 g_variant_unref (child);
3726 else
3727 g_variant_valist_get (str, NULL, free, app);
3729 (*str)++;
3733 /* User-facing API {{{2 */
3735 * g_variant_new:
3736 * @format_string: a #GVariant format string
3737 * @...: arguments, as per @format_string
3738 * @returns: a new floating #GVariant instance
3740 * Creates a new #GVariant instance.
3742 * Think of this function as an analogue to g_strdup_printf().
3744 * The type of the created instance and the arguments that are
3745 * expected by this function are determined by @format_string. See the
3746 * section on <link linkend='gvariant-format-strings'>GVariant Format
3747 * Strings</link>. Please note that the syntax of the format string is
3748 * very likely to be extended in the future.
3750 * The first character of the format string must not be '*' '?' '@' or
3751 * 'r'; in essence, a new #GVariant must always be constructed by this
3752 * function (and not merely passed through it unmodified).
3754 * Since: 2.24
3756 GVariant *
3757 g_variant_new (const gchar *format_string,
3758 ...)
3760 GVariant *value;
3761 va_list ap;
3763 g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
3764 format_string[0] != '?' && format_string[0] != '@' &&
3765 format_string[0] != '*' && format_string[0] != 'r',
3766 NULL);
3768 va_start (ap, format_string);
3769 value = g_variant_new_va (format_string, NULL, &ap);
3770 va_end (ap);
3772 return value;
3776 * g_variant_new_va:
3777 * @format_string: a string that is prefixed with a format string
3778 * @endptr: location to store the end pointer, or %NULL
3779 * @app: a pointer to a #va_list
3780 * @returns: a new, usually floating, #GVariant
3782 * This function is intended to be used by libraries based on
3783 * #GVariant that want to provide g_variant_new()-like functionality
3784 * to their users.
3786 * The API is more general than g_variant_new() to allow a wider range
3787 * of possible uses.
3789 * @format_string must still point to a valid format string, but it only
3790 * needs to be nul-terminated if @endptr is %NULL. If @endptr is
3791 * non-%NULL then it is updated to point to the first character past the
3792 * end of the format string.
3794 * @app is a pointer to a #va_list. The arguments, according to
3795 * @format_string, are collected from this #va_list and the list is left
3796 * pointing to the argument following the last.
3798 * These two generalisations allow mixing of multiple calls to
3799 * g_variant_new_va() and g_variant_get_va() within a single actual
3800 * varargs call by the user.
3802 * The return value will be floating if it was a newly created GVariant
3803 * instance (for example, if the format string was "(ii)"). In the case
3804 * that the format_string was '*', '?', 'r', or a format starting with
3805 * '@' then the collected #GVariant pointer will be returned unmodified,
3806 * without adding any additional references.
3808 * In order to behave correctly in all cases it is necessary for the
3809 * calling function to g_variant_ref_sink() the return result before
3810 * returning control to the user that originally provided the pointer.
3811 * At this point, the caller will have their own full reference to the
3812 * result. This can also be done by adding the result to a container,
3813 * or by passing it to another g_variant_new() call.
3815 * Since: 2.24
3817 GVariant *
3818 g_variant_new_va (const gchar *format_string,
3819 const gchar **endptr,
3820 va_list *app)
3822 GVariant *value;
3824 g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
3825 NULL);
3826 g_return_val_if_fail (app != NULL, NULL);
3828 value = g_variant_valist_new (&format_string, app);
3830 if (endptr != NULL)
3831 *endptr = format_string;
3833 return value;
3837 * g_variant_get:
3838 * @value: a #GVariant instance
3839 * @format_string: a #GVariant format string
3840 * @...: arguments, as per @format_string
3842 * Deconstructs a #GVariant instance.
3844 * Think of this function as an analogue to scanf().
3846 * The arguments that are expected by this function are entirely
3847 * determined by @format_string. @format_string also restricts the
3848 * permissible types of @value. It is an error to give a value with
3849 * an incompatible type. See the section on <link
3850 * linkend='gvariant-format-strings'>GVariant Format Strings</link>.
3851 * Please note that the syntax of the format string is very likely to be
3852 * extended in the future.
3854 * Since: 2.24
3856 void
3857 g_variant_get (GVariant *value,
3858 const gchar *format_string,
3859 ...)
3861 va_list ap;
3863 g_return_if_fail (valid_format_string (format_string, TRUE, value));
3865 /* if any direct-pointer-access formats are in use, flatten first */
3866 if (strchr (format_string, '&'))
3867 g_variant_get_data (value);
3869 va_start (ap, format_string);
3870 g_variant_get_va (value, format_string, NULL, &ap);
3871 va_end (ap);
3875 * g_variant_get_va:
3876 * @value: a #GVariant
3877 * @format_string: a string that is prefixed with a format string
3878 * @endptr: location to store the end pointer, or %NULL
3879 * @app: a pointer to a #va_list
3881 * This function is intended to be used by libraries based on #GVariant
3882 * that want to provide g_variant_get()-like functionality to their
3883 * users.
3885 * The API is more general than g_variant_get() to allow a wider range
3886 * of possible uses.
3888 * @format_string must still point to a valid format string, but it only
3889 * need to be nul-terminated if @endptr is %NULL. If @endptr is
3890 * non-%NULL then it is updated to point to the first character past the
3891 * end of the format string.
3893 * @app is a pointer to a #va_list. The arguments, according to
3894 * @format_string, are collected from this #va_list and the list is left
3895 * pointing to the argument following the last.
3897 * These two generalisations allow mixing of multiple calls to
3898 * g_variant_new_va() and g_variant_get_va() within a single actual
3899 * varargs call by the user.
3901 * Since: 2.24
3903 void
3904 g_variant_get_va (GVariant *value,
3905 const gchar *format_string,
3906 const gchar **endptr,
3907 va_list *app)
3909 g_return_if_fail (valid_format_string (format_string, !endptr, value));
3910 g_return_if_fail (value != NULL);
3911 g_return_if_fail (app != NULL);
3913 /* if any direct-pointer-access formats are in use, flatten first */
3914 if (strchr (format_string, '&'))
3915 g_variant_get_data (value);
3917 g_variant_valist_get (&format_string, value, FALSE, app);
3919 if (endptr != NULL)
3920 *endptr = format_string;
3923 /* Varargs-enabled Utility Functions {{{1 */
3926 * g_variant_builder_add:
3927 * @builder: a #GVariantBuilder
3928 * @format_string: a #GVariant varargs format string
3929 * @...: arguments, as per @format_string
3931 * Adds to a #GVariantBuilder.
3933 * This call is a convenience wrapper that is exactly equivalent to
3934 * calling g_variant_new() followed by g_variant_builder_add_value().
3936 * This function might be used as follows:
3938 * <programlisting>
3939 * GVariant *
3940 * make_pointless_dictionary (void)
3942 * GVariantBuilder *builder;
3943 * int i;
3945 * builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3946 * for (i = 0; i < 16; i++)
3948 * gchar buf[3];
3950 * sprintf (buf, "%d", i);
3951 * g_variant_builder_add (builder, "{is}", i, buf);
3954 * return g_variant_builder_end (builder);
3956 * </programlisting>
3958 * Since: 2.24
3960 void
3961 g_variant_builder_add (GVariantBuilder *builder,
3962 const gchar *format_string,
3963 ...)
3965 GVariant *variant;
3966 va_list ap;
3968 va_start (ap, format_string);
3969 variant = g_variant_new_va (format_string, NULL, &ap);
3970 va_end (ap);
3972 g_variant_builder_add_value (builder, variant);
3976 * g_variant_get_child:
3977 * @value: a container #GVariant
3978 * @index_: the index of the child to deconstruct
3979 * @format_string: a #GVariant format string
3980 * @...: arguments, as per @format_string
3982 * Reads a child item out of a container #GVariant instance and
3983 * deconstructs it according to @format_string. This call is
3984 * essentially a combination of g_variant_get_child_value() and
3985 * g_variant_get().
3987 * Since: 2.24
3989 void
3990 g_variant_get_child (GVariant *value,
3991 gsize index_,
3992 const gchar *format_string,
3993 ...)
3995 GVariant *child;
3996 va_list ap;
3998 child = g_variant_get_child_value (value, index_);
3999 g_return_if_fail (valid_format_string (format_string, TRUE, child));
4001 va_start (ap, format_string);
4002 g_variant_get_va (child, format_string, NULL, &ap);
4003 va_end (ap);
4005 g_variant_unref (child);
4009 * g_variant_iter_next:
4010 * @iter: a #GVariantIter
4011 * @format_string: a GVariant format string
4012 * @...: the arguments to unpack the value into
4013 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4014 * value
4016 * Gets the next item in the container and unpacks it into the variable
4017 * argument list according to @format_string, returning %TRUE.
4019 * If no more items remain then %FALSE is returned.
4021 * All of the pointers given on the variable arguments list of this
4022 * function are assumed to point at uninitialised memory. It is the
4023 * responsibility of the caller to free all of the values returned by
4024 * the unpacking process.
4026 * See the section on <link linkend='gvariant-format-strings'>GVariant
4027 * Format Strings</link>.
4029 * <example>
4030 * <title>Memory management with g_variant_iter_next()</title>
4031 * <programlisting>
4032 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4033 * void
4034 * iterate_dictionary (GVariant *dictionary)
4036 * GVariantIter iter;
4037 * GVariant *value;
4038 * gchar *key;
4040 * g_variant_iter_init (&iter, dictionary);
4041 * while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4043 * g_print ("Item '%s' has type '%s'\n", key,
4044 * g_variant_get_type_string (value));
4046 * /<!-- -->* must free data for ourselves *<!-- -->/
4047 * g_variant_unref (value);
4048 * g_free (key);
4051 * </programlisting>
4052 * </example>
4054 * For a solution that is likely to be more convenient to C programmers
4055 * when dealing with loops, see g_variant_iter_loop().
4057 * Since: 2.24
4059 gboolean
4060 g_variant_iter_next (GVariantIter *iter,
4061 const gchar *format_string,
4062 ...)
4064 GVariant *value;
4066 value = g_variant_iter_next_value (iter);
4068 g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
4069 FALSE);
4071 if (value != NULL)
4073 va_list ap;
4075 va_start (ap, format_string);
4076 g_variant_valist_get (&format_string, value, FALSE, &ap);
4077 va_end (ap);
4079 g_variant_unref (value);
4082 return value != NULL;
4086 * g_variant_iter_loop:
4087 * @iter: a #GVariantIter
4088 * @format_string: a GVariant format string
4089 * @...: the arguments to unpack the value into
4090 * @returns: %TRUE if a value was unpacked, or %FALSE if there as no
4091 * value
4093 * Gets the next item in the container and unpacks it into the variable
4094 * argument list according to @format_string, returning %TRUE.
4096 * If no more items remain then %FALSE is returned.
4098 * On the first call to this function, the pointers appearing on the
4099 * variable argument list are assumed to point at uninitialised memory.
4100 * On the second and later calls, it is assumed that the same pointers
4101 * will be given and that they will point to the memory as set by the
4102 * previous call to this function. This allows the previous values to
4103 * be freed, as appropriate.
4105 * This function is intended to be used with a while loop as
4106 * demonstrated in the following example. This function can only be
4107 * used when iterating over an array. It is only valid to call this
4108 * function with a string constant for the format string and the same
4109 * string constant must be used each time. Mixing calls to this
4110 * function and g_variant_iter_next() or g_variant_iter_next_value() on
4111 * the same iterator is not recommended.
4113 * See the section on <link linkend='gvariant-format-strings'>GVariant
4114 * Format Strings</link>.
4116 * <example>
4117 * <title>Memory management with g_variant_iter_loop()</title>
4118 * <programlisting>
4119 * /<!-- -->* Iterates a dictionary of type 'a{sv}' *<!-- -->/
4120 * void
4121 * iterate_dictionary (GVariant *dictionary)
4123 * GVariantIter iter;
4124 * GVariant *value;
4125 * gchar *key;
4127 * g_variant_iter_init (&iter, dictionary);
4128 * while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
4130 * g_print ("Item '%s' has type '%s'\n", key,
4131 * g_variant_get_type_string (value));
4133 * /<!-- -->* no need to free 'key' and 'value' here *<!-- -->/
4136 * </programlisting>
4137 * </example>
4139 * If you want a slightly less magical alternative that requires more
4140 * typing, see g_variant_iter_next().
4142 * Since: 2.24
4144 gboolean
4145 g_variant_iter_loop (GVariantIter *iter,
4146 const gchar *format_string,
4147 ...)
4149 gboolean first_time = GVSI(iter)->loop_format == NULL;
4150 GVariant *value;
4151 va_list ap;
4153 g_return_val_if_fail (first_time ||
4154 format_string == GVSI(iter)->loop_format,
4155 FALSE);
4157 if (first_time)
4159 TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
4160 GVSI(iter)->loop_format = format_string;
4162 if (strchr (format_string, '&'))
4163 g_variant_get_data (GVSI(iter)->value);
4166 value = g_variant_iter_next_value (iter);
4168 g_return_val_if_fail (!first_time ||
4169 valid_format_string (format_string, TRUE, value),
4170 FALSE);
4172 va_start (ap, format_string);
4173 g_variant_valist_get (&format_string, value, !first_time, &ap);
4174 va_end (ap);
4176 if (value != NULL)
4177 g_variant_unref (value);
4179 return value != NULL;
4182 /* Serialised data {{{1 */
4183 static GVariant *
4184 g_variant_deep_copy (GVariant *value)
4186 switch (g_variant_classify (value))
4188 case G_VARIANT_CLASS_MAYBE:
4189 case G_VARIANT_CLASS_ARRAY:
4190 case G_VARIANT_CLASS_TUPLE:
4191 case G_VARIANT_CLASS_DICT_ENTRY:
4192 case G_VARIANT_CLASS_VARIANT:
4194 GVariantBuilder builder;
4195 GVariantIter iter;
4196 GVariant *child;
4198 g_variant_builder_init (&builder, g_variant_get_type (value));
4199 g_variant_iter_init (&iter, value);
4201 while ((child = g_variant_iter_next_value (&iter)))
4203 g_variant_builder_add_value (&builder, g_variant_deep_copy (child));
4204 g_variant_unref (child);
4207 return g_variant_builder_end (&builder);
4210 case G_VARIANT_CLASS_BOOLEAN:
4211 return g_variant_new_boolean (g_variant_get_boolean (value));
4213 case G_VARIANT_CLASS_BYTE:
4214 return g_variant_new_byte (g_variant_get_byte (value));
4216 case G_VARIANT_CLASS_INT16:
4217 return g_variant_new_int16 (g_variant_get_int16 (value));
4219 case G_VARIANT_CLASS_UINT16:
4220 return g_variant_new_uint16 (g_variant_get_uint16 (value));
4222 case G_VARIANT_CLASS_INT32:
4223 return g_variant_new_int32 (g_variant_get_int32 (value));
4225 case G_VARIANT_CLASS_UINT32:
4226 return g_variant_new_uint32 (g_variant_get_uint32 (value));
4228 case G_VARIANT_CLASS_INT64:
4229 return g_variant_new_int64 (g_variant_get_int64 (value));
4231 case G_VARIANT_CLASS_UINT64:
4232 return g_variant_new_uint64 (g_variant_get_uint64 (value));
4234 case G_VARIANT_CLASS_HANDLE:
4235 return g_variant_new_handle (g_variant_get_handle (value));
4237 case G_VARIANT_CLASS_DOUBLE:
4238 return g_variant_new_double (g_variant_get_double (value));
4240 case G_VARIANT_CLASS_STRING:
4241 return g_variant_new_string (g_variant_get_string (value, NULL));
4243 case G_VARIANT_CLASS_OBJECT_PATH:
4244 return g_variant_new_object_path (g_variant_get_string (value, NULL));
4246 case G_VARIANT_CLASS_SIGNATURE:
4247 return g_variant_new_signature (g_variant_get_string (value, NULL));
4250 g_assert_not_reached ();
4254 * g_variant_get_normal_form:
4255 * @value: a #GVariant
4256 * @returns: a trusted #GVariant
4258 * Gets a #GVariant instance that has the same value as @value and is
4259 * trusted to be in normal form.
4261 * If @value is already trusted to be in normal form then a new
4262 * reference to @value is returned.
4264 * If @value is not already trusted, then it is scanned to check if it
4265 * is in normal form. If it is found to be in normal form then it is
4266 * marked as trusted and a new reference to it is returned.
4268 * If @value is found not to be in normal form then a new trusted
4269 * #GVariant is created with the same value as @value.
4271 * It makes sense to call this function if you've received #GVariant
4272 * data from untrusted sources and you want to ensure your serialised
4273 * output is definitely in normal form.
4275 * Since: 2.24
4277 GVariant *
4278 g_variant_get_normal_form (GVariant *value)
4280 GVariant *trusted;
4282 if (g_variant_is_normal_form (value))
4283 return g_variant_ref (value);
4285 trusted = g_variant_deep_copy (value);
4286 g_assert (g_variant_is_trusted (trusted));
4288 return g_variant_ref_sink (trusted);
4292 * g_variant_byteswap:
4293 * @value: a #GVariant
4294 * @returns: the byteswapped form of @value
4296 * Performs a byteswapping operation on the contents of @value. The
4297 * result is that all multi-byte numeric data contained in @value is
4298 * byteswapped. That includes 16, 32, and 64bit signed and unsigned
4299 * integers as well as file handles and double precision floating point
4300 * values.
4302 * This function is an identity mapping on any value that does not
4303 * contain multi-byte numeric data. That include strings, booleans,
4304 * bytes and containers containing only these things (recursively).
4306 * The returned value is always in normal form and is marked as trusted.
4308 * Since: 2.24
4310 GVariant *
4311 g_variant_byteswap (GVariant *value)
4313 GVariantSerialised serialised;
4314 GVariant *trusted;
4315 GBuffer *buffer;
4316 GVariant *new;
4318 trusted = g_variant_get_normal_form (value);
4319 serialised.type_info = g_variant_get_type_info (trusted);
4320 serialised.size = g_variant_get_size (trusted);
4321 serialised.data = g_malloc (serialised.size);
4322 g_variant_store (trusted, serialised.data);
4323 g_variant_unref (trusted);
4325 g_variant_serialised_byteswap (serialised);
4327 buffer = g_buffer_new_take_data (serialised.data, serialised.size);
4328 new = g_variant_new_from_buffer (g_variant_get_type (value), buffer, TRUE);
4329 g_buffer_unref (buffer);
4331 return g_variant_ref_sink (new);
4335 * g_variant_new_from_data:
4336 * @type: a definite #GVariantType
4337 * @data: the serialised data
4338 * @size: the size of @data
4339 * @trusted: %TRUE if @data is definitely in normal form
4340 * @notify: function to call when @data is no longer needed
4341 * @user_data: data for @notify
4342 * @returns: a new floating #GVariant of type @type
4344 * Creates a new #GVariant instance from serialised data.
4346 * @type is the type of #GVariant instance that will be constructed.
4347 * The interpretation of @data depends on knowing the type.
4349 * @data is not modified by this function and must remain valid with an
4350 * unchanging value until such a time as @notify is called with
4351 * @user_data. If the contents of @data change before that time then
4352 * the result is undefined.
4354 * If @data is trusted to be serialised data in normal form then
4355 * @trusted should be %TRUE. This applies to serialised data created
4356 * within this process or read from a trusted location on the disk (such
4357 * as a file installed in /usr/lib alongside your application). You
4358 * should set trusted to %FALSE if @data is read from the network, a
4359 * file in the user's home directory, etc.
4361 * @notify will be called with @user_data when @data is no longer
4362 * needed. The exact time of this call is unspecified and might even be
4363 * before this function returns.
4365 * Since: 2.24
4367 GVariant *
4368 g_variant_new_from_data (const GVariantType *type,
4369 gconstpointer data,
4370 gsize size,
4371 gboolean trusted,
4372 GDestroyNotify notify,
4373 gpointer user_data)
4375 GVariant *value;
4376 GBuffer *buffer;
4378 g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
4379 g_return_val_if_fail (data != NULL || size == 0, NULL);
4381 if (notify)
4382 buffer = g_buffer_new_from_pointer (data, size, notify, user_data);
4383 else
4384 buffer = g_buffer_new_from_static_data (data, size);
4386 value = g_variant_new_from_buffer (type, buffer, trusted);
4387 g_buffer_unref (buffer);
4389 return value;
4392 /* Epilogue {{{1 */
4393 #define __G_VARIANT_C__
4394 #include "galiasdef.c"
4396 /* vim:set foldmethod=marker: */