glib/
variant_type.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    borrow::{Borrow, Cow},
    fmt,
    hash::{Hash, Hasher},
    iter,
    marker::PhantomData,
    ops::Deref,
    ptr, slice,
    str::FromStr,
};

use crate::{ffi, gobject_ffi, prelude::*, translate::*, BoolError, Type};

// rustdoc-stripper-ignore-next
/// Describes `Variant` types.
///
/// The `Variant` type system (based on the D-Bus one) describes types with
/// "type strings". `VariantType` is an owned immutable type string (you can
/// think of it as a `Box<str>` statically guaranteed to be a valid type
/// string), `&VariantTy` is a borrowed one (like `&str`).
// rustdoc-stripper-ignore-next-stop
/// A type in the [type@GLib.Variant] type system.
///
/// This section introduces the [type@GLib.Variant] type system. It is based, in
/// large part, on the D-Bus type system, with two major changes and
/// some minor lifting of restrictions. The
/// [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html),
/// therefore, provides a significant amount of
/// information that is useful when working with [type@GLib.Variant].
///
/// The first major change with respect to the D-Bus type system is the
/// introduction of maybe (or ‘nullable’) types.  Any type in [type@GLib.Variant]
/// can be converted to a maybe type, in which case, `nothing` (or `null`)
/// becomes a valid value.  Maybe types have been added by introducing the
/// character `m` to type strings.
///
/// The second major change is that the [type@GLib.Variant] type system supports
/// the concept of ‘indefinite types’ — types that are less specific than
/// the normal types found in D-Bus.  For example, it is possible to speak
/// of ‘an array of any type’ in [type@GLib.Variant], where the D-Bus type system
/// would require you to speak of ‘an array of integers’ or ‘an array of
/// strings’.  Indefinite types have been added by introducing the
/// characters `*`, `?` and `r` to type strings.
///
/// Finally, all arbitrary restrictions relating to the complexity of
/// types are lifted along with the restriction that dictionary entries
/// may only appear nested inside of arrays.
///
/// Just as in D-Bus, [type@GLib.Variant] types are described with strings (‘type
/// strings’).  Subject to the differences mentioned above, these strings
/// are of the same form as those found in D-Bus.  Note, however: D-Bus
/// always works in terms of messages and therefore individual type
/// strings appear nowhere in its interface.  Instead, ‘signatures’
/// are a concatenation of the strings of the type of each argument in a
/// message.  [type@GLib.Variant] deals with single values directly so
/// [type@GLib.Variant] type strings always describe the type of exactly one
/// value.  This means that a D-Bus signature string is generally not a valid
/// [type@GLib.Variant] type string — except in the case that it is the signature
/// of a message containing exactly one argument.
///
/// An indefinite type is similar in spirit to what may be called an
/// abstract type in other type systems.  No value can exist that has an
/// indefinite type as its type, but values can exist that have types
/// that are subtypes of indefinite types.  That is to say,
/// [`Variant::type_()`][crate::Variant::type_()] will never return an indefinite type, but
/// calling [`Variant::is_of_type()`][crate::Variant::is_of_type()] with an indefinite type may return
/// true.  For example, you cannot have a value that represents ‘an
/// array of no particular type’, but you can have an ‘array of integers’
/// which certainly matches the type of ‘an array of no particular type’,
/// since ‘array of integers’ is a subtype of ‘array of no particular
/// type’.
///
/// This is similar to how instances of abstract classes may not
/// directly exist in other type systems, but instances of their
/// non-abstract subtypes may.  For example, in GTK, no object that has
/// the type of [`GtkWidget`](https://docs.gtk.org/gtk4/class.Widget.html) can
/// exist (since `GtkWidget` is an abstract class), but a [`GtkWindow`](https://docs.gtk.org/gtk4/class.Window.html)
/// can certainly be instantiated, and you would say that a `GtkWindow` is a
/// `GtkWidget` (since `GtkWindow` is a subclass of `GtkWidget`).
///
/// Two types may not be compared by value; use `GLib::VariantType::equal()`
/// or [`is_subtype_of()`][Self::is_subtype_of()]  May be copied using
/// `GLib::VariantType::copy()` and freed using `GLib::VariantType::free()`.
///
/// ## GVariant Type Strings
///
/// A [type@GLib.Variant] type string can be any of the following:
///
/// - any basic type string (listed below)
/// - `v`, `r` or `*`
/// - one of the characters `a` or `m`, followed by another type string
/// - the character `(`, followed by a concatenation of zero or more other
///   type strings, followed by the character `)`
/// - the character `{`, followed by a basic type string (see below),
///   followed by another type string, followed by the character `}`
///
/// A basic type string describes a basic type (as per
/// [`is_basic()`][Self::is_basic()]) and is always a single character in
/// length. The valid basic type strings are `b`, `y`, `n`, `q`, `i`, `u`, `x`,
/// `t`, `h`, `d`, `s`, `o`, `g` and `?`.
///
/// The above definition is recursive to arbitrary depth. `aaaaai` and
/// `(ui(nq((y)))s)` are both valid type strings, as is
/// `a(aa(ui)(qna{ya(yd)}))`. In order to not hit memory limits,
/// [type@GLib.Variant] imposes a limit on recursion depth of 65 nested
/// containers. This is the limit in the D-Bus specification (64) plus one to
/// allow a [`GDBusMessage`](../gio/class.DBusMessage.html) to be nested in
/// a top-level tuple.
///
/// The meaning of each of the characters is as follows:
///
/// - `b`: the type string of `G_VARIANT_TYPE_BOOLEAN`; a boolean value.
/// - `y`: the type string of `G_VARIANT_TYPE_BYTE`; a byte.
/// - `n`: the type string of `G_VARIANT_TYPE_INT16`; a signed 16 bit integer.
/// - `q`: the type string of `G_VARIANT_TYPE_UINT16`; an unsigned 16 bit integer.
/// - `i`: the type string of `G_VARIANT_TYPE_INT32`; a signed 32 bit integer.
/// - `u`: the type string of `G_VARIANT_TYPE_UINT32`; an unsigned 32 bit integer.
/// - `x`: the type string of `G_VARIANT_TYPE_INT64`; a signed 64 bit integer.
/// - `t`: the type string of `G_VARIANT_TYPE_UINT64`; an unsigned 64 bit integer.
/// - `h`: the type string of `G_VARIANT_TYPE_HANDLE`; a signed 32 bit value
///   that, by convention, is used as an index into an array of file
///   descriptors that are sent alongside a D-Bus message.
/// - `d`: the type string of `G_VARIANT_TYPE_DOUBLE`; a double precision
///   floating point value.
/// - `s`: the type string of `G_VARIANT_TYPE_STRING`; a string.
/// - `o`: the type string of `G_VARIANT_TYPE_OBJECT_PATH`; a string in the form
///   of a D-Bus object path.
/// - `g`: the type string of `G_VARIANT_TYPE_SIGNATURE`; a string in the form of
///   a D-Bus type signature.
/// - `?`: the type string of `G_VARIANT_TYPE_BASIC`; an indefinite type that
///   is a supertype of any of the basic types.
/// - `v`: the type string of `G_VARIANT_TYPE_VARIANT`; a container type that
///   contain any other type of value.
/// - `a`: used as a prefix on another type string to mean an array of that
///   type; the type string `ai`, for example, is the type of an array of
///   signed 32-bit integers.
/// - `m`: used as a prefix on another type string to mean a ‘maybe’, or
///   ‘nullable’, version of that type; the type string `ms`, for example,
///   is the type of a value that maybe contains a string, or maybe contains
///   nothing.
/// - `()`: used to enclose zero or more other concatenated type strings to
///   create a tuple type; the type string `(is)`, for example, is the type of
///   a pair of an integer and a string.
/// - `r`: the type string of `G_VARIANT_TYPE_TUPLE`; an indefinite type that is
///   a supertype of any tuple type, regardless of the number of items.
/// - `{}`: used to enclose a basic type string concatenated with another type
///   string to create a dictionary entry type, which usually appears inside of
///   an array to form a dictionary; the type string `a{sd}`, for example, is
///   the type of a dictionary that maps strings to double precision floating
///   point values.
///
///   The first type (the basic type) is the key type and the second type is
///   the value type. The reason that the first type is restricted to being a
///   basic type is so that it can easily be hashed.
/// - `*`: the type string of `G_VARIANT_TYPE_ANY`; the indefinite type that is
///   a supertype of all types.  Note that, as with all type strings, this
///   character represents exactly one type. It cannot be used inside of tuples
///   to mean ‘any number of items’.
///
/// Any type string of a container that contains an indefinite type is,
/// itself, an indefinite type. For example, the type string `a*`
/// (corresponding to `G_VARIANT_TYPE_ARRAY`) is an indefinite type
/// that is a supertype of every array type. `(*s)` is a supertype
/// of all tuples that contain exactly two items where the second
/// item is a string.
///
/// `a{?*}` is an indefinite type that is a supertype of all arrays
/// containing dictionary entries where the key is any basic type and
/// the value is any type at all.  This is, by definition, a dictionary,
/// so this type string corresponds to `G_VARIANT_TYPE_DICTIONARY`. Note
/// that, due to the restriction that the key of a dictionary entry must
/// be a basic type, `{**}` is not a valid type string.
#[doc(alias = "GVariantType")]
pub struct VariantType {
    // GVariantType* essentially is a char*, that always is valid UTF-8 but
    // isn't NUL-terminated.
    ptr: ptr::NonNull<ffi::GVariantType>,
    // We query the length on creation assuming it's cheap (because type strings
    // are short) and likely to happen anyway.
    len: usize,
}

impl VariantType {
    // rustdoc-stripper-ignore-next
    /// Tries to create a `VariantType` from a string slice.
    ///
    /// Returns `Ok` if the string is a valid type string, `Err` otherwise.
    // rustdoc-stripper-ignore-next-stop
    /// Creates a new [type@GLib.VariantType] corresponding to the type string given
    /// by @type_string.
    ///
    /// It is appropriate to call `GLib::VariantType::free()` on the return value.
    ///
    /// It is a programmer error to call this function with an invalid type
    /// string.  Use [`string_is_valid()`][Self::string_is_valid()] if you are unsure.
    /// ## `type_string`
    /// a valid [GVariant type string](./struct.VariantType.html#gvariant-type-strings)
    ///
    /// # Returns
    ///
    /// a new [type@GLib.VariantType]
    pub fn new(type_string: &str) -> Result<VariantType, BoolError> {
        VariantTy::new(type_string).map(ToOwned::to_owned)
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `VariantType` from a key and value type.
    // rustdoc-stripper-ignore-next-stop
    /// Constructs the type corresponding to a dictionary entry with a key
    /// of type @key and a value of type @value.
    ///
    /// It is appropriate to call `GLib::VariantType::free()` on the return value.
    /// ## `key`
    /// a basic type to use for the key
    /// ## `value`
    /// a type to use for the value
    ///
    /// # Returns
    ///
    /// a new dictionary entry type
    /// Since 2.24
    #[doc(alias = "g_variant_type_new_dict_entry")]
    pub fn new_dict_entry(key_type: &VariantTy, value_type: &VariantTy) -> VariantType {
        unsafe {
            from_glib_full(ffi::g_variant_type_new_dict_entry(
                key_type.to_glib_none().0,
                value_type.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `VariantType` from an array element type.
    // rustdoc-stripper-ignore-next-stop
    /// Constructs the type corresponding to an array of elements of the
    /// type @type_.
    ///
    /// It is appropriate to call [`first()`][Self::first()] on the return value.
    /// ## `element`
    /// an element type
    ///
    /// # Returns
    ///
    /// a new array type
    /// Since 2.24
    #[doc(alias = "g_variant_type_new_array")]
    pub fn new_array(elem_type: &VariantTy) -> VariantType {
        unsafe { from_glib_full(ffi::g_variant_type_new_array(elem_type.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `VariantType` from a maybe element type.
    // rustdoc-stripper-ignore-next-stop
    /// Constructs the type corresponding to a ‘maybe’ instance containing
    /// type @type_ or `Nothing`.
    ///
    /// It is appropriate to call `GLib::VariantType::free()` on the return value.
    /// ## `element`
    /// an element type
    ///
    /// # Returns
    ///
    /// a new ‘maybe’ type
    /// Since 2.24
    #[doc(alias = "g_variant_type_new_maybe")]
    pub fn new_maybe(child_type: &VariantTy) -> VariantType {
        unsafe { from_glib_full(ffi::g_variant_type_new_maybe(child_type.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a `VariantType` from a maybe element type.
    // rustdoc-stripper-ignore-next-stop
    /// Constructs a new tuple type, from @items.
    ///
    /// @length is the number of items in @items, or `-1` to indicate that
    /// @items is `NULL`-terminated.
    ///
    /// It is appropriate to call `GLib::VariantType::free()` on the return value.
    /// ## `items`
    /// an array of types, one for each item
    ///
    /// # Returns
    ///
    /// a new tuple type
    /// Since 2.24
    #[doc(alias = "g_variant_type_new_tuple")]
    pub fn new_tuple(items: impl IntoIterator<Item = impl AsRef<VariantTy>>) -> VariantType {
        let mut builder = crate::GStringBuilder::new("(");

        for ty in items {
            builder.append(ty.as_ref().as_str());
        }

        builder.append_c(')');

        VariantType::from_string(builder.into_string()).unwrap()
    }

    // rustdoc-stripper-ignore-next
    /// Tries to create a `VariantType` from an owned string.
    ///
    /// Returns `Ok` if the string is a valid type string, `Err` otherwise.
    pub fn from_string(type_string: impl Into<crate::GString>) -> Result<VariantType, BoolError> {
        let type_string = type_string.into();
        VariantTy::new(&type_string)?;

        let len = type_string.len();
        unsafe {
            let ptr = type_string.into_glib_ptr();

            Ok(VariantType {
                ptr: ptr::NonNull::new_unchecked(ptr as *mut ffi::GVariantType),
                len,
            })
        }
    }
}

unsafe impl Send for VariantType {}
unsafe impl Sync for VariantType {}

impl Drop for VariantType {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::g_variant_type_free(self.ptr.as_ptr()) }
    }
}

impl AsRef<VariantTy> for VariantType {
    #[inline]
    fn as_ref(&self) -> &VariantTy {
        self
    }
}

impl Borrow<VariantTy> for VariantType {
    #[inline]
    fn borrow(&self) -> &VariantTy {
        self
    }
}

impl Clone for VariantType {
    #[inline]
    fn clone(&self) -> VariantType {
        unsafe {
            VariantType {
                ptr: ptr::NonNull::new_unchecked(ffi::g_variant_type_copy(self.ptr.as_ptr())),
                len: self.len,
            }
        }
    }
}

impl Deref for VariantType {
    type Target = VariantTy;

    #[allow(clippy::cast_slice_from_raw_parts)]
    #[inline]
    fn deref(&self) -> &VariantTy {
        unsafe {
            &*(slice::from_raw_parts(self.ptr.as_ptr() as *const u8, self.len) as *const [u8]
                as *const VariantTy)
        }
    }
}

impl fmt::Debug for VariantType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <VariantTy as fmt::Debug>::fmt(self, f)
    }
}

impl fmt::Display for VariantType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for VariantType {
    type Err = BoolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

impl Hash for VariantType {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        <VariantTy as Hash>::hash(self, state)
    }
}

impl<'a> From<VariantType> for Cow<'a, VariantTy> {
    #[inline]
    fn from(ty: VariantType) -> Cow<'a, VariantTy> {
        Cow::Owned(ty)
    }
}

#[doc(hidden)]
impl IntoGlibPtr<*mut ffi::GVariantType> for VariantType {
    #[inline]
    unsafe fn into_glib_ptr(self) -> *mut ffi::GVariantType {
        std::mem::ManuallyDrop::new(self).to_glib_none().0
    }
}

#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *const ffi::GVariantType> for VariantType {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const ffi::GVariantType, Self> {
        Stash(self.ptr.as_ptr(), PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *const ffi::GVariantType {
        unsafe { ffi::g_variant_type_copy(self.ptr.as_ptr()) }
    }
}

#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *mut ffi::GVariantType> for VariantType {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut ffi::GVariantType, Self> {
        Stash(self.ptr.as_ptr(), PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut ffi::GVariantType {
        unsafe { ffi::g_variant_type_copy(self.ptr.as_ptr()) }
    }
}

#[doc(hidden)]
impl<'a> ToGlibPtrMut<'a, *mut ffi::GVariantType> for VariantType {
    type Storage = PhantomData<&'a mut Self>;

    #[inline]
    fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ffi::GVariantType, Self> {
        StashMut(self.ptr.as_ptr(), PhantomData)
    }
}

#[doc(hidden)]
impl FromGlibPtrNone<*const ffi::GVariantType> for VariantType {
    #[inline]
    unsafe fn from_glib_none(ptr: *const ffi::GVariantType) -> VariantType {
        VariantTy::from_ptr(ptr).to_owned()
    }
}

#[doc(hidden)]
impl FromGlibPtrFull<*const ffi::GVariantType> for VariantType {
    #[inline]
    unsafe fn from_glib_full(ptr: *const ffi::GVariantType) -> VariantType {
        // Don't assume ownership of a const pointer.
        // A transfer: full annotation on a `const GVariantType*` is likely a bug.
        VariantTy::from_ptr(ptr).to_owned()
    }
}

#[doc(hidden)]
impl FromGlibPtrFull<*mut ffi::GVariantType> for VariantType {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::GVariantType) -> VariantType {
        debug_assert!(!ptr.is_null());
        let len: usize = ffi::g_variant_type_get_string_length(ptr) as _;
        VariantType {
            ptr: ptr::NonNull::new_unchecked(ptr),
            len,
        }
    }
}

// rustdoc-stripper-ignore-next
/// Describes `Variant` types.
///
/// This is a borrowed counterpart of [`VariantType`](struct.VariantType.html).
/// Essentially it's a `str` statically guaranteed to be a valid type string.
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct VariantTy {
    inner: str,
}

impl VariantTy {
    // rustdoc-stripper-ignore-next
    /// `bool`.
    #[doc(alias = "G_VARIANT_TYPE_BOOLEAN")]
    pub const BOOLEAN: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_BOOLEAN) };

    // rustdoc-stripper-ignore-next
    /// `u8`.
    #[doc(alias = "G_VARIANT_TYPE_BYTE")]
    pub const BYTE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_BYTE) };

    // rustdoc-stripper-ignore-next
    /// `i16`.
    #[doc(alias = "G_VARIANT_TYPE_INT16")]
    pub const INT16: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_INT16) };

    // rustdoc-stripper-ignore-next
    /// `u16`.
    #[doc(alias = "G_VARIANT_TYPE_UINT16")]
    pub const UINT16: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_UINT16) };

    // rustdoc-stripper-ignore-next
    /// `i32`.
    #[doc(alias = "G_VARIANT_TYPE_INT32")]
    pub const INT32: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_INT32) };

    // rustdoc-stripper-ignore-next
    /// `u32`.
    #[doc(alias = "G_VARIANT_TYPE_UINT32")]
    pub const UINT32: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_UINT32) };

    // rustdoc-stripper-ignore-next
    /// `i64`.
    #[doc(alias = "G_VARIANT_TYPE_INT64")]
    pub const INT64: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_INT64) };

    // rustdoc-stripper-ignore-next
    /// `u64`.
    #[doc(alias = "G_VARIANT_TYPE_UINT64")]
    pub const UINT64: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_UINT64) };

    // rustdoc-stripper-ignore-next
    /// `f64`.
    #[doc(alias = "G_VARIANT_TYPE_DOUBLE")]
    pub const DOUBLE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_DOUBLE) };

    // rustdoc-stripper-ignore-next
    /// `&str`.
    #[doc(alias = "G_VARIANT_TYPE_STRING")]
    pub const STRING: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_STRING) };

    // rustdoc-stripper-ignore-next
    /// DBus object path.
    #[doc(alias = "G_VARIANT_TYPE_OBJECT_PATH")]
    pub const OBJECT_PATH: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_OBJECT_PATH) };

    // rustdoc-stripper-ignore-next
    /// Type signature.
    #[doc(alias = "G_VARIANT_TYPE_SIGNATURE")]
    pub const SIGNATURE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_SIGNATURE) };

    // rustdoc-stripper-ignore-next
    /// Variant.
    #[doc(alias = "G_VARIANT_TYPE_VARIANT")]
    pub const VARIANT: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_VARIANT) };

    // rustdoc-stripper-ignore-next
    /// Handle.
    #[doc(alias = "G_VARIANT_TYPE_HANDLE")]
    pub const HANDLE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_HANDLE) };

    // rustdoc-stripper-ignore-next
    /// Unit, i.e. `()`.
    #[doc(alias = "G_VARIANT_TYPE_UNIT")]
    pub const UNIT: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_UNIT) };

    // rustdoc-stripper-ignore-next
    /// An indefinite type that is a supertype of every type (including itself).
    #[doc(alias = "G_VARIANT_TYPE_ANY")]
    pub const ANY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_ANY) };

    // rustdoc-stripper-ignore-next
    /// Any basic type.
    #[doc(alias = "G_VARIANT_TYPE_BASIC")]
    pub const BASIC: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_BASIC) };

    // rustdoc-stripper-ignore-next
    /// Any maybe type, i.e. `Option<T>`.
    #[doc(alias = "G_VARIANT_TYPE_MAYBE")]
    pub const MAYBE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_MAYBE) };

    // rustdoc-stripper-ignore-next
    /// Any array type, i.e. `[T]`.
    #[doc(alias = "G_VARIANT_TYPE_ARRAY")]
    pub const ARRAY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_ARRAY) };

    // rustdoc-stripper-ignore-next
    /// Any tuple type, i.e. `(T)`, `(T, T)`, etc.
    #[doc(alias = "G_VARIANT_TYPE_TUPLE")]
    pub const TUPLE: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_TUPLE) };

    // rustdoc-stripper-ignore-next
    /// Any dict entry type, i.e. `DictEntry<K, V>`.
    #[doc(alias = "G_VARIANT_TYPE_DICT_ENTRY")]
    pub const DICT_ENTRY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_DICT_ENTRY) };

    // rustdoc-stripper-ignore-next
    /// Any dictionary type, i.e. `HashMap<K, V>`, `BTreeMap<K, V>`.
    #[doc(alias = "G_VARIANT_TYPE_DICTIONARY")]
    pub const DICTIONARY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_DICTIONARY) };

    // rustdoc-stripper-ignore-next
    /// String array, i.e. `[&str]`.
    #[doc(alias = "G_VARIANT_TYPE_STRING_ARRAY")]
    pub const STRING_ARRAY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_STRING_ARRAY) };

    // rustdoc-stripper-ignore-next
    /// Object path array, i.e. `[&str]`.
    #[doc(alias = "G_VARIANT_TYPE_OBJECT_PATH_ARRAY")]
    pub const OBJECT_PATH_ARRAY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_OBJECT_PATH_ARRAY) };

    // rustdoc-stripper-ignore-next
    /// Byte string, i.e. `[u8]`.
    #[doc(alias = "G_VARIANT_TYPE_BYTE_STRING")]
    pub const BYTE_STRING: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_BYTE_STRING) };

    // rustdoc-stripper-ignore-next
    /// Byte string array, i.e. `[[u8]]`.
    #[doc(alias = "G_VARIANT_TYPE_BYTE_STRING_ARRAY")]
    pub const BYTE_STRING_ARRAY: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_BYTE_STRING_ARRAY) };

    // rustdoc-stripper-ignore-next
    /// Variant dictionary, i.e. `HashMap<String, Variant>`, `BTreeMap<String, Variant>`, etc.
    #[doc(alias = "G_VARIANT_TYPE_VARDICT")]
    pub const VARDICT: &'static VariantTy =
        unsafe { VariantTy::from_str_unchecked(ffi::G_VARIANT_TYPE_VARDICT) };

    // rustdoc-stripper-ignore-next
    /// Tries to create a `&VariantTy` from a string slice.
    ///
    /// Returns `Ok` if the string is a valid type string, `Err` otherwise.
    pub fn new(type_string: &str) -> Result<&VariantTy, BoolError> {
        unsafe {
            let ptr = type_string.as_ptr();
            let limit = ptr.add(type_string.len());
            let mut end = ptr::null();

            let ok = from_glib(ffi::g_variant_type_string_scan(
                ptr as *const _,
                limit as *const _,
                &mut end,
            ));
            if ok && end as *const _ == limit {
                Ok(&*(type_string.as_bytes() as *const [u8] as *const VariantTy))
            } else {
                Err(bool_error!("Invalid type string: '{}'", type_string))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Converts a type string into `&VariantTy` without any checks.
    ///
    /// # Safety
    ///
    /// The caller is responsible for passing in only a valid variant type string.
    #[inline]
    pub const unsafe fn from_str_unchecked(type_string: &str) -> &VariantTy {
        std::mem::transmute::<&str, &VariantTy>(type_string)
    }

    // rustdoc-stripper-ignore-next
    /// Creates `&VariantTy` with a wildcard lifetime from a `GVariantType`
    /// pointer.
    #[doc(hidden)]
    #[allow(clippy::cast_slice_from_raw_parts)]
    #[inline]
    pub unsafe fn from_ptr<'a>(ptr: *const ffi::GVariantType) -> &'a VariantTy {
        debug_assert!(!ptr.is_null());
        let len: usize = ffi::g_variant_type_get_string_length(ptr) as _;
        debug_assert!(len > 0);
        &*(slice::from_raw_parts(ptr as *const u8, len) as *const [u8] as *const VariantTy)
    }

    // rustdoc-stripper-ignore-next
    /// Returns a `GVariantType` pointer.
    #[doc(hidden)]
    #[inline]
    pub fn as_ptr(&self) -> *const ffi::GVariantType {
        self.inner.as_ptr() as *const _
    }

    // rustdoc-stripper-ignore-next
    /// Converts to a string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.inner
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a definite type.
    #[doc(alias = "g_variant_type_is_definite")]
    pub fn is_definite(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_definite(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a container type.
    #[doc(alias = "g_variant_type_is_container")]
    pub fn is_container(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_container(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a basic type.
    #[doc(alias = "g_variant_type_is_basic")]
    pub fn is_basic(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_basic(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a maybe type.
    #[doc(alias = "g_variant_type_is_maybe")]
    pub fn is_maybe(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_maybe(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is an array type.
    #[doc(alias = "g_variant_type_is_array")]
    pub fn is_array(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_array(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a tuple type.
    #[doc(alias = "g_variant_type_is_tuple")]
    pub fn is_tuple(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_tuple(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a dict entry type.
    #[doc(alias = "g_variant_type_is_dict_entry")]
    pub fn is_dict_entry(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_dict_entry(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a variant.
    #[doc(alias = "g_variant_type_is_variant")]
    pub fn is_variant(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_type_is_variant(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Check if this variant type is a subtype of another.
    #[doc(alias = "g_variant_type_is_subtype_of")]
    pub fn is_subtype_of(&self, supertype: &Self) -> bool {
        unsafe {
            from_glib(ffi::g_variant_type_is_subtype_of(
                self.to_glib_none().0,
                supertype.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Return the element type of this variant type.
    ///
    /// # Panics
    ///
    /// This function panics if not called with an array or maybe type.
    #[doc(alias = "g_variant_type_element")]
    pub fn element(&self) -> &VariantTy {
        assert!(self.is_array() || self.is_maybe());

        unsafe {
            let element = ffi::g_variant_type_element(self.to_glib_none().0);
            Self::from_ptr(element)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Iterate over the types of this variant type.
    ///
    /// # Panics
    ///
    /// This function panics if not called with a tuple or dictionary entry type.
    pub fn tuple_types(&self) -> VariantTyIterator {
        VariantTyIterator::new(self).expect("VariantTy does not represent a tuple")
    }

    // rustdoc-stripper-ignore-next
    /// Return the first type of this variant type.
    ///
    /// # Panics
    ///
    /// This function panics if not called with a tuple or dictionary entry type.
    #[doc(alias = "g_variant_type_first")]
    pub fn first(&self) -> Option<&VariantTy> {
        assert!(self.as_str().starts_with('(') || self.as_str().starts_with('{'));

        unsafe {
            let first = ffi::g_variant_type_first(self.to_glib_none().0);
            if first.is_null() {
                None
            } else {
                Some(Self::from_ptr(first))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Return the next type of this variant type.
    #[doc(alias = "g_variant_type_next")]
    pub fn next(&self) -> Option<&VariantTy> {
        unsafe {
            let next = ffi::g_variant_type_next(self.to_glib_none().0);
            if next.is_null() {
                None
            } else {
                Some(Self::from_ptr(next))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Return the number of items in this variant type.
    #[doc(alias = "g_variant_type_n_items")]
    pub fn n_items(&self) -> usize {
        unsafe { ffi::g_variant_type_n_items(self.to_glib_none().0) }
    }

    // rustdoc-stripper-ignore-next
    /// Return the key type of this variant type.
    ///
    /// # Panics
    ///
    /// This function panics if not called with a dictionary entry type.
    #[doc(alias = "g_variant_type_key")]
    pub fn key(&self) -> &VariantTy {
        assert!(self.as_str().starts_with('{'));

        unsafe {
            let key = ffi::g_variant_type_key(self.to_glib_none().0);
            Self::from_ptr(key)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Return the value type of this variant type.
    ///
    /// # Panics
    ///
    /// This function panics if not called with a dictionary entry type.
    #[doc(alias = "g_variant_type_value")]
    pub fn value(&self) -> &VariantTy {
        assert!(self.as_str().starts_with('{'));

        unsafe {
            let value = ffi::g_variant_type_value(self.to_glib_none().0);
            Self::from_ptr(value)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Return this type as an array.
    pub(crate) fn as_array<'a>(&self) -> Cow<'a, VariantTy> {
        if self == VariantTy::STRING {
            Cow::Borrowed(VariantTy::STRING_ARRAY)
        } else if self == VariantTy::BYTE {
            Cow::Borrowed(VariantTy::BYTE_STRING)
        } else if self == VariantTy::BYTE_STRING {
            Cow::Borrowed(VariantTy::BYTE_STRING_ARRAY)
        } else if self == VariantTy::OBJECT_PATH {
            Cow::Borrowed(VariantTy::OBJECT_PATH_ARRAY)
        } else if self == VariantTy::DICT_ENTRY {
            Cow::Borrowed(VariantTy::DICTIONARY)
        } else {
            Cow::Owned(VariantType::new_array(self))
        }
    }
}

unsafe impl Sync for VariantTy {}

#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *const ffi::GVariantType> for VariantTy {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const ffi::GVariantType, Self> {
        Stash(self.as_ptr(), PhantomData)
    }
}

impl fmt::Display for VariantTy {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl<'a> From<&'a VariantTy> for Cow<'a, VariantTy> {
    #[inline]
    fn from(ty: &'a VariantTy) -> Cow<'a, VariantTy> {
        Cow::Borrowed(ty)
    }
}

impl AsRef<VariantTy> for VariantTy {
    #[inline]
    fn as_ref(&self) -> &Self {
        self
    }
}

impl ToOwned for VariantTy {
    type Owned = VariantType;

    #[inline]
    fn to_owned(&self) -> VariantType {
        unsafe {
            VariantType {
                ptr: ptr::NonNull::new_unchecked(ffi::g_variant_type_copy(self.as_ptr())),
                len: self.inner.len(),
            }
        }
    }
}

impl StaticType for VariantTy {
    #[inline]
    fn static_type() -> Type {
        unsafe { from_glib(ffi::g_variant_type_get_gtype()) }
    }
}

#[doc(hidden)]
unsafe impl<'a> crate::value::FromValue<'a> for &'a VariantTy {
    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a crate::Value) -> Self {
        let ptr = gobject_ffi::g_value_get_boxed(value.to_glib_none().0);
        debug_assert!(!ptr.is_null());
        VariantTy::from_ptr(ptr as *const ffi::GVariantType)
    }
}

#[doc(hidden)]
impl crate::value::ToValue for VariantTy {
    fn to_value(&self) -> crate::Value {
        unsafe {
            let mut value = crate::Value::from_type_unchecked(VariantTy::static_type());
            gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                self.to_glib_none().0 as *mut _,
            );
            value
        }
    }

    fn value_type(&self) -> crate::Type {
        VariantTy::static_type()
    }
}

#[doc(hidden)]
impl crate::value::ToValue for &VariantTy {
    fn to_value(&self) -> crate::Value {
        (*self).to_value()
    }

    #[inline]
    fn value_type(&self) -> crate::Type {
        VariantTy::static_type()
    }
}

#[doc(hidden)]
impl crate::value::ToValueOptional for &VariantTy {
    fn to_value_optional(s: Option<&Self>) -> crate::Value {
        let mut value = crate::Value::for_value_type::<VariantType>();
        unsafe {
            gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                s.to_glib_none().0 as *mut _,
            );
        }

        value
    }
}

impl StaticType for VariantType {
    #[inline]
    fn static_type() -> Type {
        unsafe { from_glib(ffi::g_variant_type_get_gtype()) }
    }
}

#[doc(hidden)]
impl crate::value::ValueType for VariantType {
    type Type = VariantType;
}

#[doc(hidden)]
impl crate::value::ValueTypeOptional for VariantType {}

#[doc(hidden)]
unsafe impl<'a> crate::value::FromValue<'a> for VariantType {
    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a crate::Value) -> Self {
        let ptr = gobject_ffi::g_value_get_boxed(value.to_glib_none().0);
        debug_assert!(!ptr.is_null());
        from_glib_none(ptr as *const ffi::GVariantType)
    }
}

#[doc(hidden)]
impl crate::value::ToValue for VariantType {
    fn to_value(&self) -> crate::Value {
        unsafe {
            let mut value = crate::Value::from_type_unchecked(VariantType::static_type());
            gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut _>::to_glib_none(&self).0 as *mut _,
            );
            value
        }
    }

    fn value_type(&self) -> crate::Type {
        VariantType::static_type()
    }
}

#[doc(hidden)]
impl From<VariantType> for crate::Value {
    fn from(t: VariantType) -> Self {
        unsafe {
            let mut value = crate::Value::from_type_unchecked(VariantType::static_type());
            gobject_ffi::g_value_take_boxed(
                value.to_glib_none_mut().0,
                IntoGlibPtr::<*mut _>::into_glib_ptr(t) as *mut _,
            );
            value
        }
    }
}

#[doc(hidden)]
impl crate::value::ToValueOptional for VariantType {
    fn to_value_optional(s: Option<&Self>) -> crate::Value {
        let mut value = crate::Value::for_value_type::<Self>();
        unsafe {
            gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut _>::to_glib_none(&s).0 as *mut _,
            );
        }

        value
    }
}

impl PartialEq for VariantType {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        <VariantTy as PartialEq>::eq(self, other)
    }
}

macro_rules! impl_eq {
    ($lhs:ty, $rhs: ty) => {
        #[allow(clippy::extra_unused_lifetimes)]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                <VariantTy as PartialEq>::eq(self, other)
            }
        }

        #[allow(clippy::extra_unused_lifetimes)]
        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                <VariantTy as PartialEq>::eq(self, other)
            }
        }
    };
}

impl_eq!(VariantType, VariantTy);
impl_eq!(VariantType, &'a VariantTy);
impl_eq!(VariantType, Cow<'a, VariantTy>);
impl_eq!(&'a VariantTy, Cow<'b, VariantTy>);

macro_rules! impl_str_eq {
    ($lhs:ty, $rhs: ty) => {
        #[allow(clippy::redundant_slicing)]
        #[allow(clippy::extra_unused_lifetimes)]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                self.as_str().eq(&other[..])
            }
        }

        #[allow(clippy::extra_unused_lifetimes)]
        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                self[..].eq(other.as_str())
            }
        }
    };
}

impl_str_eq!(VariantTy, str);
impl_str_eq!(VariantTy, &'a str);
impl_str_eq!(&'a VariantTy, str);
impl_str_eq!(VariantTy, String);
impl_str_eq!(&'a VariantTy, String);
impl_str_eq!(VariantType, str);
impl_str_eq!(VariantType, &'a str);
impl_str_eq!(VariantType, String);

impl Eq for VariantType {}

// rustdoc-stripper-ignore-next
/// An iterator over the individual components of a tuple [VariantTy].
///
/// This can be conveniently constructed using [VariantTy::tuple_types].
#[derive(Debug, Copy, Clone)]
pub struct VariantTyIterator<'a> {
    elem: Option<&'a VariantTy>,
}

impl<'a> VariantTyIterator<'a> {
    // rustdoc-stripper-ignore-next
    /// Creates a new iterator over the types of the specified [VariantTy].
    ///
    /// Returns `Ok` if the type is a definite tuple or dictionary entry type,
    /// `Err` otherwise.
    pub fn new(ty: &'a VariantTy) -> Result<Self, BoolError> {
        if (ty.is_tuple() && ty != VariantTy::TUPLE) || ty.is_dict_entry() {
            Ok(Self { elem: ty.first() })
        } else {
            Err(bool_error!(
                "Expected a definite tuple or dictionary entry type"
            ))
        }
    }
}

impl<'a> Iterator for VariantTyIterator<'a> {
    type Item = &'a VariantTy;

    #[doc(alias = "g_variant_type_next")]
    fn next(&mut self) -> Option<Self::Item> {
        let elem = self.elem?;
        self.elem = elem.next();
        Some(elem)
    }
}

impl iter::FusedIterator for VariantTyIterator<'_> {}

#[cfg(test)]
mod tests {
    use super::*;

    unsafe fn equal<T, U>(ptr1: *const T, ptr2: *const U) -> bool {
        from_glib(ffi::g_variant_type_equal(
            ptr1 as *const _,
            ptr2 as *const _,
        ))
    }

    #[test]
    fn new() {
        let ty = VariantTy::new("((iii)s)").unwrap();
        unsafe {
            assert!(equal(ty.as_ptr(), b"((iii)s)\0" as *const u8));
        }
    }

    #[test]
    fn new_empty() {
        assert!(VariantTy::new("").is_err());
    }

    #[test]
    fn new_with_nul() {
        assert!(VariantTy::new("((iii\0)s)").is_err());
    }

    #[test]
    fn new_too_short() {
        assert!(VariantTy::new("((iii").is_err());
    }

    #[test]
    fn new_too_long() {
        assert!(VariantTy::new("(iii)s").is_err());
    }

    #[test]
    fn eq() {
        let ty1 = VariantTy::new("((iii)s)").unwrap();
        let ty2 = VariantTy::new("((iii)s)").unwrap();
        assert_eq!(ty1, ty2);
        assert_eq!(ty1, "((iii)s)");
        unsafe {
            assert!(equal(ty1.as_ptr(), ty2.as_ptr()));
        }
    }

    #[test]
    fn ne() {
        let ty1 = VariantTy::new("((iii)s)").unwrap();
        let ty2 = VariantTy::new("((iii)o)").unwrap();
        assert_ne!(ty1, ty2);
        assert_ne!(ty1, "((iii)o)");
        unsafe {
            assert!(!equal(ty1.as_ptr(), ty2.as_ptr()));
        }
    }

    #[test]
    fn from_bytes() {
        unsafe {
            let ty = VariantTy::from_ptr(b"((iii)s)" as *const u8 as *const _);
            assert_eq!(ty, "((iii)s)");
            assert!(equal(ty.as_ptr(), "((iii)s)".as_ptr()));
        }
    }

    #[test]
    fn to_owned() {
        let ty1 = VariantTy::new("((iii)s)").unwrap();
        let ty2 = ty1.to_owned();
        assert_eq!(ty1, ty2);
        assert_eq!(ty2, "((iii)s)");
        unsafe {
            assert!(equal(ty1.as_ptr(), ty2.as_ptr()));
        }
    }

    #[test]
    fn value() {
        let ty1 = VariantType::new("*").unwrap();
        let tyv = ty1.to_value();
        let ty2 = tyv.get::<VariantType>().unwrap();
        assert_eq!(ty1, ty2);

        let ty3 = VariantTy::new("*").unwrap();
        let tyv2 = ty3.to_value();
        let ty4 = tyv2.get::<VariantType>().unwrap();
        assert_eq!(ty3, ty4);

        let ty5 = VariantTy::ANY;
        let tyv3 = ty5.to_value();
        let ty6 = tyv3.get::<VariantType>().unwrap();
        assert_eq!(ty5, ty6);
    }

    #[test]
    fn type_() {
        assert_eq!(VariantTy::static_type(), VariantType::static_type())
    }

    #[test]
    fn tuple_iter() {
        let ty = VariantTy::new("((iii)s)").unwrap();
        let types: Vec<_> = ty.tuple_types().map(|t| t.as_str()).collect();
        assert_eq!(&types, &["(iii)", "s"]);
    }
}