Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / gvarianttype.c
1 /*
2  * Copyright © 2007, 2008 Ryan Lortie
3  * Copyright © 2009, 2010 Codethink Limited
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Author: Ryan Lortie <desrt@desrt.ca>
21  */
22
23 #include "config.h"
24
25 #include "gvarianttype.h"
26
27 #include <glib/gtestutils.h>
28 #include <glib/gstrfuncs.h>
29 #include <glib/gvariant-internal.h>
30
31 #include <string.h>
32
33
34 /**
35  * SECTION:gvarianttype
36  * @title: GVariantType
37  * @short_description: introduction to the GVariant type system
38  * @see_also: #GVariantType, #GVariant
39  *
40  * This section introduces the GVariant type system. It is based, in
41  * large part, on the D-Bus type system, with two major changes and
42  * some minor lifting of restrictions. The
43  * [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html),
44  * therefore, provides a significant amount of
45  * information that is useful when working with GVariant.
46  *
47  * The first major change with respect to the D-Bus type system is the
48  * introduction of maybe (or "nullable") types.  Any type in GVariant can be
49  * converted to a maybe type, in which case, "nothing" (or "null") becomes a
50  * valid value.  Maybe types have been added by introducing the
51  * character "m" to type strings.
52  *
53  * The second major change is that the GVariant type system supports the
54  * concept of "indefinite types" -- types that are less specific than
55  * the normal types found in D-Bus.  For example, it is possible to speak
56  * of "an array of any type" in GVariant, where the D-Bus type system
57  * would require you to speak of "an array of integers" or "an array of
58  * strings".  Indefinite types have been added by introducing the
59  * characters "*", "?" and "r" to type strings.
60  *
61  * Finally, all arbitrary restrictions relating to the complexity of
62  * types are lifted along with the restriction that dictionary entries
63  * may only appear nested inside of arrays.
64  *
65  * Just as in D-Bus, GVariant types are described with strings ("type
66  * strings").  Subject to the differences mentioned above, these strings
67  * are of the same form as those found in D-Bus.  Note, however: D-Bus
68  * always works in terms of messages and therefore individual type
69  * strings appear nowhere in its interface.  Instead, "signatures"
70  * are a concatenation of the strings of the type of each argument in a
71  * message.  GVariant deals with single values directly so GVariant type
72  * strings always describe the type of exactly one value.  This means
73  * that a D-Bus signature string is generally not a valid GVariant type
74  * string -- except in the case that it is the signature of a message
75  * containing exactly one argument.
76  *
77  * An indefinite type is similar in spirit to what may be called an
78  * abstract type in other type systems.  No value can exist that has an
79  * indefinite type as its type, but values can exist that have types
80  * that are subtypes of indefinite types.  That is to say,
81  * g_variant_get_type() will never return an indefinite type, but
82  * calling g_variant_is_of_type() with an indefinite type may return
83  * %TRUE.  For example, you cannot have a value that represents "an
84  * array of no particular type", but you can have an "array of integers"
85  * which certainly matches the type of "an array of no particular type",
86  * since "array of integers" is a subtype of "array of no particular
87  * type".
88  *
89  * This is similar to how instances of abstract classes may not
90  * directly exist in other type systems, but instances of their
91  * non-abstract subtypes may.  For example, in GTK, no object that has
92  * the type of #GtkBin can exist (since #GtkBin is an abstract class),
93  * but a #GtkWindow can certainly be instantiated, and you would say
94  * that the #GtkWindow is a #GtkBin (since #GtkWindow is a subclass of
95  * #GtkBin).
96  *
97  * ## GVariant Type Strings
98  *
99  * A GVariant type string can be any of the following:
100  *
101  * - any basic type string (listed below)
102  *
103  * - "v", "r" or "*"
104  *
105  * - one of the characters 'a' or 'm', followed by another type string
106  *
107  * - the character '(', followed by a concatenation of zero or more other
108  *   type strings, followed by the character ')'
109  *
110  * - the character '{', followed by a basic type string (see below),
111  *   followed by another type string, followed by the character '}'
112  *
113  * A basic type string describes a basic type (as per
114  * g_variant_type_is_basic()) and is always a single character in length.
115  * The valid basic type strings are "b", "y", "n", "q", "i", "u", "x", "t",
116  * "h", "d", "s", "o", "g" and "?".
117  *
118  * The above definition is recursive to arbitrary depth. "aaaaai" and
119  * "(ui(nq((y)))s)" are both valid type strings, as is
120  * "a(aa(ui)(qna{ya(yd)}))". In order to not hit memory limits, #GVariant
121  * imposes a limit on recursion depth of 65 nested containers. This is the
122  * limit in the D-Bus specification (64) plus one to allow a #GDBusMessage to
123  * be nested in a top-level tuple.
124  *
125  * The meaning of each of the characters is as follows:
126  * - `b`: the type string of %G_VARIANT_TYPE_BOOLEAN; a boolean value.
127  * - `y`: the type string of %G_VARIANT_TYPE_BYTE; a byte.
128  * - `n`: the type string of %G_VARIANT_TYPE_INT16; a signed 16 bit integer.
129  * - `q`: the type string of %G_VARIANT_TYPE_UINT16; an unsigned 16 bit integer.
130  * - `i`: the type string of %G_VARIANT_TYPE_INT32; a signed 32 bit integer.
131  * - `u`: the type string of %G_VARIANT_TYPE_UINT32; an unsigned 32 bit integer.
132  * - `x`: the type string of %G_VARIANT_TYPE_INT64; a signed 64 bit integer.
133  * - `t`: the type string of %G_VARIANT_TYPE_UINT64; an unsigned 64 bit integer.
134  * - `h`: the type string of %G_VARIANT_TYPE_HANDLE; a signed 32 bit value
135  *   that, by convention, is used as an index into an array of file
136  *   descriptors that are sent alongside a D-Bus message.
137  * - `d`: the type string of %G_VARIANT_TYPE_DOUBLE; a double precision
138  *   floating point value.
139  * - `s`: the type string of %G_VARIANT_TYPE_STRING; a string.
140  * - `o`: the type string of %G_VARIANT_TYPE_OBJECT_PATH; a string in the form
141  *   of a D-Bus object path.
142  * - `g`: the type string of %G_VARIANT_TYPE_SIGNATURE; a string in the form of
143  *   a D-Bus type signature.
144  * - `?`: the type string of %G_VARIANT_TYPE_BASIC; an indefinite type that
145  *   is a supertype of any of the basic types.
146  * - `v`: the type string of %G_VARIANT_TYPE_VARIANT; a container type that
147  *   contain any other type of value.
148  * - `a`: used as a prefix on another type string to mean an array of that
149  *   type; the type string "ai", for example, is the type of an array of
150  *   signed 32-bit integers.
151  * - `m`: used as a prefix on another type string to mean a "maybe", or
152  *   "nullable", version of that type; the type string "ms", for example,
153  *   is the type of a value that maybe contains a string, or maybe contains
154  *   nothing.
155  * - `()`: used to enclose zero or more other concatenated type strings to
156  *   create a tuple type; the type string "(is)", for example, is the type of
157  *   a pair of an integer and a string.
158  * - `r`: the type string of %G_VARIANT_TYPE_TUPLE; an indefinite type that is
159  *   a supertype of any tuple type, regardless of the number of items.
160  * - `{}`: used to enclose a basic type string concatenated with another type
161  *   string to create a dictionary entry type, which usually appears inside of
162  *   an array to form a dictionary; the type string "a{sd}", for example, is
163  *   the type of a dictionary that maps strings to double precision floating
164  *   point values.
165  *
166  *   The first type (the basic type) is the key type and the second type is
167  *   the value type. The reason that the first type is restricted to being a
168  *   basic type is so that it can easily be hashed.
169  * - `*`: the type string of %G_VARIANT_TYPE_ANY; the indefinite type that is
170  *   a supertype of all types.  Note that, as with all type strings, this
171  *   character represents exactly one type. It cannot be used inside of tuples
172  *   to mean "any number of items".
173  *
174  * Any type string of a container that contains an indefinite type is,
175  * itself, an indefinite type. For example, the type string "a*"
176  * (corresponding to %G_VARIANT_TYPE_ARRAY) is an indefinite type
177  * that is a supertype of every array type. "(*s)" is a supertype
178  * of all tuples that contain exactly two items where the second
179  * item is a string.
180  *
181  * "a{?*}" is an indefinite type that is a supertype of all arrays
182  * containing dictionary entries where the key is any basic type and
183  * the value is any type at all.  This is, by definition, a dictionary,
184  * so this type string corresponds to %G_VARIANT_TYPE_DICTIONARY. Note
185  * that, due to the restriction that the key of a dictionary entry must
186  * be a basic type, "{**}" is not a valid type string.
187  */
188
189
190 static gboolean
191 g_variant_type_check (const GVariantType *type)
192 {
193   if (type == NULL)
194     return FALSE;
195
196 #if 0
197   return g_variant_type_string_scan ((const gchar *) type, NULL, NULL);
198 #else
199   return TRUE;
200 #endif
201 }
202
203 static gboolean
204 variant_type_string_scan_internal (const gchar  *string,
205                                    const gchar  *limit,
206                                    const gchar **endptr,
207                                    gsize        *depth,
208                                    gsize         depth_limit)
209 {
210   gsize max_depth = 0, child_depth;
211
212   g_return_val_if_fail (string != NULL, FALSE);
213
214   if (string == limit || *string == '\0')
215     return FALSE;
216
217   switch (*string++)
218     {
219     case '(':
220       while (string == limit || *string != ')')
221         {
222           if (depth_limit == 0 ||
223               !variant_type_string_scan_internal (string, limit, &string,
224                                                   &child_depth,
225                                                   depth_limit - 1))
226             return FALSE;
227
228           max_depth = MAX (max_depth, child_depth + 1);
229         }
230
231       string++;
232       break;
233
234     case '{':
235       if (depth_limit == 0 ||
236           string == limit || *string == '\0' ||                                  /* { */
237           !strchr ("bynqihuxtdsog?", *string++) ||                               /* key */
238           !variant_type_string_scan_internal (string, limit, &string,
239                                               &child_depth, depth_limit - 1) ||  /* value */
240           string == limit || *string++ != '}')                                   /* } */
241         return FALSE;
242
243       max_depth = MAX (max_depth, child_depth + 1);
244       break;
245
246     case 'm': case 'a':
247       if (depth_limit == 0 ||
248           !variant_type_string_scan_internal (string, limit, &string,
249                                               &child_depth, depth_limit - 1))
250         return FALSE;
251
252       max_depth = MAX (max_depth, child_depth + 1);
253       break;
254
255     case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
256     case 'x': case 't': case 'd': case 's': case 'o': case 'g':
257     case 'v': case 'r': case '*': case '?': case 'h':
258       max_depth = MAX (max_depth, 1);
259       break;
260
261     default:
262       return FALSE;
263     }
264
265   if (endptr != NULL)
266     *endptr = string;
267   if (depth != NULL)
268     *depth = max_depth;
269
270   return TRUE;
271 }
272
273 /**
274  * g_variant_type_string_scan:
275  * @string: a pointer to any string
276  * @limit: (nullable): the end of @string, or %NULL
277  * @endptr: (out) (optional): location to store the end pointer, or %NULL
278  *
279  * Scan for a single complete and valid GVariant type string in @string.
280  * The memory pointed to by @limit (or bytes beyond it) is never
281  * accessed.
282  *
283  * If a valid type string is found, @endptr is updated to point to the
284  * first character past the end of the string that was found and %TRUE
285  * is returned.
286  *
287  * If there is no valid type string starting at @string, or if the type
288  * string does not end before @limit then %FALSE is returned.
289  *
290  * For the simple case of checking if a string is a valid type string,
291  * see g_variant_type_string_is_valid().
292  *
293  * Returns: %TRUE if a valid type string was found
294  *
295  * Since: 2.24
296  **/
297 gboolean
298 g_variant_type_string_scan (const gchar  *string,
299                             const gchar  *limit,
300                             const gchar **endptr)
301 {
302   return variant_type_string_scan_internal (string, limit, endptr, NULL,
303                                             G_VARIANT_MAX_RECURSION_DEPTH);
304 }
305
306 /* < private >
307  * g_variant_type_string_get_depth_:
308  * @type_string: a pointer to any string
309  *
310  * Get the maximum depth of the nested types in @type_string. A basic type will
311  * return depth 1, and a container type will return a greater value. The depth
312  * of a tuple is 1 plus the depth of its deepest child type.
313  *
314  * If @type_string is not a valid #GVariant type string, 0 will be returned.
315  *
316  * Returns: depth of @type_string, or 0 on error
317  * Since: 2.60
318  */
319 gsize
320 g_variant_type_string_get_depth_ (const gchar *type_string)
321 {
322   const gchar *endptr;
323   gsize depth = 0;
324
325   g_return_val_if_fail (type_string != NULL, 0);
326
327   if (!variant_type_string_scan_internal (type_string, NULL, &endptr, &depth,
328                                           G_VARIANT_MAX_RECURSION_DEPTH) ||
329       *endptr != '\0')
330     return 0;
331
332   return depth;
333 }
334
335 /**
336  * g_variant_type_string_is_valid:
337  * @type_string: a pointer to any string
338  *
339  * Checks if @type_string is a valid GVariant type string.  This call is
340  * equivalent to calling g_variant_type_string_scan() and confirming
341  * that the following character is a nul terminator.
342  *
343  * Returns: %TRUE if @type_string is exactly one valid type string
344  *
345  * Since 2.24
346  **/
347 gboolean
348 g_variant_type_string_is_valid (const gchar *type_string)
349 {
350   const gchar *endptr;
351
352   g_return_val_if_fail (type_string != NULL, FALSE);
353
354   if (!g_variant_type_string_scan (type_string, NULL, &endptr))
355     return FALSE;
356
357   return *endptr == '\0';
358 }
359
360 /**
361  * g_variant_type_free:
362  * @type: (nullable): a #GVariantType, or %NULL
363  *
364  * Frees a #GVariantType that was allocated with
365  * g_variant_type_copy(), g_variant_type_new() or one of the container
366  * type constructor functions.
367  *
368  * In the case that @type is %NULL, this function does nothing.
369  *
370  * Since 2.24
371  **/
372 void
373 g_variant_type_free (GVariantType *type)
374 {
375   g_return_if_fail (type == NULL || g_variant_type_check (type));
376
377   g_free (type);
378 }
379
380 /**
381  * g_variant_type_copy:
382  * @type: a #GVariantType
383  *
384  * Makes a copy of a #GVariantType.  It is appropriate to call
385  * g_variant_type_free() on the return value.  @type may not be %NULL.
386  *
387  * Returns: (transfer full): a new #GVariantType
388  *
389  * Since 2.24
390  **/
391 GVariantType *
392 g_variant_type_copy (const GVariantType *type)
393 {
394   gsize length;
395   gchar *new;
396
397   g_return_val_if_fail (g_variant_type_check (type), NULL);
398
399   length = g_variant_type_get_string_length (type);
400   new = g_malloc (length + 1);
401
402   memcpy (new, type, length);
403   new[length] = '\0';
404
405   return (GVariantType *) new;
406 }
407
408 /**
409  * g_variant_type_new:
410  * @type_string: a valid GVariant type string
411  *
412  * Creates a new #GVariantType corresponding to the type string given
413  * by @type_string.  It is appropriate to call g_variant_type_free() on
414  * the return value.
415  *
416  * It is a programmer error to call this function with an invalid type
417  * string.  Use g_variant_type_string_is_valid() if you are unsure.
418  *
419  * Returns: (transfer full): a new #GVariantType
420  *
421  * Since: 2.24
422  */
423 GVariantType *
424 g_variant_type_new (const gchar *type_string)
425 {
426   g_return_val_if_fail (type_string != NULL, NULL);
427
428   return g_variant_type_copy (G_VARIANT_TYPE (type_string));
429 }
430
431 /**
432  * g_variant_type_get_string_length:
433  * @type: a #GVariantType
434  *
435  * Returns the length of the type string corresponding to the given
436  * @type.  This function must be used to determine the valid extent of
437  * the memory region returned by g_variant_type_peek_string().
438  *
439  * Returns: the length of the corresponding type string
440  *
441  * Since 2.24
442  **/
443 gsize
444 g_variant_type_get_string_length (const GVariantType *type)
445 {
446   const gchar *type_string = (const gchar *) type;
447   gint brackets = 0;
448   gsize index = 0;
449
450   g_return_val_if_fail (g_variant_type_check (type), 0);
451
452   do
453     {
454       while (type_string[index] == 'a' || type_string[index] == 'm')
455         index++;
456
457       if (type_string[index] == '(' || type_string[index] == '{')
458         brackets++;
459
460       else if (type_string[index] == ')' || type_string[index] == '}')
461         brackets--;
462
463       index++;
464     }
465   while (brackets);
466
467   return index;
468 }
469
470 /*
471   This function is not introspectable, it returns something that
472   is not an array and neither a string
473 */
474 /**
475  * g_variant_type_peek_string: (skip)
476  * @type: a #GVariantType
477  *
478  * Returns the type string corresponding to the given @type.  The
479  * result is not nul-terminated; in order to determine its length you
480  * must call g_variant_type_get_string_length().
481  *
482  * To get a nul-terminated string, see g_variant_type_dup_string().
483  *
484  * Returns: the corresponding type string (not nul-terminated)
485  *
486  * Since 2.24
487  **/
488 const gchar *
489 g_variant_type_peek_string (const GVariantType *type)
490 {
491   g_return_val_if_fail (g_variant_type_check (type), NULL);
492
493   return (const gchar *) type;
494 }
495
496 /**
497  * g_variant_type_dup_string:
498  * @type: a #GVariantType
499  *
500  * Returns a newly-allocated copy of the type string corresponding to
501  * @type.  The returned string is nul-terminated.  It is appropriate to
502  * call g_free() on the return value.
503  *
504  * Returns: (transfer full): the corresponding type string
505  *
506  * Since 2.24
507  **/
508 gchar *
509 g_variant_type_dup_string (const GVariantType *type)
510 {
511   g_return_val_if_fail (g_variant_type_check (type), NULL);
512
513   return g_strndup (g_variant_type_peek_string (type),
514                     g_variant_type_get_string_length (type));
515 }
516
517 /**
518  * g_variant_type_is_definite:
519  * @type: a #GVariantType
520  *
521  * Determines if the given @type is definite (ie: not indefinite).
522  *
523  * A type is definite if its type string does not contain any indefinite
524  * type characters ('*', '?', or 'r').
525  *
526  * A #GVariant instance may not have an indefinite type, so calling
527  * this function on the result of g_variant_get_type() will always
528  * result in %TRUE being returned.  Calling this function on an
529  * indefinite type like %G_VARIANT_TYPE_ARRAY, however, will result in
530  * %FALSE being returned.
531  *
532  * Returns: %TRUE if @type is definite
533  *
534  * Since 2.24
535  **/
536 gboolean
537 g_variant_type_is_definite (const GVariantType *type)
538 {
539   const gchar *type_string;
540   gsize type_length;
541   gsize i;
542
543   g_return_val_if_fail (g_variant_type_check (type), FALSE);
544
545   type_length = g_variant_type_get_string_length (type);
546   type_string = g_variant_type_peek_string (type);
547
548   for (i = 0; i < type_length; i++)
549     if (type_string[i] == '*' ||
550         type_string[i] == '?' ||
551         type_string[i] == 'r')
552       return FALSE;
553
554   return TRUE;
555 }
556
557 /**
558  * g_variant_type_is_container:
559  * @type: a #GVariantType
560  *
561  * Determines if the given @type is a container type.
562  *
563  * Container types are any array, maybe, tuple, or dictionary
564  * entry types plus the variant type.
565  *
566  * This function returns %TRUE for any indefinite type for which every
567  * definite subtype is a container -- %G_VARIANT_TYPE_ARRAY, for
568  * example.
569  *
570  * Returns: %TRUE if @type is a container type
571  *
572  * Since 2.24
573  **/
574 gboolean
575 g_variant_type_is_container (const GVariantType *type)
576 {
577   gchar first_char;
578
579   g_return_val_if_fail (g_variant_type_check (type), FALSE);
580
581   first_char = g_variant_type_peek_string (type)[0];
582   switch (first_char)
583   {
584     case 'a':
585     case 'm':
586     case 'r':
587     case '(':
588     case '{':
589     case 'v':
590       return TRUE;
591
592     default:
593       return FALSE;
594   }
595 }
596
597 /**
598  * g_variant_type_is_basic:
599  * @type: a #GVariantType
600  *
601  * Determines if the given @type is a basic type.
602  *
603  * Basic types are booleans, bytes, integers, doubles, strings, object
604  * paths and signatures.
605  *
606  * Only a basic type may be used as the key of a dictionary entry.
607  *
608  * This function returns %FALSE for all indefinite types except
609  * %G_VARIANT_TYPE_BASIC.
610  *
611  * Returns: %TRUE if @type is a basic type
612  *
613  * Since 2.24
614  **/
615 gboolean
616 g_variant_type_is_basic (const GVariantType *type)
617 {
618   gchar first_char;
619
620   g_return_val_if_fail (g_variant_type_check (type), FALSE);
621
622   first_char = g_variant_type_peek_string (type)[0];
623   switch (first_char)
624   {
625     case 'b':
626     case 'y':
627     case 'n':
628     case 'q':
629     case 'i':
630     case 'h':
631     case 'u':
632     case 't':
633     case 'x':
634     case 'd':
635     case 's':
636     case 'o':
637     case 'g':
638     case '?':
639       return TRUE;
640
641     default:
642       return FALSE;
643   }
644 }
645
646 /**
647  * g_variant_type_is_maybe:
648  * @type: a #GVariantType
649  *
650  * Determines if the given @type is a maybe type.  This is true if the
651  * type string for @type starts with an 'm'.
652  *
653  * This function returns %TRUE for any indefinite type for which every
654  * definite subtype is a maybe type -- %G_VARIANT_TYPE_MAYBE, for
655  * example.
656  *
657  * Returns: %TRUE if @type is a maybe type
658  *
659  * Since 2.24
660  **/
661 gboolean
662 g_variant_type_is_maybe (const GVariantType *type)
663 {
664   g_return_val_if_fail (g_variant_type_check (type), FALSE);
665
666   return g_variant_type_peek_string (type)[0] == 'm';
667 }
668
669 /**
670  * g_variant_type_is_array:
671  * @type: a #GVariantType
672  *
673  * Determines if the given @type is an array type.  This is true if the
674  * type string for @type starts with an 'a'.
675  *
676  * This function returns %TRUE for any indefinite type for which every
677  * definite subtype is an array type -- %G_VARIANT_TYPE_ARRAY, for
678  * example.
679  *
680  * Returns: %TRUE if @type is an array type
681  *
682  * Since 2.24
683  **/
684 gboolean
685 g_variant_type_is_array (const GVariantType *type)
686 {
687   g_return_val_if_fail (g_variant_type_check (type), FALSE);
688
689   return g_variant_type_peek_string (type)[0] == 'a';
690 }
691
692 /**
693  * g_variant_type_is_tuple:
694  * @type: a #GVariantType
695  *
696  * Determines if the given @type is a tuple type.  This is true if the
697  * type string for @type starts with a '(' or if @type is
698  * %G_VARIANT_TYPE_TUPLE.
699  *
700  * This function returns %TRUE for any indefinite type for which every
701  * definite subtype is a tuple type -- %G_VARIANT_TYPE_TUPLE, for
702  * example.
703  *
704  * Returns: %TRUE if @type is a tuple type
705  *
706  * Since 2.24
707  **/
708 gboolean
709 g_variant_type_is_tuple (const GVariantType *type)
710 {
711   gchar type_char;
712
713   g_return_val_if_fail (g_variant_type_check (type), FALSE);
714
715   type_char = g_variant_type_peek_string (type)[0];
716   return type_char == 'r' || type_char == '(';
717 }
718
719 /**
720  * g_variant_type_is_dict_entry:
721  * @type: a #GVariantType
722  *
723  * Determines if the given @type is a dictionary entry type.  This is
724  * true if the type string for @type starts with a '{'.
725  *
726  * This function returns %TRUE for any indefinite type for which every
727  * definite subtype is a dictionary entry type --
728  * %G_VARIANT_TYPE_DICT_ENTRY, for example.
729  *
730  * Returns: %TRUE if @type is a dictionary entry type
731  *
732  * Since 2.24
733  **/
734 gboolean
735 g_variant_type_is_dict_entry (const GVariantType *type)
736 {
737   g_return_val_if_fail (g_variant_type_check (type), FALSE);
738
739   return g_variant_type_peek_string (type)[0] == '{';
740 }
741
742 /**
743  * g_variant_type_is_variant:
744  * @type: a #GVariantType
745  *
746  * Determines if the given @type is the variant type.
747  *
748  * Returns: %TRUE if @type is the variant type
749  *
750  * Since 2.24
751  **/
752 gboolean
753 g_variant_type_is_variant (const GVariantType *type)
754 {
755   g_return_val_if_fail (g_variant_type_check (type), FALSE);
756
757   return g_variant_type_peek_string (type)[0] == 'v';
758 }
759
760 /**
761  * g_variant_type_hash:
762  * @type: (type GVariantType): a #GVariantType
763  *
764  * Hashes @type.
765  *
766  * The argument type of @type is only #gconstpointer to allow use with
767  * #GHashTable without function pointer casting.  A valid
768  * #GVariantType must be provided.
769  *
770  * Returns: the hash value
771  *
772  * Since 2.24
773  **/
774 guint
775 g_variant_type_hash (gconstpointer type)
776 {
777   const gchar *type_string;
778   guint value = 0;
779   gsize length;
780   gsize i;
781
782   g_return_val_if_fail (g_variant_type_check (type), 0);
783
784   type_string = g_variant_type_peek_string (type);
785   length = g_variant_type_get_string_length (type);
786
787   for (i = 0; i < length; i++)
788     value = (value << 5) - value + type_string[i];
789
790   return value;
791 }
792
793 /**
794  * g_variant_type_equal:
795  * @type1: (type GVariantType): a #GVariantType
796  * @type2: (type GVariantType): a #GVariantType
797  *
798  * Compares @type1 and @type2 for equality.
799  *
800  * Only returns %TRUE if the types are exactly equal.  Even if one type
801  * is an indefinite type and the other is a subtype of it, %FALSE will
802  * be returned if they are not exactly equal.  If you want to check for
803  * subtypes, use g_variant_type_is_subtype_of().
804  *
805  * The argument types of @type1 and @type2 are only #gconstpointer to
806  * allow use with #GHashTable without function pointer casting.  For
807  * both arguments, a valid #GVariantType must be provided.
808  *
809  * Returns: %TRUE if @type1 and @type2 are exactly equal
810  *
811  * Since 2.24
812  **/
813 gboolean
814 g_variant_type_equal (gconstpointer type1,
815                       gconstpointer type2)
816 {
817   const gchar *string1, *string2;
818   gsize size1, size2;
819
820   g_return_val_if_fail (g_variant_type_check (type1), FALSE);
821   g_return_val_if_fail (g_variant_type_check (type2), FALSE);
822
823   if (type1 == type2)
824     return TRUE;
825
826   size1 = g_variant_type_get_string_length (type1);
827   size2 = g_variant_type_get_string_length (type2);
828
829   if (size1 != size2)
830     return FALSE;
831
832   string1 = g_variant_type_peek_string (type1);
833   string2 = g_variant_type_peek_string (type2);
834
835   return memcmp (string1, string2, size1) == 0;
836 }
837
838 /**
839  * g_variant_type_is_subtype_of:
840  * @type: a #GVariantType
841  * @supertype: a #GVariantType
842  *
843  * Checks if @type is a subtype of @supertype.
844  *
845  * This function returns %TRUE if @type is a subtype of @supertype.  All
846  * types are considered to be subtypes of themselves.  Aside from that,
847  * only indefinite types can have subtypes.
848  *
849  * Returns: %TRUE if @type is a subtype of @supertype
850  *
851  * Since 2.24
852  **/
853 gboolean
854 g_variant_type_is_subtype_of (const GVariantType *type,
855                               const GVariantType *supertype)
856 {
857   const gchar *supertype_string;
858   const gchar *supertype_end;
859   const gchar *type_string;
860
861   g_return_val_if_fail (g_variant_type_check (type), FALSE);
862   g_return_val_if_fail (g_variant_type_check (supertype), FALSE);
863
864   supertype_string = g_variant_type_peek_string (supertype);
865   type_string = g_variant_type_peek_string (type);
866
867   supertype_end = supertype_string +
868                   g_variant_type_get_string_length (supertype);
869
870   /* we know that type and supertype are both well-formed, so it's
871    * safe to treat this merely as a text processing problem.
872    */
873   while (supertype_string < supertype_end)
874     {
875       char supertype_char = *supertype_string++;
876
877       if (supertype_char == *type_string)
878         type_string++;
879
880       else if (*type_string == ')')
881         return FALSE;
882
883       else
884         {
885           const GVariantType *target_type = (GVariantType *) type_string;
886
887           switch (supertype_char)
888             {
889             case 'r':
890               if (!g_variant_type_is_tuple (target_type))
891                 return FALSE;
892               break;
893
894             case '*':
895               break;
896
897             case '?':
898               if (!g_variant_type_is_basic (target_type))
899                 return FALSE;
900               break;
901
902             default:
903               return FALSE;
904             }
905
906           type_string += g_variant_type_get_string_length (target_type);
907         }
908     }
909
910   return TRUE;
911 }
912
913 /**
914  * g_variant_type_element:
915  * @type: an array or maybe #GVariantType
916  *
917  * Determines the element type of an array or maybe type.
918  *
919  * This function may only be used with array or maybe types.
920  *
921  * Returns: (transfer none): the element type of @type
922  *
923  * Since 2.24
924  **/
925 const GVariantType *
926 g_variant_type_element (const GVariantType *type)
927 {
928   const gchar *type_string;
929
930   g_return_val_if_fail (g_variant_type_check (type), NULL);
931
932   type_string = g_variant_type_peek_string (type);
933
934   g_assert (type_string[0] == 'a' || type_string[0] == 'm');
935
936   return (const GVariantType *) &type_string[1];
937 }
938
939 /**
940  * g_variant_type_first:
941  * @type: a tuple or dictionary entry #GVariantType
942  *
943  * Determines the first item type of a tuple or dictionary entry
944  * type.
945  *
946  * This function may only be used with tuple or dictionary entry types,
947  * but must not be used with the generic tuple type
948  * %G_VARIANT_TYPE_TUPLE.
949  *
950  * In the case of a dictionary entry type, this returns the type of
951  * the key.
952  *
953  * %NULL is returned in case of @type being %G_VARIANT_TYPE_UNIT.
954  *
955  * This call, together with g_variant_type_next() provides an iterator
956  * interface over tuple and dictionary entry types.
957  *
958  * Returns: (transfer none): the first item type of @type, or %NULL
959  *
960  * Since 2.24
961  **/
962 const GVariantType *
963 g_variant_type_first (const GVariantType *type)
964 {
965   const gchar *type_string;
966
967   g_return_val_if_fail (g_variant_type_check (type), NULL);
968
969   type_string = g_variant_type_peek_string (type);
970   g_assert (type_string[0] == '(' || type_string[0] == '{');
971
972   if (type_string[1] == ')')
973     return NULL;
974
975   return (const GVariantType *) &type_string[1];
976 }
977
978 /**
979  * g_variant_type_next:
980  * @type: a #GVariantType from a previous call
981  *
982  * Determines the next item type of a tuple or dictionary entry
983  * type.
984  *
985  * @type must be the result of a previous call to
986  * g_variant_type_first() or g_variant_type_next().
987  *
988  * If called on the key type of a dictionary entry then this call
989  * returns the value type.  If called on the value type of a dictionary
990  * entry then this call returns %NULL.
991  *
992  * For tuples, %NULL is returned when @type is the last item in a tuple.
993  *
994  * Returns: (transfer none): the next #GVariantType after @type, or %NULL
995  *
996  * Since 2.24
997  **/
998 const GVariantType *
999 g_variant_type_next (const GVariantType *type)
1000 {
1001   const gchar *type_string;
1002
1003   g_return_val_if_fail (g_variant_type_check (type), NULL);
1004
1005   type_string = g_variant_type_peek_string (type);
1006   type_string += g_variant_type_get_string_length (type);
1007
1008   if (*type_string == ')' || *type_string == '}')
1009     return NULL;
1010
1011   return (const GVariantType *) type_string;
1012 }
1013
1014 /**
1015  * g_variant_type_n_items:
1016  * @type: a tuple or dictionary entry #GVariantType
1017  *
1018  * Determines the number of items contained in a tuple or
1019  * dictionary entry type.
1020  *
1021  * This function may only be used with tuple or dictionary entry types,
1022  * but must not be used with the generic tuple type
1023  * %G_VARIANT_TYPE_TUPLE.
1024  *
1025  * In the case of a dictionary entry type, this function will always
1026  * return 2.
1027  *
1028  * Returns: the number of items in @type
1029  *
1030  * Since 2.24
1031  **/
1032 gsize
1033 g_variant_type_n_items (const GVariantType *type)
1034 {
1035   gsize count = 0;
1036
1037   g_return_val_if_fail (g_variant_type_check (type), 0);
1038
1039   for (type = g_variant_type_first (type);
1040        type;
1041        type = g_variant_type_next (type))
1042     count++;
1043
1044   return count;
1045 }
1046
1047 /**
1048  * g_variant_type_key:
1049  * @type: a dictionary entry #GVariantType
1050  *
1051  * Determines the key type of a dictionary entry type.
1052  *
1053  * This function may only be used with a dictionary entry type.  Other
1054  * than the additional restriction, this call is equivalent to
1055  * g_variant_type_first().
1056  *
1057  * Returns: (transfer none): the key type of the dictionary entry
1058  *
1059  * Since 2.24
1060  **/
1061 const GVariantType *
1062 g_variant_type_key (const GVariantType *type)
1063 {
1064   const gchar *type_string;
1065
1066   g_return_val_if_fail (g_variant_type_check (type), NULL);
1067
1068   type_string = g_variant_type_peek_string (type);
1069   g_assert (type_string[0] == '{');
1070
1071   return (const GVariantType *) &type_string[1];
1072 }
1073
1074 /**
1075  * g_variant_type_value:
1076  * @type: a dictionary entry #GVariantType
1077  *
1078  * Determines the value type of a dictionary entry type.
1079  *
1080  * This function may only be used with a dictionary entry type.
1081  *
1082  * Returns: (transfer none): the value type of the dictionary entry
1083  *
1084  * Since 2.24
1085  **/
1086 const GVariantType *
1087 g_variant_type_value (const GVariantType *type)
1088 {
1089 #ifndef G_DISABLE_ASSERT
1090   const gchar *type_string;
1091 #endif
1092
1093   g_return_val_if_fail (g_variant_type_check (type), NULL);
1094
1095 #ifndef G_DISABLE_ASSERT
1096   type_string = g_variant_type_peek_string (type);
1097   g_assert (type_string[0] == '{');
1098 #endif
1099
1100   return g_variant_type_next (g_variant_type_key (type));
1101 }
1102
1103 /**
1104  * g_variant_type_new_tuple:
1105  * @items: (array length=length): an array of #GVariantTypes, one for each item
1106  * @length: the length of @items, or -1
1107  *
1108  * Constructs a new tuple type, from @items.
1109  *
1110  * @length is the number of items in @items, or -1 to indicate that
1111  * @items is %NULL-terminated.
1112  *
1113  * It is appropriate to call g_variant_type_free() on the return value.
1114  *
1115  * Returns: (transfer full): a new tuple #GVariantType
1116  *
1117  * Since 2.24
1118  **/
1119 static GVariantType *
1120 g_variant_type_new_tuple_slow (const GVariantType * const *items,
1121                                gint                        length)
1122 {
1123   /* the "slow" version is needed in case the static buffer of 1024
1124    * bytes is exceeded when running the normal version.  this will
1125    * happen only with very unusually large types, so it can be slow.
1126    */
1127   GString *string;
1128   gint i;
1129
1130   string = g_string_new ("(");
1131   for (i = 0; i < length; i++)
1132     {
1133       const GVariantType *type;
1134       gsize size;
1135
1136       g_return_val_if_fail (g_variant_type_check (items[i]), NULL);
1137
1138       type = items[i];
1139       size = g_variant_type_get_string_length (type);
1140       g_string_append_len (string, (const gchar *) type, size);
1141     }
1142   g_string_append_c (string, ')');
1143
1144   return (GVariantType *) g_string_free (string, FALSE);
1145 }
1146
1147 GVariantType *
1148 g_variant_type_new_tuple (const GVariantType * const *items,
1149                           gint                        length)
1150 {
1151   char buffer[1024];
1152   gsize offset;
1153   gsize i;
1154   gsize length_unsigned;
1155
1156   g_return_val_if_fail (length == 0 || items != NULL, NULL);
1157
1158   if (length < 0)
1159     for (length_unsigned = 0; items[length_unsigned] != NULL; length_unsigned++);
1160   else
1161     length_unsigned = (gsize) length;
1162
1163   offset = 0;
1164   buffer[offset++] = '(';
1165
1166   for (i = 0; i < length_unsigned; i++)
1167     {
1168       const GVariantType *type;
1169       gsize size;
1170
1171       g_return_val_if_fail (g_variant_type_check (items[i]), NULL);
1172
1173       type = items[i];
1174       size = g_variant_type_get_string_length (type);
1175
1176       if (offset + size >= sizeof buffer) /* leave room for ')' */
1177         return g_variant_type_new_tuple_slow (items, length_unsigned);
1178
1179       memcpy (&buffer[offset], type, size);
1180       offset += size;
1181     }
1182
1183   g_assert (offset < sizeof buffer);
1184   buffer[offset++] = ')';
1185
1186   return (GVariantType *) g_memdup2 (buffer, offset);
1187 }
1188
1189 /**
1190  * g_variant_type_new_array: (constructor)
1191  * @element: a #GVariantType
1192  *
1193  * Constructs the type corresponding to an array of elements of the
1194  * type @type.
1195  *
1196  * It is appropriate to call g_variant_type_free() on the return value.
1197  *
1198  * Returns: (transfer full): a new array #GVariantType
1199  *
1200  * Since 2.24
1201  **/
1202 GVariantType *
1203 g_variant_type_new_array (const GVariantType *element)
1204 {
1205   gsize size;
1206   gchar *new;
1207
1208   g_return_val_if_fail (g_variant_type_check (element), NULL);
1209
1210   size = g_variant_type_get_string_length (element);
1211   new = g_malloc (size + 1);
1212
1213   new[0] = 'a';
1214   memcpy (new + 1, element, size);
1215
1216   return (GVariantType *) new;
1217 }
1218
1219 /**
1220  * g_variant_type_new_maybe: (constructor)
1221  * @element: a #GVariantType
1222  *
1223  * Constructs the type corresponding to a maybe instance containing
1224  * type @type or Nothing.
1225  *
1226  * It is appropriate to call g_variant_type_free() on the return value.
1227  *
1228  * Returns: (transfer full): a new maybe #GVariantType
1229  *
1230  * Since 2.24
1231  **/
1232 GVariantType *
1233 g_variant_type_new_maybe (const GVariantType *element)
1234 {
1235   gsize size;
1236   gchar *new;
1237
1238   g_return_val_if_fail (g_variant_type_check (element), NULL);
1239
1240   size = g_variant_type_get_string_length (element);
1241   new = g_malloc (size + 1);
1242
1243   new[0] = 'm';
1244   memcpy (new + 1, element, size);
1245
1246   return (GVariantType *) new;
1247 }
1248
1249 /**
1250  * g_variant_type_new_dict_entry: (constructor)
1251  * @key: a basic #GVariantType
1252  * @value: a #GVariantType
1253  *
1254  * Constructs the type corresponding to a dictionary entry with a key
1255  * of type @key and a value of type @value.
1256  *
1257  * It is appropriate to call g_variant_type_free() on the return value.
1258  *
1259  * Returns: (transfer full): a new dictionary entry #GVariantType
1260  *
1261  * Since 2.24
1262  **/
1263 GVariantType *
1264 g_variant_type_new_dict_entry (const GVariantType *key,
1265                                const GVariantType *value)
1266 {
1267   gsize keysize, valsize;
1268   gchar *new;
1269
1270   g_return_val_if_fail (g_variant_type_check (key), NULL);
1271   g_return_val_if_fail (g_variant_type_check (value), NULL);
1272
1273   keysize = g_variant_type_get_string_length (key);
1274   valsize = g_variant_type_get_string_length (value);
1275
1276   new = g_malloc (1 + keysize + valsize + 1);
1277
1278   new[0] = '{';
1279   memcpy (new + 1, key, keysize);
1280   memcpy (new + 1 + keysize, value, valsize);
1281   new[1 + keysize + valsize] = '}';
1282
1283   return (GVariantType *) new;
1284 }
1285
1286 /* private */
1287 const GVariantType *
1288 g_variant_type_checked_ (const gchar *type_string)
1289 {
1290   g_return_val_if_fail (g_variant_type_string_is_valid (type_string), NULL);
1291   return (const GVariantType *) type_string;
1292 }