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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::translate::*;
use crate::types::StaticType;
use crate::types::Type;
use crate::BoolError;
use std::borrow::{Borrow, Cow, ToOwned};
use std::cmp::{Eq, PartialEq};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::slice;

/// 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
/// This section introduces the GVariant 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 GVariant.
///
/// The first major change with respect to the D-Bus type system is the
/// introduction of maybe (or "nullable") types. Any type in GVariant 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 GVariant 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 GVariant, 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, GVariant 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. GVariant deals with single values directly so GVariant type
/// strings always describe the type of exactly one value. This means
/// that a D-Bus signature string is generally not a valid GVariant 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 `GtkBin` can exist (since `GtkBin` is an abstract class),
/// but a `GtkWindow` can certainly be instantiated, and you would say
/// that the `GtkWindow` is a `GtkBin` (since `GtkWindow` is a subclass of
/// `GtkBin`).
///
/// ## GVariant Type Strings
///
/// A GVariant 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, [`Variant`][crate::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` 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: *mut 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 {
    /// 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 [`VariantType`][crate::VariantType] corresponding to the type string given
    /// by `type_string`. It is appropriate to call `g_variant_type_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
    ///
    /// # Returns
    ///
    /// a new [`VariantType`][crate::VariantType]
    pub fn new(type_string: &str) -> Result<VariantType, BoolError> {
        VariantTy::new(type_string).map(ToOwned::to_owned)
    }
}

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

impl Drop for VariantType {
    fn drop(&mut self) {
        unsafe { ffi::g_variant_type_free(self.ptr) }
    }
}

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

impl Clone for VariantType {
    fn clone(&self) -> VariantType {
        unsafe {
            VariantType {
                ptr: ffi::g_variant_type_copy(self.ptr),
                len: self.len,
            }
        }
    }
}

impl Deref for VariantType {
    type Target = VariantTy;
    fn deref(&self) -> &VariantTy {
        unsafe {
            &*(slice::from_raw_parts(self.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.to_str())
    }
}

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

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

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

    fn to_glib_none(&'a self) -> Stash<'a, *const ffi::GVariantType, Self> {
        Stash(self.ptr, self)
    }

    fn to_glib_full(&self) -> *const ffi::GVariantType {
        unsafe { ffi::g_variant_type_copy(self.ptr) }
    }
}

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

    fn to_glib_none(&'a self) -> Stash<'a, *mut ffi::GVariantType, Self> {
        Stash(self.ptr, self)
    }

    fn to_glib_full(&self) -> *mut ffi::GVariantType {
        unsafe { ffi::g_variant_type_copy(self.ptr) }
    }
}

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

    fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ffi::GVariantType, Self> {
        StashMut(self.ptr, self)
    }
}

#[doc(hidden)]
impl FromGlibPtrNone<*const ffi::GVariantType> for VariantType {
    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 {
    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()
    }
}

/// 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.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct VariantTy {
    inner: str,
}

impl VariantTy {
    /// An indefinite type that is a supertype of every type (including itself).
    #[doc(alias = "G_VARIANT_TYPE_ANY")]
    pub const ANY: &'static VariantTy = unsafe { std::mem::transmute::<&str, &VariantTy>("*") };

    /// 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> {
        let ptr = type_string.as_ptr();
        let limit = ptr as usize + type_string.len();
        let mut end = 0_usize;
        unsafe {
            let ok = from_glib(ffi::g_variant_type_string_scan(
                ptr as *const _,
                limit as *const _,
                &mut end as *mut usize as *mut _,
            ));
            if ok && end == limit {
                Ok(&*(type_string.as_bytes() as *const [u8] as *const VariantTy))
            } else {
                Err(bool_error!("Invalid type string: '{}'", type_string))
            }
        }
    }

    /// Converts a type string into `&VariantTy` without any checks.
    ///
    /// # Safety
    ///
    /// The caller is responsible for passing in only a valid variant type string
    /// which is already registered with the type system.
    pub unsafe fn from_str_unchecked(type_string: &str) -> &VariantTy {
        &*(type_string as *const str as *const VariantTy)
    }

    /// Creates `&VariantTy` with a wildcard lifetime from a `GVariantType`
    /// pointer.
    #[doc(hidden)]
    pub unsafe fn from_ptr<'a>(ptr: *const ffi::GVariantType) -> &'a VariantTy {
        let len = ffi::g_variant_type_get_string_length(ptr) as usize;
        &*(slice::from_raw_parts(ptr as *const u8, len) as *const [u8] as *const VariantTy)
    }

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

    /// Converts to a string slice.
    pub fn to_str(&self) -> &str {
        &self.inner
    }

    /// Return this type as an array.
    pub(crate) fn with_array(&self) -> VariantType {
        VariantType::new(&format!("a{}", self.to_str())).expect("invalid variant signature")
    }
}

unsafe impl Sync for VariantTy {}

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

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

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

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

impl ToOwned for VariantTy {
    type Owned = VariantType;

    fn to_owned(&self) -> VariantType {
        unsafe {
            VariantType {
                ptr: ffi::g_variant_type_copy(self.as_ptr()),
                len: self.inner.len(),
            }
        }
    }
}

impl StaticType for VariantTy {
    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);
        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(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()
    }

    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 {
    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)]
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);
        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(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 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) => {
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                <VariantTy as PartialEq>::eq(self, other)
            }
        }

        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)]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                self.to_str().eq(&other[..])
            }
        }

        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                self[..].eq(other.to_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 {}

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

    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())
    }
}