Skip to main content

glib/
variant.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3// rustdoc-stripper-ignore-next
4//! `Variant` binding and helper traits.
5//!
6//! [`Variant`](struct.Variant.html) is an immutable dynamically-typed generic
7//! container. Its type and value are defined at construction and never change.
8//!
9//! `Variant` types are described by [`VariantType`](../struct.VariantType.html)
10//! "type strings".
11//!
12//! `GVariant` supports arbitrarily complex types built from primitives like integers, floating point
13//! numbers, strings, arrays, tuples and dictionaries. See [`ToVariant#foreign-impls`] for
14//! a full list of supported types. You may also implement [`ToVariant`] and [`FromVariant`]
15//! manually, or derive them using the [`Variant`](derive@crate::Variant) derive macro.
16//!
17//! # Examples
18//!
19//! ```
20//! use glib::prelude::*; // or `use gtk::prelude::*;`
21//! use glib::variant::{Variant, FromVariant};
22//! use std::collections::HashMap;
23//!
24//! // Using the `ToVariant` trait.
25//! let num = 10.to_variant();
26//!
27//! // `is` tests the type of the value.
28//! assert!(num.is::<i32>());
29//!
30//! // `get` tries to extract the value.
31//! assert_eq!(num.get::<i32>(), Some(10));
32//! assert_eq!(num.get::<u32>(), None);
33//!
34//! // `get_str` tries to borrow a string slice.
35//! let hello = "Hello!".to_variant();
36//! assert_eq!(hello.str(), Some("Hello!"));
37//! assert_eq!(num.str(), None);
38//!
39//! // `fixed_array` tries to borrow a fixed size array (u8, bool, i16, etc.),
40//! // rather than creating a deep copy which would be expensive for
41//! // nontrivially sized arrays of fixed size elements.
42//! // The test data here is the zstd compression header, which
43//! // stands in for arbitrary binary data (e.g. not UTF-8).
44//! let bufdata = b"\xFD\x2F\xB5\x28";
45//! let bufv = glib::Variant::array_from_fixed_array(&bufdata[..]);
46//! assert_eq!(bufv.fixed_array::<u8>().unwrap(), bufdata);
47//! assert!(num.fixed_array::<u8>().is_err());
48//!
49//! // Variant carrying a Variant
50//! let variant = Variant::from_variant(&hello);
51//! let variant = variant.as_variant().unwrap();
52//! assert_eq!(variant.str(), Some("Hello!"));
53//!
54//! // Variant carrying an array
55//! let array = ["Hello", "there!"];
56//! let variant = array.into_iter().collect::<Variant>();
57//! assert_eq!(variant.n_children(), 2);
58//! assert_eq!(variant.child_value(0).str(), Some("Hello"));
59//! assert_eq!(variant.child_value(1).str(), Some("there!"));
60//!
61//! // You can also convert from and to a Vec
62//! let variant = vec!["Hello", "there!"].to_variant();
63//! assert_eq!(variant.n_children(), 2);
64//! let vec = <Vec<String>>::from_variant(&variant).unwrap();
65//! assert_eq!(vec[0], "Hello");
66//!
67//! // Conversion to and from HashMap and BTreeMap is also possible
68//! let mut map: HashMap<u16, &str> = HashMap::new();
69//! map.insert(1, "hi");
70//! map.insert(2, "there");
71//! let variant = map.to_variant();
72//! assert_eq!(variant.n_children(), 2);
73//! let map: HashMap<u16, String> = HashMap::from_variant(&variant).unwrap();
74//! assert_eq!(map[&1], "hi");
75//! assert_eq!(map[&2], "there");
76//!
77//! // And conversion to and from tuples.
78//! let variant = ("hello", 42u16, vec![ "there", "you" ],).to_variant();
79//! assert_eq!(variant.n_children(), 3);
80//! assert_eq!(variant.type_().as_str(), "(sqas)");
81//! let tuple = <(String, u16, Vec<String>)>::from_variant(&variant).unwrap();
82//! assert_eq!(tuple.0, "hello");
83//! assert_eq!(tuple.1, 42);
84//! assert_eq!(tuple.2, &[ "there", "you"]);
85//!
86//! // `Option` is supported as well, through maybe types
87//! let variant = Some("hello").to_variant();
88//! assert_eq!(variant.n_children(), 1);
89//! let mut s = <Option<String>>::from_variant(&variant).unwrap();
90//! assert_eq!(s.unwrap(), "hello");
91//! s = None;
92//! let variant = s.to_variant();
93//! assert_eq!(variant.n_children(), 0);
94//! let s = <Option<String>>::from_variant(&variant).unwrap();
95//! assert!(s.is_none());
96//!
97//! // Paths may be converted, too. Please note the portability warning above!
98//! use std::path::{Path, PathBuf};
99//! let path = Path::new("foo/bar");
100//! let path_variant = path.to_variant();
101//! assert_eq!(PathBuf::from_variant(&path_variant).as_deref(), Some(path));
102//! ```
103
104use std::{
105    borrow::Cow,
106    cmp::Ordering,
107    collections::{BTreeMap, HashMap},
108    fmt,
109    fmt::Display,
110    hash::{BuildHasher, Hash, Hasher},
111    mem, ptr, slice, str,
112};
113
114use crate::{
115    Bytes, Type, VariantIter, VariantStrIter, VariantTy, VariantType, ffi, gobject_ffi, prelude::*,
116    translate::*,
117};
118
119wrapper! {
120    // rustdoc-stripper-ignore-next
121    /// A generic immutable value capable of carrying various types.
122    ///
123    /// See the [module documentation](index.html) for more details.
124    #[doc(alias = "GVariant")]
125    pub struct Variant(Shared<ffi::GVariant>);
126
127    match fn {
128        ref => |ptr| ffi::g_variant_ref_sink(ptr),
129        unref => |ptr| ffi::g_variant_unref(ptr),
130    }
131}
132
133impl StaticType for Variant {
134    #[inline]
135    fn static_type() -> Type {
136        Type::VARIANT
137    }
138}
139
140#[doc(hidden)]
141impl crate::value::ValueType for Variant {
142    type Type = Variant;
143}
144
145#[doc(hidden)]
146impl crate::value::ValueTypeOptional for Variant {}
147
148#[doc(hidden)]
149unsafe impl<'a> crate::value::FromValue<'a> for Variant {
150    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;
151
152    unsafe fn from_value(value: &'a crate::Value) -> Self {
153        unsafe {
154            let ptr = gobject_ffi::g_value_dup_variant(value.to_glib_none().0);
155            debug_assert!(!ptr.is_null());
156            from_glib_full(ptr)
157        }
158    }
159}
160
161#[doc(hidden)]
162impl crate::value::ToValue for Variant {
163    fn to_value(&self) -> crate::Value {
164        unsafe {
165            let mut value = crate::Value::from_type_unchecked(Variant::static_type());
166            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, self.to_glib_full());
167            value
168        }
169    }
170
171    fn value_type(&self) -> crate::Type {
172        Variant::static_type()
173    }
174}
175
176#[doc(hidden)]
177impl From<Variant> for crate::Value {
178    #[inline]
179    fn from(v: Variant) -> Self {
180        unsafe {
181            let mut value = crate::Value::from_type_unchecked(Variant::static_type());
182            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, v.into_glib_ptr());
183            value
184        }
185    }
186}
187
188#[doc(hidden)]
189impl crate::value::ToValueOptional for Variant {
190    fn to_value_optional(s: Option<&Self>) -> crate::Value {
191        let mut value = crate::Value::for_value_type::<Self>();
192        unsafe {
193            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, s.to_glib_full());
194        }
195
196        value
197    }
198}
199
200// rustdoc-stripper-ignore-next
201/// An error returned from the [`try_get`](struct.Variant.html#method.try_get) function
202/// on a [`Variant`](struct.Variant.html) when the expected type does not match the actual type.
203#[derive(Clone, PartialEq, Eq, Debug)]
204pub struct VariantTypeMismatchError {
205    pub actual: VariantType,
206    pub expected: VariantType,
207}
208
209impl VariantTypeMismatchError {
210    pub fn new(actual: VariantType, expected: VariantType) -> Self {
211        Self { actual, expected }
212    }
213}
214
215impl fmt::Display for VariantTypeMismatchError {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        write!(
218            f,
219            "Type mismatch: Expected '{}' got '{}'",
220            self.expected, self.actual
221        )
222    }
223}
224
225impl std::error::Error for VariantTypeMismatchError {}
226
227impl Variant {
228    // rustdoc-stripper-ignore-next
229    /// Returns the type of the value.
230    #[doc(alias = "g_variant_get_type")]
231    pub fn type_(&self) -> &VariantTy {
232        unsafe { VariantTy::from_ptr(ffi::g_variant_get_type(self.to_glib_none().0)) }
233    }
234
235    // rustdoc-stripper-ignore-next
236    /// Returns `true` if the type of the value corresponds to `T`.
237    #[inline]
238    #[doc(alias = "g_variant_is_of_type")]
239    pub fn is<T: StaticVariantType>(&self) -> bool {
240        self.is_type(&T::static_variant_type())
241    }
242
243    // rustdoc-stripper-ignore-next
244    /// Returns `true` if the type of the value corresponds to `type_`.
245    ///
246    /// This is equivalent to [`self.type_().is_subtype_of(type_)`](VariantTy::is_subtype_of).
247    #[inline]
248    #[doc(alias = "g_variant_is_of_type")]
249    pub fn is_type(&self, type_: &VariantTy) -> bool {
250        unsafe {
251            from_glib(ffi::g_variant_is_of_type(
252                self.to_glib_none().0,
253                type_.to_glib_none().0,
254            ))
255        }
256    }
257
258    // rustdoc-stripper-ignore-next
259    /// Returns the classification of the variant.
260    #[doc(alias = "g_variant_classify")]
261    pub fn classify(&self) -> crate::VariantClass {
262        unsafe { from_glib(ffi::g_variant_classify(self.to_glib_none().0)) }
263    }
264
265    // rustdoc-stripper-ignore-next
266    /// Tries to extract a value of type `T`.
267    ///
268    /// Returns `Some` if `T` matches the variant's type.
269    #[inline]
270    pub fn get<T: FromVariant>(&self) -> Option<T> {
271        T::from_variant(self)
272    }
273
274    // rustdoc-stripper-ignore-next
275    /// Tries to extract a value of type `T`.
276    pub fn try_get<T: FromVariant>(&self) -> Result<T, VariantTypeMismatchError> {
277        self.get().ok_or_else(|| {
278            VariantTypeMismatchError::new(
279                self.type_().to_owned(),
280                T::static_variant_type().into_owned(),
281            )
282        })
283    }
284
285    // rustdoc-stripper-ignore-next
286    /// Boxes value.
287    #[inline]
288    pub fn from_variant(value: &Variant) -> Self {
289        unsafe { from_glib_none(ffi::g_variant_new_variant(value.to_glib_none().0)) }
290    }
291
292    // rustdoc-stripper-ignore-next
293    /// Unboxes self.
294    ///
295    /// Returns `Some` if self contains a `Variant`.
296    #[inline]
297    #[doc(alias = "get_variant")]
298    pub fn as_variant(&self) -> Option<Variant> {
299        unsafe { from_glib_full(ffi::g_variant_get_variant(self.to_glib_none().0)) }
300    }
301
302    // rustdoc-stripper-ignore-next
303    /// Reads a child item out of a container `Variant` instance.
304    ///
305    /// # Panics
306    ///
307    /// * if `self` is not a container type.
308    /// * if given `index` is larger than number of children.
309    #[doc(alias = "get_child_value")]
310    #[doc(alias = "g_variant_get_child_value")]
311    #[must_use]
312    pub fn child_value(&self, index: usize) -> Variant {
313        assert!(self.is_container());
314        assert!(index < self.n_children());
315
316        unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) }
317    }
318
319    // rustdoc-stripper-ignore-next
320    /// Try to read a child item out of a container `Variant` instance.
321    ///
322    /// It returns `None` if `self` is not a container type or if the given
323    /// `index` is larger than number of children.
324    pub fn try_child_value(&self, index: usize) -> Option<Variant> {
325        if !(self.is_container() && index < self.n_children()) {
326            return None;
327        }
328
329        let v =
330            unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) };
331        Some(v)
332    }
333
334    // rustdoc-stripper-ignore-next
335    /// Try to read a child item out of a container `Variant` instance.
336    ///
337    /// It returns `Ok(None)` if `self` is not a container type or if the given
338    /// `index` is larger than number of children.  An error is thrown if the
339    /// type does not match.
340    pub fn try_child_get<T: StaticVariantType + FromVariant>(
341        &self,
342        index: usize,
343    ) -> Result<Option<T>, VariantTypeMismatchError> {
344        // TODO: In the future optimize this by using g_variant_get_child()
345        // directly to avoid allocating a GVariant.
346        self.try_child_value(index).map(|v| v.try_get()).transpose()
347    }
348
349    // rustdoc-stripper-ignore-next
350    /// Read a child item out of a container `Variant` instance.
351    ///
352    /// # Panics
353    ///
354    /// * if `self` is not a container type.
355    /// * if given `index` is larger than number of children.
356    /// * if the expected variant type does not match
357    pub fn child_get<T: StaticVariantType + FromVariant>(&self, index: usize) -> T {
358        // TODO: In the future optimize this by using g_variant_get_child()
359        // directly to avoid allocating a GVariant.
360        self.child_value(index).get().unwrap()
361    }
362
363    // rustdoc-stripper-ignore-next
364    /// Tries to extract a `&str`.
365    ///
366    /// Returns `Some` if the variant has a string type (`s`, `o` or `g` type
367    /// strings).
368    #[doc(alias = "get_str")]
369    #[doc(alias = "g_variant_get_string")]
370    pub fn str(&self) -> Option<&str> {
371        unsafe {
372            match self.type_().as_str() {
373                "s" | "o" | "g" => {
374                    let mut len = 0;
375                    let ptr = ffi::g_variant_get_string(self.to_glib_none().0, &mut len);
376                    if len == 0 {
377                        Some("")
378                    } else {
379                        let ret = str::from_utf8_unchecked(slice::from_raw_parts(
380                            ptr as *const u8,
381                            len as _,
382                        ));
383                        Some(ret)
384                    }
385                }
386                _ => None,
387            }
388        }
389    }
390
391    // rustdoc-stripper-ignore-next
392    /// Tries to extract a `&[T]` from a variant of array type with a suitable element type.
393    ///
394    /// Returns an error if the type is wrong.
395    #[doc(alias = "g_variant_get_fixed_array")]
396    pub fn fixed_array<T: FixedSizeVariantType>(&self) -> Result<&[T], VariantTypeMismatchError> {
397        unsafe {
398            let expected_ty = T::static_variant_type().as_array();
399            if self.type_() != expected_ty {
400                return Err(VariantTypeMismatchError {
401                    actual: self.type_().to_owned(),
402                    expected: expected_ty.into_owned(),
403                });
404            }
405
406            let mut n_elements = mem::MaybeUninit::uninit();
407            let ptr = ffi::g_variant_get_fixed_array(
408                self.to_glib_none().0,
409                n_elements.as_mut_ptr(),
410                mem::size_of::<T>(),
411            );
412
413            let n_elements = n_elements.assume_init();
414            if n_elements == 0 {
415                Ok(&[])
416            } else {
417                debug_assert!(!ptr.is_null());
418                Ok(slice::from_raw_parts(ptr as *const T, n_elements))
419            }
420        }
421    }
422
423    // rustdoc-stripper-ignore-next
424    /// Creates a new Variant array from children.
425    ///
426    /// # Panics
427    ///
428    /// This function panics if not all variants are of type `T`.
429    #[doc(alias = "g_variant_new_array")]
430    pub fn array_from_iter<T: StaticVariantType>(
431        children: impl IntoIterator<Item = Variant>,
432    ) -> Self {
433        Self::array_from_iter_with_type(&T::static_variant_type(), children)
434    }
435
436    // rustdoc-stripper-ignore-next
437    /// Creates a new Variant array from children with the specified type.
438    ///
439    /// # Panics
440    ///
441    /// This function panics if not all variants are of type `type_`.
442    #[doc(alias = "g_variant_new_array")]
443    pub fn array_from_iter_with_type(
444        type_: &VariantTy,
445        children: impl IntoIterator<Item = impl AsRef<Variant>>,
446    ) -> Self {
447        unsafe {
448            let mut builder = mem::MaybeUninit::uninit();
449            ffi::g_variant_builder_init(builder.as_mut_ptr(), type_.as_array().to_glib_none().0);
450            let mut builder = builder.assume_init();
451            for value in children.into_iter() {
452                let value = value.as_ref();
453                if ffi::g_variant_is_of_type(value.to_glib_none().0, type_.to_glib_none().0)
454                    == ffi::GFALSE
455                {
456                    ffi::g_variant_builder_clear(&mut builder);
457                    assert!(value.is_type(type_));
458                }
459
460                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
461            }
462            from_glib_none(ffi::g_variant_builder_end(&mut builder))
463        }
464    }
465
466    // rustdoc-stripper-ignore-next
467    /// Creates a new Variant array from a fixed array.
468    #[doc(alias = "g_variant_new_fixed_array")]
469    pub fn array_from_fixed_array<T: FixedSizeVariantType>(array: &[T]) -> Self {
470        let type_ = T::static_variant_type();
471
472        unsafe {
473            from_glib_none(ffi::g_variant_new_fixed_array(
474                type_.as_ptr(),
475                array.as_ptr() as ffi::gconstpointer,
476                array.len(),
477                mem::size_of::<T>(),
478            ))
479        }
480    }
481
482    // rustdoc-stripper-ignore-next
483    /// Creates a new Variant tuple from children.
484    #[doc(alias = "g_variant_new_tuple")]
485    pub fn tuple_from_iter(children: impl IntoIterator<Item = impl AsRef<Variant>>) -> Self {
486        unsafe {
487            let mut builder = mem::MaybeUninit::uninit();
488            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
489            let mut builder = builder.assume_init();
490            for value in children.into_iter() {
491                ffi::g_variant_builder_add_value(&mut builder, value.as_ref().to_glib_none().0);
492            }
493            from_glib_none(ffi::g_variant_builder_end(&mut builder))
494        }
495    }
496
497    // rustdoc-stripper-ignore-next
498    /// Creates a new dictionary entry Variant.
499    ///
500    /// [DictEntry] should be preferred over this when the types are known statically.
501    #[doc(alias = "g_variant_new_dict_entry")]
502    pub fn from_dict_entry(key: &Variant, value: &Variant) -> Self {
503        unsafe {
504            from_glib_none(ffi::g_variant_new_dict_entry(
505                key.to_glib_none().0,
506                value.to_glib_none().0,
507            ))
508        }
509    }
510
511    // rustdoc-stripper-ignore-next
512    /// Creates a new maybe Variant.
513    #[doc(alias = "g_variant_new_maybe")]
514    pub fn from_maybe<T: StaticVariantType>(child: Option<&Variant>) -> Self {
515        let type_ = T::static_variant_type();
516        match child {
517            Some(child) => {
518                assert_eq!(type_, child.type_());
519
520                Self::from_some(child)
521            }
522            None => Self::from_none(&type_),
523        }
524    }
525
526    // rustdoc-stripper-ignore-next
527    /// Creates a new maybe Variant from a child.
528    #[doc(alias = "g_variant_new_maybe")]
529    pub fn from_some(child: &Variant) -> Self {
530        unsafe {
531            from_glib_none(ffi::g_variant_new_maybe(
532                ptr::null(),
533                child.to_glib_none().0,
534            ))
535        }
536    }
537
538    // rustdoc-stripper-ignore-next
539    /// Creates a new maybe Variant with Nothing.
540    #[doc(alias = "g_variant_new_maybe")]
541    pub fn from_none(type_: &VariantTy) -> Self {
542        unsafe {
543            from_glib_none(ffi::g_variant_new_maybe(
544                type_.to_glib_none().0,
545                ptr::null_mut(),
546            ))
547        }
548    }
549
550    // rustdoc-stripper-ignore-next
551    /// Extract the value of a maybe Variant.
552    ///
553    /// Returns the child value, or `None` if the value is Nothing.
554    ///
555    /// # Panics
556    ///
557    /// Panics if the variant is not maybe-typed.
558    #[inline]
559    pub fn as_maybe(&self) -> Option<Variant> {
560        assert!(self.type_().is_maybe());
561
562        unsafe { from_glib_full(ffi::g_variant_get_maybe(self.to_glib_none().0)) }
563    }
564
565    // rustdoc-stripper-ignore-next
566    /// Pretty-print the contents of this variant in a human-readable form.
567    ///
568    /// A variant can be recreated from this output via [`Variant::parse`].
569    #[doc(alias = "g_variant_print")]
570    pub fn print(&self, type_annotate: bool) -> crate::GString {
571        unsafe {
572            from_glib_full(ffi::g_variant_print(
573                self.to_glib_none().0,
574                type_annotate.into_glib(),
575            ))
576        }
577    }
578
579    // rustdoc-stripper-ignore-next
580    /// Parses a GVariant from the text representation produced by [`print()`](Self::print).
581    #[doc(alias = "g_variant_parse")]
582    pub fn parse(type_: Option<&VariantTy>, text: &str) -> Result<Self, crate::Error> {
583        unsafe {
584            let mut error = ptr::null_mut();
585            let text = text.as_bytes().as_ptr_range();
586            let variant = ffi::g_variant_parse(
587                type_.to_glib_none().0,
588                text.start as *const _,
589                text.end as *const _,
590                ptr::null_mut(),
591                &mut error,
592            );
593            if variant.is_null() {
594                debug_assert!(!error.is_null());
595                Err(from_glib_full(error))
596            } else {
597                debug_assert!(error.is_null());
598                Ok(from_glib_full(variant))
599            }
600        }
601    }
602
603    // rustdoc-stripper-ignore-next
604    /// Constructs a new serialized-mode GVariant instance.
605    #[doc(alias = "g_variant_new_from_bytes")]
606    pub fn from_bytes<T: StaticVariantType>(bytes: &Bytes) -> Self {
607        Variant::from_bytes_with_type(bytes, &T::static_variant_type())
608    }
609
610    // rustdoc-stripper-ignore-next
611    /// Constructs a new serialized-mode GVariant instance.
612    ///
613    /// This is the same as `from_bytes`, except that checks on the passed
614    /// data are skipped.
615    ///
616    /// You should not use this function on data from external sources.
617    ///
618    /// # Safety
619    ///
620    /// Since the data is not validated, this is potentially dangerous if called
621    /// on bytes which are not guaranteed to have come from serialising another
622    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
623    pub unsafe fn from_bytes_trusted<T: StaticVariantType>(bytes: &Bytes) -> Self {
624        unsafe { Variant::from_bytes_with_type_trusted(bytes, &T::static_variant_type()) }
625    }
626
627    // rustdoc-stripper-ignore-next
628    /// Constructs a new serialized-mode GVariant instance.
629    #[doc(alias = "g_variant_new_from_data")]
630    pub fn from_data<T: StaticVariantType, A: AsRef<[u8]> + 'static>(data: A) -> Self {
631        Variant::from_data_with_type(data, &T::static_variant_type())
632    }
633
634    // rustdoc-stripper-ignore-next
635    /// Constructs a new serialized-mode GVariant instance.
636    ///
637    /// This is the same as `from_data`, except that checks on the passed
638    /// data are skipped.
639    ///
640    /// You should not use this function on data from external sources.
641    ///
642    /// # Safety
643    ///
644    /// Since the data is not validated, this is potentially dangerous if called
645    /// on bytes which are not guaranteed to have come from serialising another
646    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
647    pub unsafe fn from_data_trusted<T: StaticVariantType, A: AsRef<[u8]> + 'static>(
648        data: A,
649    ) -> Self {
650        unsafe { Variant::from_data_with_type_trusted(data, &T::static_variant_type()) }
651    }
652
653    // rustdoc-stripper-ignore-next
654    /// Constructs a new serialized-mode GVariant instance with a given type.
655    #[doc(alias = "g_variant_new_from_bytes")]
656    pub fn from_bytes_with_type(bytes: &Bytes, type_: &VariantTy) -> Self {
657        unsafe {
658            from_glib_none(ffi::g_variant_new_from_bytes(
659                type_.as_ptr() as *const _,
660                bytes.to_glib_none().0,
661                false.into_glib(),
662            ))
663        }
664    }
665
666    // rustdoc-stripper-ignore-next
667    /// Constructs a new serialized-mode GVariant instance with a given type.
668    ///
669    /// This is the same as `from_bytes`, except that checks on the passed
670    /// data are skipped.
671    ///
672    /// You should not use this function on data from external sources.
673    ///
674    /// # Safety
675    ///
676    /// Since the data is not validated, this is potentially dangerous if called
677    /// on bytes which are not guaranteed to have come from serialising another
678    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
679    pub unsafe fn from_bytes_with_type_trusted(bytes: &Bytes, type_: &VariantTy) -> Self {
680        unsafe {
681            from_glib_none(ffi::g_variant_new_from_bytes(
682                type_.as_ptr() as *const _,
683                bytes.to_glib_none().0,
684                true.into_glib(),
685            ))
686        }
687    }
688
689    // rustdoc-stripper-ignore-next
690    /// Constructs a new serialized-mode GVariant instance with a given type.
691    #[doc(alias = "g_variant_new_from_data")]
692    pub fn from_data_with_type<A: AsRef<[u8]> + 'static>(data: A, type_: &VariantTy) -> Self {
693        unsafe {
694            let data = Box::new(data);
695            let (data_ptr, len) = {
696                let data = (*data).as_ref();
697                (data.as_ptr(), data.len())
698            };
699
700            unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
701                unsafe {
702                    let _ = Box::from_raw(ptr as *mut A);
703                }
704            }
705
706            from_glib_none(ffi::g_variant_new_from_data(
707                type_.as_ptr() as *const _,
708                data_ptr as ffi::gconstpointer,
709                len,
710                false.into_glib(),
711                Some(free_data::<A>),
712                Box::into_raw(data) as ffi::gpointer,
713            ))
714        }
715    }
716
717    // rustdoc-stripper-ignore-next
718    /// Constructs a new serialized-mode GVariant instance with a given type.
719    ///
720    /// This is the same as `from_data`, except that checks on the passed
721    /// data are skipped.
722    ///
723    /// You should not use this function on data from external sources.
724    ///
725    /// # Safety
726    ///
727    /// Since the data is not validated, this is potentially dangerous if called
728    /// on bytes which are not guaranteed to have come from serialising another
729    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
730    pub unsafe fn from_data_with_type_trusted<A: AsRef<[u8]> + 'static>(
731        data: A,
732        type_: &VariantTy,
733    ) -> Self {
734        unsafe {
735            let data = Box::new(data);
736            let (data_ptr, len) = {
737                let data = (*data).as_ref();
738                (data.as_ptr(), data.len())
739            };
740
741            unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
742                unsafe {
743                    let _ = Box::from_raw(ptr as *mut A);
744                }
745            }
746
747            from_glib_none(ffi::g_variant_new_from_data(
748                type_.as_ptr() as *const _,
749                data_ptr as ffi::gconstpointer,
750                len,
751                true.into_glib(),
752                Some(free_data::<A>),
753                Box::into_raw(data) as ffi::gpointer,
754            ))
755        }
756    }
757
758    // rustdoc-stripper-ignore-next
759    /// Returns the serialized form of a GVariant instance.
760    #[doc(alias = "get_data_as_bytes")]
761    #[doc(alias = "g_variant_get_data_as_bytes")]
762    pub fn data_as_bytes(&self) -> Bytes {
763        unsafe { from_glib_full(ffi::g_variant_get_data_as_bytes(self.to_glib_none().0)) }
764    }
765
766    // rustdoc-stripper-ignore-next
767    /// Returns the serialized form of a GVariant instance.
768    #[doc(alias = "g_variant_get_data")]
769    pub fn data(&self) -> &[u8] {
770        unsafe {
771            let selfv = self.to_glib_none();
772            let len = ffi::g_variant_get_size(selfv.0);
773            if len == 0 {
774                return &[];
775            }
776            let ptr = ffi::g_variant_get_data(selfv.0);
777            slice::from_raw_parts(ptr as *const _, len as _)
778        }
779    }
780
781    // rustdoc-stripper-ignore-next
782    /// Returns the size of serialized form of a GVariant instance.
783    #[doc(alias = "g_variant_get_size")]
784    pub fn size(&self) -> usize {
785        unsafe { ffi::g_variant_get_size(self.to_glib_none().0) }
786    }
787
788    // rustdoc-stripper-ignore-next
789    /// Stores the serialized form of a GVariant instance into the given slice.
790    ///
791    /// The slice needs to be big enough.
792    #[doc(alias = "g_variant_store")]
793    pub fn store(&self, data: &mut [u8]) -> Result<usize, crate::BoolError> {
794        unsafe {
795            let size = ffi::g_variant_get_size(self.to_glib_none().0);
796            if data.len() < size {
797                return Err(bool_error!("Provided slice is too small"));
798            }
799
800            ffi::g_variant_store(self.to_glib_none().0, data.as_mut_ptr() as ffi::gpointer);
801
802            Ok(size)
803        }
804    }
805
806    // rustdoc-stripper-ignore-next
807    /// Returns a copy of the variant in normal form.
808    #[doc(alias = "g_variant_get_normal_form")]
809    #[must_use]
810    pub fn normal_form(&self) -> Self {
811        unsafe { from_glib_full(ffi::g_variant_get_normal_form(self.to_glib_none().0)) }
812    }
813
814    // rustdoc-stripper-ignore-next
815    /// Returns a copy of the variant in the opposite endianness.
816    #[doc(alias = "g_variant_byteswap")]
817    #[must_use]
818    pub fn byteswap(&self) -> Self {
819        unsafe { from_glib_full(ffi::g_variant_byteswap(self.to_glib_none().0)) }
820    }
821
822    // rustdoc-stripper-ignore-next
823    /// Determines the number of children in a container GVariant instance.
824    #[doc(alias = "g_variant_n_children")]
825    pub fn n_children(&self) -> usize {
826        assert!(self.is_container());
827
828        unsafe { ffi::g_variant_n_children(self.to_glib_none().0) }
829    }
830
831    // rustdoc-stripper-ignore-next
832    /// Create an iterator over items in the variant.
833    ///
834    /// Note that this heap allocates a variant for each element,
835    /// which can be particularly expensive for large arrays.
836    pub fn iter(&self) -> VariantIter {
837        assert!(self.is_container());
838
839        VariantIter::new(self.clone())
840    }
841
842    // rustdoc-stripper-ignore-next
843    /// Create an iterator over borrowed strings from a GVariant of type `as` (array of string).
844    ///
845    /// This will fail if the variant is not an array of with
846    /// the expected child type.
847    ///
848    /// A benefit of this API over [`Self::iter()`] is that it
849    /// minimizes allocation, and provides strongly typed access.
850    ///
851    /// ```
852    /// # use glib::prelude::*;
853    /// let strs = &["foo", "bar"];
854    /// let strs_variant: glib::Variant = strs.to_variant();
855    /// for s in strs_variant.array_iter_str()? {
856    ///     println!("{}", s);
857    /// }
858    /// # Ok::<(), Box<dyn std::error::Error>>(())
859    /// ```
860    pub fn array_iter_str(&self) -> Result<VariantStrIter<'_>, VariantTypeMismatchError> {
861        let child_ty = String::static_variant_type();
862        let actual_ty = self.type_();
863        let expected_ty = child_ty.as_array();
864        if actual_ty != expected_ty {
865            return Err(VariantTypeMismatchError {
866                actual: actual_ty.to_owned(),
867                expected: expected_ty.into_owned(),
868            });
869        }
870
871        Ok(VariantStrIter::new(self))
872    }
873
874    // rustdoc-stripper-ignore-next
875    /// Return whether this Variant is a container type.
876    #[doc(alias = "g_variant_is_container")]
877    pub fn is_container(&self) -> bool {
878        unsafe { from_glib(ffi::g_variant_is_container(self.to_glib_none().0)) }
879    }
880
881    // rustdoc-stripper-ignore-next
882    /// Return whether this Variant is in normal form.
883    #[doc(alias = "g_variant_is_normal_form")]
884    pub fn is_normal_form(&self) -> bool {
885        unsafe { from_glib(ffi::g_variant_is_normal_form(self.to_glib_none().0)) }
886    }
887
888    // rustdoc-stripper-ignore-next
889    /// Return whether input string is a valid `VariantClass::ObjectPath`.
890    #[doc(alias = "g_variant_is_object_path")]
891    pub fn is_object_path(string: &str) -> bool {
892        unsafe { from_glib(ffi::g_variant_is_object_path(string.to_glib_none().0)) }
893    }
894
895    // rustdoc-stripper-ignore-next
896    /// Return whether input string is a valid `VariantClass::Signature`.
897    #[doc(alias = "g_variant_is_signature")]
898    pub fn is_signature(string: &str) -> bool {
899        unsafe { from_glib(ffi::g_variant_is_signature(string.to_glib_none().0)) }
900    }
901}
902
903unsafe impl Send for Variant {}
904unsafe impl Sync for Variant {}
905
906impl fmt::Debug for Variant {
907    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
908        f.debug_struct("Variant")
909            .field("ptr", &ToGlibPtr::<*const _>::to_glib_none(self).0)
910            .field("type", &self.type_())
911            .field("value", &self.to_string())
912            .finish()
913    }
914}
915
916impl fmt::Display for Variant {
917    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
918        f.write_str(&self.print(true))
919    }
920}
921
922impl str::FromStr for Variant {
923    type Err = crate::Error;
924
925    fn from_str(s: &str) -> Result<Self, Self::Err> {
926        Self::parse(None, s)
927    }
928}
929
930impl PartialEq for Variant {
931    #[doc(alias = "g_variant_equal")]
932    fn eq(&self, other: &Self) -> bool {
933        unsafe {
934            from_glib(ffi::g_variant_equal(
935                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
936                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
937            ))
938        }
939    }
940}
941
942impl Eq for Variant {}
943
944impl PartialOrd for Variant {
945    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
946        unsafe {
947            if ffi::g_variant_classify(self.to_glib_none().0)
948                != ffi::g_variant_classify(other.to_glib_none().0)
949            {
950                return None;
951            }
952
953            if self.is_container() {
954                return None;
955            }
956
957            let res = ffi::g_variant_compare(
958                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
959                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
960            );
961
962            Some(res.cmp(&0))
963        }
964    }
965}
966
967impl Hash for Variant {
968    #[doc(alias = "g_variant_hash")]
969    fn hash<H: Hasher>(&self, state: &mut H) {
970        unsafe {
971            state.write_u32(ffi::g_variant_hash(
972                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
973            ))
974        }
975    }
976}
977
978impl AsRef<Variant> for Variant {
979    #[inline]
980    fn as_ref(&self) -> &Self {
981        self
982    }
983}
984
985// rustdoc-stripper-ignore-next
986/// Converts to `Variant`.
987pub trait ToVariant {
988    // rustdoc-stripper-ignore-next
989    /// Returns a `Variant` clone of `self`.
990    fn to_variant(&self) -> Variant;
991}
992
993// rustdoc-stripper-ignore-next
994/// Extracts a value.
995pub trait FromVariant: Sized + StaticVariantType {
996    // rustdoc-stripper-ignore-next
997    /// Tries to extract a value.
998    ///
999    /// Returns `Some` if the variant's type matches `Self`.
1000    fn from_variant(variant: &Variant) -> Option<Self>;
1001}
1002
1003// rustdoc-stripper-ignore-next
1004/// Returns `VariantType` of `Self`.
1005pub trait StaticVariantType {
1006    // rustdoc-stripper-ignore-next
1007    /// Returns the `VariantType` corresponding to `Self`.
1008    fn static_variant_type() -> Cow<'static, VariantTy>;
1009}
1010
1011impl StaticVariantType for Variant {
1012    fn static_variant_type() -> Cow<'static, VariantTy> {
1013        Cow::Borrowed(VariantTy::VARIANT)
1014    }
1015}
1016
1017impl<T: ?Sized + ToVariant> ToVariant for &T {
1018    fn to_variant(&self) -> Variant {
1019        <T as ToVariant>::to_variant(self)
1020    }
1021}
1022
1023impl<'a, T: Into<Variant> + Clone> From<&'a T> for Variant {
1024    #[inline]
1025    fn from(v: &'a T) -> Self {
1026        v.clone().into()
1027    }
1028}
1029
1030impl<T: ?Sized + StaticVariantType> StaticVariantType for &T {
1031    fn static_variant_type() -> Cow<'static, VariantTy> {
1032        <T as StaticVariantType>::static_variant_type()
1033    }
1034}
1035
1036macro_rules! impl_numeric {
1037    ($name:ty, $typ:expr, $new_fn:ident, $get_fn:ident) => {
1038        impl StaticVariantType for $name {
1039            fn static_variant_type() -> Cow<'static, VariantTy> {
1040                Cow::Borrowed($typ)
1041            }
1042        }
1043
1044        impl ToVariant for $name {
1045            fn to_variant(&self) -> Variant {
1046                unsafe { from_glib_none(ffi::$new_fn(*self)) }
1047            }
1048        }
1049
1050        impl From<$name> for Variant {
1051            #[inline]
1052            fn from(v: $name) -> Self {
1053                v.to_variant()
1054            }
1055        }
1056
1057        impl FromVariant for $name {
1058            fn from_variant(variant: &Variant) -> Option<Self> {
1059                unsafe {
1060                    if variant.is::<Self>() {
1061                        Some(ffi::$get_fn(variant.to_glib_none().0))
1062                    } else {
1063                        None
1064                    }
1065                }
1066            }
1067        }
1068    };
1069}
1070
1071impl_numeric!(u8, VariantTy::BYTE, g_variant_new_byte, g_variant_get_byte);
1072impl_numeric!(
1073    i16,
1074    VariantTy::INT16,
1075    g_variant_new_int16,
1076    g_variant_get_int16
1077);
1078impl_numeric!(
1079    u16,
1080    VariantTy::UINT16,
1081    g_variant_new_uint16,
1082    g_variant_get_uint16
1083);
1084impl_numeric!(
1085    i32,
1086    VariantTy::INT32,
1087    g_variant_new_int32,
1088    g_variant_get_int32
1089);
1090impl_numeric!(
1091    u32,
1092    VariantTy::UINT32,
1093    g_variant_new_uint32,
1094    g_variant_get_uint32
1095);
1096impl_numeric!(
1097    i64,
1098    VariantTy::INT64,
1099    g_variant_new_int64,
1100    g_variant_get_int64
1101);
1102impl_numeric!(
1103    u64,
1104    VariantTy::UINT64,
1105    g_variant_new_uint64,
1106    g_variant_get_uint64
1107);
1108impl_numeric!(
1109    f64,
1110    VariantTy::DOUBLE,
1111    g_variant_new_double,
1112    g_variant_get_double
1113);
1114
1115impl StaticVariantType for () {
1116    fn static_variant_type() -> Cow<'static, VariantTy> {
1117        Cow::Borrowed(VariantTy::UNIT)
1118    }
1119}
1120
1121impl ToVariant for () {
1122    fn to_variant(&self) -> Variant {
1123        unsafe { from_glib_none(ffi::g_variant_new_tuple(ptr::null(), 0)) }
1124    }
1125}
1126
1127impl From<()> for Variant {
1128    #[inline]
1129    fn from(_: ()) -> Self {
1130        ().to_variant()
1131    }
1132}
1133
1134impl FromVariant for () {
1135    fn from_variant(variant: &Variant) -> Option<Self> {
1136        if variant.is::<Self>() { Some(()) } else { None }
1137    }
1138}
1139
1140impl StaticVariantType for bool {
1141    fn static_variant_type() -> Cow<'static, VariantTy> {
1142        Cow::Borrowed(VariantTy::BOOLEAN)
1143    }
1144}
1145
1146impl ToVariant for bool {
1147    fn to_variant(&self) -> Variant {
1148        unsafe { from_glib_none(ffi::g_variant_new_boolean(self.into_glib())) }
1149    }
1150}
1151
1152impl From<bool> for Variant {
1153    #[inline]
1154    fn from(v: bool) -> Self {
1155        v.to_variant()
1156    }
1157}
1158
1159impl FromVariant for bool {
1160    fn from_variant(variant: &Variant) -> Option<Self> {
1161        unsafe {
1162            if variant.is::<Self>() {
1163                Some(from_glib(ffi::g_variant_get_boolean(
1164                    variant.to_glib_none().0,
1165                )))
1166            } else {
1167                None
1168            }
1169        }
1170    }
1171}
1172
1173impl StaticVariantType for String {
1174    fn static_variant_type() -> Cow<'static, VariantTy> {
1175        Cow::Borrowed(VariantTy::STRING)
1176    }
1177}
1178
1179impl ToVariant for String {
1180    fn to_variant(&self) -> Variant {
1181        self[..].to_variant()
1182    }
1183}
1184
1185impl From<String> for Variant {
1186    #[inline]
1187    fn from(s: String) -> Self {
1188        s.to_variant()
1189    }
1190}
1191
1192impl FromVariant for String {
1193    fn from_variant(variant: &Variant) -> Option<Self> {
1194        variant.str().map(String::from)
1195    }
1196}
1197
1198impl StaticVariantType for str {
1199    fn static_variant_type() -> Cow<'static, VariantTy> {
1200        String::static_variant_type()
1201    }
1202}
1203
1204impl ToVariant for str {
1205    fn to_variant(&self) -> Variant {
1206        unsafe { from_glib_none(ffi::g_variant_new_take_string(self.to_glib_full())) }
1207    }
1208}
1209
1210impl From<&str> for Variant {
1211    #[inline]
1212    fn from(s: &str) -> Self {
1213        s.to_variant()
1214    }
1215}
1216
1217impl<'a> StaticVariantType for Cow<'a, str> {
1218    fn static_variant_type() -> Cow<'static, VariantTy> {
1219        String::static_variant_type()
1220    }
1221}
1222
1223impl<'a> FromVariant for Cow<'a, str> {
1224    fn from_variant(variant: &Variant) -> Option<Self> {
1225        String::from_variant(variant).map(Cow::from)
1226    }
1227}
1228
1229impl<'a, B> From<Cow<'a, B>> for Variant
1230where
1231    B: 'a + ToOwned + ?Sized + StaticVariantType + ToVariant,
1232    <B as ToOwned>::Owned: StaticVariantType + ToVariant,
1233{
1234    fn from(s: Cow<'a, B>) -> Self {
1235        match s {
1236            Cow::Borrowed(v) => v.to_variant(),
1237            Cow::Owned(v) => v.to_variant(),
1238        }
1239    }
1240}
1241
1242impl StaticVariantType for std::path::PathBuf {
1243    fn static_variant_type() -> Cow<'static, VariantTy> {
1244        std::path::Path::static_variant_type()
1245    }
1246}
1247
1248impl ToVariant for std::path::PathBuf {
1249    fn to_variant(&self) -> Variant {
1250        self.as_path().to_variant()
1251    }
1252}
1253
1254impl From<std::path::PathBuf> for Variant {
1255    #[inline]
1256    fn from(p: std::path::PathBuf) -> Self {
1257        p.to_variant()
1258    }
1259}
1260
1261impl FromVariant for std::path::PathBuf {
1262    fn from_variant(variant: &Variant) -> Option<Self> {
1263        unsafe {
1264            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
1265            Some(crate::translate::c_to_path_buf(ptr as *const _))
1266        }
1267    }
1268}
1269
1270impl StaticVariantType for std::path::Path {
1271    fn static_variant_type() -> Cow<'static, VariantTy> {
1272        <&[u8]>::static_variant_type()
1273    }
1274}
1275
1276impl ToVariant for std::path::Path {
1277    fn to_variant(&self) -> Variant {
1278        let tmp = crate::translate::path_to_c(self);
1279        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
1280    }
1281}
1282
1283impl From<&std::path::Path> for Variant {
1284    #[inline]
1285    fn from(p: &std::path::Path) -> Self {
1286        p.to_variant()
1287    }
1288}
1289
1290impl StaticVariantType for std::ffi::OsString {
1291    fn static_variant_type() -> Cow<'static, VariantTy> {
1292        std::ffi::OsStr::static_variant_type()
1293    }
1294}
1295
1296impl ToVariant for std::ffi::OsString {
1297    fn to_variant(&self) -> Variant {
1298        self.as_os_str().to_variant()
1299    }
1300}
1301
1302impl From<std::ffi::OsString> for Variant {
1303    #[inline]
1304    fn from(s: std::ffi::OsString) -> Self {
1305        s.to_variant()
1306    }
1307}
1308
1309impl FromVariant for std::ffi::OsString {
1310    fn from_variant(variant: &Variant) -> Option<Self> {
1311        unsafe {
1312            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
1313            Some(crate::translate::c_to_os_string(ptr as *const _))
1314        }
1315    }
1316}
1317
1318impl StaticVariantType for std::ffi::OsStr {
1319    fn static_variant_type() -> Cow<'static, VariantTy> {
1320        <&[u8]>::static_variant_type()
1321    }
1322}
1323
1324impl ToVariant for std::ffi::OsStr {
1325    fn to_variant(&self) -> Variant {
1326        let tmp = crate::translate::os_str_to_c(self);
1327        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
1328    }
1329}
1330
1331impl From<&std::ffi::OsStr> for Variant {
1332    #[inline]
1333    fn from(s: &std::ffi::OsStr) -> Self {
1334        s.to_variant()
1335    }
1336}
1337
1338impl<T: StaticVariantType> StaticVariantType for Option<T> {
1339    fn static_variant_type() -> Cow<'static, VariantTy> {
1340        Cow::Owned(VariantType::new_maybe(&T::static_variant_type()))
1341    }
1342}
1343
1344impl<T: StaticVariantType + ToVariant> ToVariant for Option<T> {
1345    fn to_variant(&self) -> Variant {
1346        Variant::from_maybe::<T>(self.as_ref().map(|m| m.to_variant()).as_ref())
1347    }
1348}
1349
1350impl<T: StaticVariantType + Into<Variant>> From<Option<T>> for Variant {
1351    #[inline]
1352    fn from(v: Option<T>) -> Self {
1353        Variant::from_maybe::<T>(v.map(|v| v.into()).as_ref())
1354    }
1355}
1356
1357impl<T: StaticVariantType + FromVariant> FromVariant for Option<T> {
1358    fn from_variant(variant: &Variant) -> Option<Self> {
1359        unsafe {
1360            if variant.is::<Self>() {
1361                let c_child = ffi::g_variant_get_maybe(variant.to_glib_none().0);
1362                if !c_child.is_null() {
1363                    let child: Variant = from_glib_full(c_child);
1364
1365                    Some(T::from_variant(&child))
1366                } else {
1367                    Some(None)
1368                }
1369            } else {
1370                None
1371            }
1372        }
1373    }
1374}
1375
1376impl<T: StaticVariantType> StaticVariantType for [T] {
1377    fn static_variant_type() -> Cow<'static, VariantTy> {
1378        T::static_variant_type().as_array()
1379    }
1380}
1381
1382impl<T: StaticVariantType + ToVariant> ToVariant for [T] {
1383    fn to_variant(&self) -> Variant {
1384        unsafe {
1385            if self.is_empty() {
1386                return from_glib_none(ffi::g_variant_new_array(
1387                    T::static_variant_type().to_glib_none().0,
1388                    ptr::null(),
1389                    0,
1390                ));
1391            }
1392
1393            let mut builder = mem::MaybeUninit::uninit();
1394            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1395            let mut builder = builder.assume_init();
1396            for value in self {
1397                let value = value.to_variant();
1398                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
1399            }
1400            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1401        }
1402    }
1403}
1404
1405impl<T: StaticVariantType + ToVariant> From<&[T]> for Variant {
1406    #[inline]
1407    fn from(s: &[T]) -> Self {
1408        s.to_variant()
1409    }
1410}
1411
1412impl<T: FromVariant> FromVariant for Vec<T> {
1413    fn from_variant(variant: &Variant) -> Option<Self> {
1414        if !variant.is_container() {
1415            return None;
1416        }
1417
1418        let mut vec = Vec::with_capacity(variant.n_children());
1419
1420        for i in 0..variant.n_children() {
1421            let child = variant.child_value(i).get()?;
1422            vec.push(child)
1423        }
1424
1425        Some(vec)
1426    }
1427}
1428
1429impl<T: StaticVariantType + ToVariant> ToVariant for Vec<T> {
1430    fn to_variant(&self) -> Variant {
1431        self.as_slice().to_variant()
1432    }
1433}
1434
1435impl<T: StaticVariantType + Into<Variant>> From<Vec<T>> for Variant {
1436    fn from(v: Vec<T>) -> Self {
1437        unsafe {
1438            if v.is_empty() {
1439                return from_glib_none(ffi::g_variant_new_array(
1440                    T::static_variant_type().to_glib_none().0,
1441                    ptr::null(),
1442                    0,
1443                ));
1444            }
1445
1446            let mut builder = mem::MaybeUninit::uninit();
1447            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1448            let mut builder = builder.assume_init();
1449            for value in v {
1450                let value = value.into();
1451                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
1452            }
1453            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1454        }
1455    }
1456}
1457
1458impl<T: StaticVariantType> StaticVariantType for Vec<T> {
1459    fn static_variant_type() -> Cow<'static, VariantTy> {
1460        <[T]>::static_variant_type()
1461    }
1462}
1463
1464impl<K, V, H> FromVariant for HashMap<K, V, H>
1465where
1466    K: FromVariant + Eq + Hash,
1467    V: FromVariant,
1468    H: BuildHasher + Default,
1469{
1470    fn from_variant(variant: &Variant) -> Option<Self> {
1471        if !variant.is_container() {
1472            return None;
1473        }
1474
1475        let mut map = HashMap::default();
1476
1477        for i in 0..variant.n_children() {
1478            let entry = variant.child_value(i);
1479            let key = entry.child_value(0).get()?;
1480            let val = entry.child_value(1).get()?;
1481
1482            map.insert(key, val);
1483        }
1484
1485        Some(map)
1486    }
1487}
1488
1489impl<K, V> FromVariant for BTreeMap<K, V>
1490where
1491    K: FromVariant + Eq + Ord,
1492    V: FromVariant,
1493{
1494    fn from_variant(variant: &Variant) -> Option<Self> {
1495        if !variant.is_container() {
1496            return None;
1497        }
1498
1499        let mut map = BTreeMap::default();
1500
1501        for i in 0..variant.n_children() {
1502            let entry = variant.child_value(i);
1503            let key = entry.child_value(0).get()?;
1504            let val = entry.child_value(1).get()?;
1505
1506            map.insert(key, val);
1507        }
1508
1509        Some(map)
1510    }
1511}
1512
1513impl<K, V> ToVariant for HashMap<K, V>
1514where
1515    K: StaticVariantType + ToVariant + Eq + Hash,
1516    V: StaticVariantType + ToVariant,
1517{
1518    fn to_variant(&self) -> Variant {
1519        unsafe {
1520            if self.is_empty() {
1521                return from_glib_none(ffi::g_variant_new_array(
1522                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
1523                    ptr::null(),
1524                    0,
1525                ));
1526            }
1527
1528            let mut builder = mem::MaybeUninit::uninit();
1529            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1530            let mut builder = builder.assume_init();
1531            for (key, value) in self {
1532                let entry = DictEntry::new(key, value).to_variant();
1533                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
1534            }
1535            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1536        }
1537    }
1538}
1539
1540impl<K, V> From<HashMap<K, V>> for Variant
1541where
1542    K: StaticVariantType + Into<Variant> + Eq + Hash,
1543    V: StaticVariantType + Into<Variant>,
1544{
1545    fn from(m: HashMap<K, V>) -> Self {
1546        unsafe {
1547            if m.is_empty() {
1548                return from_glib_none(ffi::g_variant_new_array(
1549                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
1550                    ptr::null(),
1551                    0,
1552                ));
1553            }
1554
1555            let mut builder = mem::MaybeUninit::uninit();
1556            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1557            let mut builder = builder.assume_init();
1558            for (key, value) in m {
1559                let entry = Variant::from(DictEntry::new(key, value));
1560                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
1561            }
1562            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1563        }
1564    }
1565}
1566
1567impl<K, V> ToVariant for BTreeMap<K, V>
1568where
1569    K: StaticVariantType + ToVariant + Eq + Hash,
1570    V: StaticVariantType + ToVariant,
1571{
1572    fn to_variant(&self) -> Variant {
1573        unsafe {
1574            if self.is_empty() {
1575                return from_glib_none(ffi::g_variant_new_array(
1576                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
1577                    ptr::null(),
1578                    0,
1579                ));
1580            }
1581
1582            let mut builder = mem::MaybeUninit::uninit();
1583            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1584            let mut builder = builder.assume_init();
1585            for (key, value) in self {
1586                let entry = DictEntry::new(key, value).to_variant();
1587                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
1588            }
1589            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1590        }
1591    }
1592}
1593
1594impl<K, V> From<BTreeMap<K, V>> for Variant
1595where
1596    K: StaticVariantType + Into<Variant> + Eq + Hash,
1597    V: StaticVariantType + Into<Variant>,
1598{
1599    fn from(m: BTreeMap<K, V>) -> Self {
1600        unsafe {
1601            if m.is_empty() {
1602                return from_glib_none(ffi::g_variant_new_array(
1603                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
1604                    ptr::null(),
1605                    0,
1606                ));
1607            }
1608
1609            let mut builder = mem::MaybeUninit::uninit();
1610            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1611            let mut builder = builder.assume_init();
1612            for (key, value) in m {
1613                let entry = Variant::from(DictEntry::new(key, value));
1614                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
1615            }
1616            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1617        }
1618    }
1619}
1620
1621/// A Dictionary entry.
1622///
1623/// While GVariant format allows a dictionary entry to be an independent type, typically you'll need
1624/// to use this in a dictionary, which is simply an array of dictionary entries. The following code
1625/// creates a dictionary:
1626///
1627/// ```
1628///# use glib::prelude::*; // or `use gtk::prelude::*;`
1629/// use glib::variant::{Variant, FromVariant, DictEntry};
1630///
1631/// let entries = [
1632///     DictEntry::new("uuid", 1000u32),
1633///     DictEntry::new("guid", 1001u32),
1634/// ];
1635/// let dict = entries.into_iter().collect::<Variant>();
1636/// assert_eq!(dict.n_children(), 2);
1637/// assert_eq!(dict.type_().as_str(), "a{su}");
1638/// ```
1639#[derive(Debug, Clone)]
1640pub struct DictEntry<K, V> {
1641    key: K,
1642    value: V,
1643}
1644
1645impl<K, V> DictEntry<K, V>
1646where
1647    K: StaticVariantType,
1648    V: StaticVariantType,
1649{
1650    pub fn new(key: K, value: V) -> Self {
1651        Self { key, value }
1652    }
1653
1654    pub fn key(&self) -> &K {
1655        &self.key
1656    }
1657
1658    pub fn value(&self) -> &V {
1659        &self.value
1660    }
1661}
1662
1663impl<K, V> FromVariant for DictEntry<K, V>
1664where
1665    K: FromVariant,
1666    V: FromVariant,
1667{
1668    fn from_variant(variant: &Variant) -> Option<Self> {
1669        if !variant.type_().is_subtype_of(VariantTy::DICT_ENTRY) {
1670            return None;
1671        }
1672
1673        let key = variant.child_value(0).get()?;
1674        let value = variant.child_value(1).get()?;
1675
1676        Some(Self { key, value })
1677    }
1678}
1679
1680impl<K, V> ToVariant for DictEntry<K, V>
1681where
1682    K: StaticVariantType + ToVariant,
1683    V: StaticVariantType + ToVariant,
1684{
1685    fn to_variant(&self) -> Variant {
1686        Variant::from_dict_entry(&self.key.to_variant(), &self.value.to_variant())
1687    }
1688}
1689
1690impl<K, V> From<DictEntry<K, V>> for Variant
1691where
1692    K: StaticVariantType + Into<Variant>,
1693    V: StaticVariantType + Into<Variant>,
1694{
1695    fn from(e: DictEntry<K, V>) -> Self {
1696        Variant::from_dict_entry(&e.key.into(), &e.value.into())
1697    }
1698}
1699
1700impl ToVariant for Variant {
1701    fn to_variant(&self) -> Variant {
1702        Variant::from_variant(self)
1703    }
1704}
1705
1706impl FromVariant for Variant {
1707    fn from_variant(variant: &Variant) -> Option<Self> {
1708        variant.as_variant()
1709    }
1710}
1711
1712impl<K: StaticVariantType, V: StaticVariantType> StaticVariantType for DictEntry<K, V> {
1713    fn static_variant_type() -> Cow<'static, VariantTy> {
1714        Cow::Owned(VariantType::new_dict_entry(
1715            &K::static_variant_type(),
1716            &V::static_variant_type(),
1717        ))
1718    }
1719}
1720
1721fn static_variant_mapping<K, V>() -> Cow<'static, VariantTy>
1722where
1723    K: StaticVariantType,
1724    V: StaticVariantType,
1725{
1726    use std::fmt::Write;
1727
1728    let key_type = K::static_variant_type();
1729    let value_type = V::static_variant_type();
1730
1731    if key_type == VariantTy::STRING && value_type == VariantTy::VARIANT {
1732        return Cow::Borrowed(VariantTy::VARDICT);
1733    }
1734
1735    let mut builder = crate::GStringBuilder::default();
1736    write!(builder, "a{{{}{}}}", key_type.as_str(), value_type.as_str()).unwrap();
1737
1738    Cow::Owned(VariantType::from_string(builder.into_string()).unwrap())
1739}
1740
1741impl<K, V, H> StaticVariantType for HashMap<K, V, H>
1742where
1743    K: StaticVariantType,
1744    V: StaticVariantType,
1745    H: BuildHasher + Default,
1746{
1747    fn static_variant_type() -> Cow<'static, VariantTy> {
1748        static_variant_mapping::<K, V>()
1749    }
1750}
1751
1752impl<K, V> StaticVariantType for BTreeMap<K, V>
1753where
1754    K: StaticVariantType,
1755    V: StaticVariantType,
1756{
1757    fn static_variant_type() -> Cow<'static, VariantTy> {
1758        static_variant_mapping::<K, V>()
1759    }
1760}
1761
1762macro_rules! tuple_impls {
1763    ($($len:expr => ($($n:tt $name:ident)+))+) => {
1764        $(
1765            impl<$($name),+> StaticVariantType for ($($name,)+)
1766            where
1767                $($name: StaticVariantType,)+
1768            {
1769                fn static_variant_type() -> Cow<'static, VariantTy> {
1770                    Cow::Owned(VariantType::new_tuple(&[
1771                        $(
1772                            $name::static_variant_type(),
1773                        )+
1774                    ]))
1775                }
1776            }
1777
1778            impl<$($name),+> FromVariant for ($($name,)+)
1779            where
1780                $($name: FromVariant,)+
1781            {
1782                fn from_variant(variant: &Variant) -> Option<Self> {
1783                    if !variant.type_().is_subtype_of(VariantTy::TUPLE) {
1784                        return None;
1785                    }
1786
1787                    Some((
1788                        $(
1789                            match variant.try_child_get::<$name>($n) {
1790                                Ok(Some(field)) => field,
1791                                _ => return None,
1792                            },
1793                        )+
1794                    ))
1795                }
1796            }
1797
1798            impl<$($name),+> ToVariant for ($($name,)+)
1799            where
1800                $($name: ToVariant,)+
1801            {
1802                fn to_variant(&self) -> Variant {
1803                    unsafe {
1804                        let mut builder = mem::MaybeUninit::uninit();
1805                        ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
1806                        let mut builder = builder.assume_init();
1807
1808                        $(
1809                            let field = self.$n.to_variant();
1810                            ffi::g_variant_builder_add_value(&mut builder, field.to_glib_none().0);
1811                        )+
1812
1813                        from_glib_none(ffi::g_variant_builder_end(&mut builder))
1814                    }
1815                }
1816            }
1817
1818            impl<$($name),+> From<($($name,)+)> for Variant
1819            where
1820                $($name: Into<Variant>,)+
1821            {
1822                fn from(t: ($($name,)+)) -> Self {
1823                    unsafe {
1824                        let mut builder = mem::MaybeUninit::uninit();
1825                        ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
1826                        let mut builder = builder.assume_init();
1827
1828                        $(
1829                            let field = t.$n.into();
1830                            ffi::g_variant_builder_add_value(&mut builder, field.to_glib_none().0);
1831                        )+
1832
1833                        from_glib_none(ffi::g_variant_builder_end(&mut builder))
1834                    }
1835                }
1836            }
1837        )+
1838    }
1839}
1840
1841tuple_impls! {
1842    1 => (0 T0)
1843    2 => (0 T0 1 T1)
1844    3 => (0 T0 1 T1 2 T2)
1845    4 => (0 T0 1 T1 2 T2 3 T3)
1846    5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
1847    6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
1848    7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
1849    8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
1850    9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
1851    10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
1852    11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
1853    12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
1854    13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
1855    14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
1856    15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
1857    16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
1858}
1859
1860impl<T: Into<Variant> + StaticVariantType> FromIterator<T> for Variant {
1861    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1862        Variant::array_from_iter::<T>(iter.into_iter().map(|v| v.into()))
1863    }
1864}
1865
1866/// Trait for fixed size variant types.
1867pub unsafe trait FixedSizeVariantType: StaticVariantType + Sized + Copy {}
1868unsafe impl FixedSizeVariantType for u8 {}
1869unsafe impl FixedSizeVariantType for i16 {}
1870unsafe impl FixedSizeVariantType for u16 {}
1871unsafe impl FixedSizeVariantType for i32 {}
1872unsafe impl FixedSizeVariantType for u32 {}
1873unsafe impl FixedSizeVariantType for i64 {}
1874unsafe impl FixedSizeVariantType for u64 {}
1875unsafe impl FixedSizeVariantType for f64 {}
1876unsafe impl FixedSizeVariantType for bool {}
1877
1878/// Wrapper type for fixed size type arrays.
1879///
1880/// Converting this from/to a `Variant` is generally more efficient than working on the type
1881/// directly. This is especially important when deriving `Variant` trait implementations on custom
1882/// types.
1883///
1884/// This wrapper type can hold for example `Vec<u8>`, `Box<[u8]>` and similar types.
1885#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1886pub struct FixedSizeVariantArray<A, T>(A, std::marker::PhantomData<T>)
1887where
1888    A: AsRef<[T]>,
1889    T: FixedSizeVariantType;
1890
1891impl<A: AsRef<[T]>, T: FixedSizeVariantType> From<A> for FixedSizeVariantArray<A, T> {
1892    fn from(array: A) -> Self {
1893        FixedSizeVariantArray(array, std::marker::PhantomData)
1894    }
1895}
1896
1897impl<A: AsRef<[T]>, T: FixedSizeVariantType> FixedSizeVariantArray<A, T> {
1898    pub fn into_inner(self) -> A {
1899        self.0
1900    }
1901}
1902
1903impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::Deref for FixedSizeVariantArray<A, T> {
1904    type Target = A;
1905
1906    #[inline]
1907    fn deref(&self) -> &Self::Target {
1908        &self.0
1909    }
1910}
1911
1912impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::DerefMut for FixedSizeVariantArray<A, T> {
1913    #[inline]
1914    fn deref_mut(&mut self) -> &mut Self::Target {
1915        &mut self.0
1916    }
1917}
1918
1919impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<A> for FixedSizeVariantArray<A, T> {
1920    #[inline]
1921    fn as_ref(&self) -> &A {
1922        &self.0
1923    }
1924}
1925
1926impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsMut<A> for FixedSizeVariantArray<A, T> {
1927    #[inline]
1928    fn as_mut(&mut self) -> &mut A {
1929        &mut self.0
1930    }
1931}
1932
1933impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<[T]> for FixedSizeVariantArray<A, T> {
1934    #[inline]
1935    fn as_ref(&self) -> &[T] {
1936        self.0.as_ref()
1937    }
1938}
1939
1940impl<A: AsRef<[T]> + AsMut<[T]>, T: FixedSizeVariantType> AsMut<[T]>
1941    for FixedSizeVariantArray<A, T>
1942{
1943    #[inline]
1944    fn as_mut(&mut self) -> &mut [T] {
1945        self.0.as_mut()
1946    }
1947}
1948
1949impl<A: AsRef<[T]>, T: FixedSizeVariantType> StaticVariantType for FixedSizeVariantArray<A, T> {
1950    fn static_variant_type() -> Cow<'static, VariantTy> {
1951        <[T]>::static_variant_type()
1952    }
1953}
1954
1955impl<A: AsRef<[T]> + for<'a> From<&'a [T]>, T: FixedSizeVariantType> FromVariant
1956    for FixedSizeVariantArray<A, T>
1957{
1958    fn from_variant(variant: &Variant) -> Option<Self> {
1959        Some(FixedSizeVariantArray(
1960            A::from(variant.fixed_array::<T>().ok()?),
1961            std::marker::PhantomData,
1962        ))
1963    }
1964}
1965
1966impl<A: AsRef<[T]>, T: FixedSizeVariantType> ToVariant for FixedSizeVariantArray<A, T> {
1967    fn to_variant(&self) -> Variant {
1968        Variant::array_from_fixed_array(self.0.as_ref())
1969    }
1970}
1971
1972impl<A: AsRef<[T]>, T: FixedSizeVariantType> From<FixedSizeVariantArray<A, T>> for Variant {
1973    #[doc(alias = "g_variant_new_from_data")]
1974    fn from(a: FixedSizeVariantArray<A, T>) -> Self {
1975        unsafe {
1976            let data = Box::new(a.0);
1977            let (data_ptr, len) = {
1978                let data = (*data).as_ref();
1979                (data.as_ptr(), mem::size_of_val(data))
1980            };
1981
1982            unsafe extern "C" fn free_data<A: AsRef<[T]>, T: FixedSizeVariantType>(
1983                ptr: ffi::gpointer,
1984            ) {
1985                unsafe {
1986                    let _ = Box::from_raw(ptr as *mut A);
1987                }
1988            }
1989
1990            from_glib_none(ffi::g_variant_new_from_data(
1991                T::static_variant_type().to_glib_none().0,
1992                data_ptr as ffi::gconstpointer,
1993                len,
1994                false.into_glib(),
1995                Some(free_data::<A, T>),
1996                Box::into_raw(data) as ffi::gpointer,
1997            ))
1998        }
1999    }
2000}
2001
2002/// A wrapper type around `Variant` handles.
2003#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2004pub struct Handle(pub i32);
2005
2006impl From<i32> for Handle {
2007    fn from(v: i32) -> Self {
2008        Handle(v)
2009    }
2010}
2011
2012impl From<Handle> for i32 {
2013    fn from(v: Handle) -> Self {
2014        v.0
2015    }
2016}
2017
2018impl StaticVariantType for Handle {
2019    fn static_variant_type() -> Cow<'static, VariantTy> {
2020        Cow::Borrowed(VariantTy::HANDLE)
2021    }
2022}
2023
2024impl ToVariant for Handle {
2025    fn to_variant(&self) -> Variant {
2026        unsafe { from_glib_none(ffi::g_variant_new_handle(self.0)) }
2027    }
2028}
2029
2030impl From<Handle> for Variant {
2031    #[inline]
2032    fn from(h: Handle) -> Self {
2033        h.to_variant()
2034    }
2035}
2036
2037impl FromVariant for Handle {
2038    fn from_variant(variant: &Variant) -> Option<Self> {
2039        unsafe {
2040            if variant.is::<Self>() {
2041                Some(Handle(ffi::g_variant_get_handle(variant.to_glib_none().0)))
2042            } else {
2043                None
2044            }
2045        }
2046    }
2047}
2048
2049/// A wrapper type around `Variant` object paths.
2050///
2051/// Values of these type are guaranteed to be valid object paths.
2052#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2053pub struct ObjectPath(String);
2054
2055impl ObjectPath {
2056    pub fn as_str(&self) -> &str {
2057        &self.0
2058    }
2059}
2060
2061impl Display for ObjectPath {
2062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2063        self.0.fmt(f)
2064    }
2065}
2066
2067impl std::ops::Deref for ObjectPath {
2068    type Target = str;
2069
2070    #[inline]
2071    fn deref(&self) -> &Self::Target {
2072        &self.0
2073    }
2074}
2075
2076impl TryFrom<String> for ObjectPath {
2077    type Error = crate::BoolError;
2078
2079    fn try_from(v: String) -> Result<Self, Self::Error> {
2080        if !Variant::is_object_path(&v) {
2081            return Err(bool_error!("Invalid object path"));
2082        }
2083
2084        Ok(ObjectPath(v))
2085    }
2086}
2087
2088impl<'a> TryFrom<&'a str> for ObjectPath {
2089    type Error = crate::BoolError;
2090
2091    fn try_from(v: &'a str) -> Result<Self, Self::Error> {
2092        ObjectPath::try_from(String::from(v))
2093    }
2094}
2095
2096impl From<ObjectPath> for String {
2097    fn from(v: ObjectPath) -> Self {
2098        v.0
2099    }
2100}
2101
2102impl StaticVariantType for ObjectPath {
2103    fn static_variant_type() -> Cow<'static, VariantTy> {
2104        Cow::Borrowed(VariantTy::OBJECT_PATH)
2105    }
2106}
2107
2108impl ToVariant for ObjectPath {
2109    fn to_variant(&self) -> Variant {
2110        unsafe { from_glib_none(ffi::g_variant_new_object_path(self.0.to_glib_none().0)) }
2111    }
2112}
2113
2114impl From<ObjectPath> for Variant {
2115    #[inline]
2116    fn from(p: ObjectPath) -> Self {
2117        let mut s = p.0;
2118        s.push('\0');
2119        unsafe { Self::from_data_trusted::<ObjectPath, _>(s) }
2120    }
2121}
2122
2123impl FromVariant for ObjectPath {
2124    #[allow(unused_unsafe)]
2125    fn from_variant(variant: &Variant) -> Option<Self> {
2126        unsafe {
2127            if variant.is::<Self>() {
2128                Some(ObjectPath(String::from(variant.str().unwrap())))
2129            } else {
2130                None
2131            }
2132        }
2133    }
2134}
2135
2136/// A wrapper type around `Variant` signatures.
2137///
2138/// Values of these type are guaranteed to be valid signatures.
2139#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2140pub struct Signature(String);
2141
2142impl Signature {
2143    pub fn as_str(&self) -> &str {
2144        &self.0
2145    }
2146}
2147
2148impl std::ops::Deref for Signature {
2149    type Target = str;
2150
2151    #[inline]
2152    fn deref(&self) -> &Self::Target {
2153        &self.0
2154    }
2155}
2156
2157impl TryFrom<String> for Signature {
2158    type Error = crate::BoolError;
2159
2160    fn try_from(v: String) -> Result<Self, Self::Error> {
2161        if !Variant::is_signature(&v) {
2162            return Err(bool_error!("Invalid signature"));
2163        }
2164
2165        Ok(Signature(v))
2166    }
2167}
2168
2169impl<'a> TryFrom<&'a str> for Signature {
2170    type Error = crate::BoolError;
2171
2172    fn try_from(v: &'a str) -> Result<Self, Self::Error> {
2173        Signature::try_from(String::from(v))
2174    }
2175}
2176
2177impl From<Signature> for String {
2178    fn from(v: Signature) -> Self {
2179        v.0
2180    }
2181}
2182
2183impl StaticVariantType for Signature {
2184    fn static_variant_type() -> Cow<'static, VariantTy> {
2185        Cow::Borrowed(VariantTy::SIGNATURE)
2186    }
2187}
2188
2189impl ToVariant for Signature {
2190    fn to_variant(&self) -> Variant {
2191        unsafe { from_glib_none(ffi::g_variant_new_signature(self.0.to_glib_none().0)) }
2192    }
2193}
2194
2195impl From<Signature> for Variant {
2196    #[inline]
2197    fn from(s: Signature) -> Self {
2198        let mut s = s.0;
2199        s.push('\0');
2200        unsafe { Self::from_data_trusted::<Signature, _>(s) }
2201    }
2202}
2203
2204impl FromVariant for Signature {
2205    #[allow(unused_unsafe)]
2206    fn from_variant(variant: &Variant) -> Option<Self> {
2207        unsafe {
2208            if variant.is::<Self>() {
2209                Some(Signature(String::from(variant.str().unwrap())))
2210            } else {
2211                None
2212            }
2213        }
2214    }
2215}
2216
2217#[cfg(test)]
2218mod tests {
2219    use std::collections::{HashMap, HashSet};
2220
2221    use super::*;
2222
2223    macro_rules! unsigned {
2224        ($name:ident, $ty:ident) => {
2225            #[test]
2226            fn $name() {
2227                let mut n = $ty::MAX;
2228                while n > 0 {
2229                    let v = n.to_variant();
2230                    assert_eq!(v.get(), Some(n));
2231                    n /= 2;
2232                }
2233            }
2234        };
2235    }
2236
2237    macro_rules! signed {
2238        ($name:ident, $ty:ident) => {
2239            #[test]
2240            fn $name() {
2241                let mut n = $ty::MAX;
2242                while n > 0 {
2243                    let v = n.to_variant();
2244                    assert_eq!(v.get(), Some(n));
2245                    let v = (-n).to_variant();
2246                    assert_eq!(v.get(), Some(-n));
2247                    n /= 2;
2248                }
2249            }
2250        };
2251    }
2252
2253    unsigned!(test_u8, u8);
2254    unsigned!(test_u16, u16);
2255    unsigned!(test_u32, u32);
2256    unsigned!(test_u64, u64);
2257    signed!(test_i16, i16);
2258    signed!(test_i32, i32);
2259    signed!(test_i64, i64);
2260
2261    #[test]
2262    fn test_str() {
2263        let s = "this is a test";
2264        let v = s.to_variant();
2265        assert_eq!(v.str(), Some(s));
2266        assert_eq!(42u32.to_variant().str(), None);
2267    }
2268
2269    #[test]
2270    fn test_fixed_array() {
2271        let b = b"this is a test";
2272        let v = Variant::array_from_fixed_array(&b[..]);
2273        assert_eq!(v.type_().as_str(), "ay");
2274        assert_eq!(v.fixed_array::<u8>().unwrap(), b);
2275        assert!(42u32.to_variant().fixed_array::<u8>().is_err());
2276
2277        let b = [1u32, 10u32, 100u32];
2278        let v = Variant::array_from_fixed_array(&b);
2279        assert_eq!(v.type_().as_str(), "au");
2280        assert_eq!(v.fixed_array::<u32>().unwrap(), b);
2281        assert!(v.fixed_array::<u8>().is_err());
2282
2283        let b = [true, false, true];
2284        let v = Variant::array_from_fixed_array(&b);
2285        assert_eq!(v.type_().as_str(), "ab");
2286        assert_eq!(v.fixed_array::<bool>().unwrap(), b);
2287        assert!(v.fixed_array::<u8>().is_err());
2288
2289        let b = [1.0f64, 2.0f64, 3.0f64];
2290        let v = Variant::array_from_fixed_array(&b);
2291        assert_eq!(v.type_().as_str(), "ad");
2292        #[allow(clippy::float_cmp)]
2293        {
2294            assert_eq!(v.fixed_array::<f64>().unwrap(), b);
2295        }
2296        assert!(v.fixed_array::<u64>().is_err());
2297    }
2298
2299    #[test]
2300    fn test_fixed_variant_array() {
2301        let b = FixedSizeVariantArray::from(&b"this is a test"[..]);
2302        let v = b.to_variant();
2303        assert_eq!(v.type_().as_str(), "ay");
2304        assert_eq!(
2305            &*v.get::<FixedSizeVariantArray<Vec<u8>, u8>>().unwrap(),
2306            &*b
2307        );
2308
2309        let b = FixedSizeVariantArray::from(vec![1i32, 2, 3]);
2310        let v = b.to_variant();
2311        assert_eq!(v.type_().as_str(), "ai");
2312        assert_eq!(v.get::<FixedSizeVariantArray<Vec<i32>, i32>>().unwrap(), b);
2313    }
2314
2315    #[test]
2316    fn test_string() {
2317        let s = String::from("this is a test");
2318        let v = s.to_variant();
2319        assert_eq!(v.get(), Some(s));
2320        assert_eq!(v.normal_form(), v);
2321    }
2322
2323    #[test]
2324    fn test_cow_string() {
2325        let s = Cow::from(String::from("this is a test"));
2326        let v = s.to_variant();
2327        assert_eq!(v.get(), Some(s));
2328        assert_eq!(v.normal_form(), v);
2329    }
2330
2331    #[test]
2332    fn test_cow_str() {
2333        let s = String::from("this is a test");
2334        let b = Cow::from(&s);
2335        let v = b.to_variant();
2336        assert_eq!(v.get(), Some(s));
2337        assert_eq!(v.normal_form(), v);
2338    }
2339
2340    #[test]
2341    fn test_eq() {
2342        let v1 = "this is a test".to_variant();
2343        let v2 = "this is a test".to_variant();
2344        let v3 = "test".to_variant();
2345        assert_eq!(v1, v2);
2346        assert_ne!(v1, v3);
2347    }
2348
2349    #[test]
2350    fn test_hash() {
2351        let v1 = "this is a test".to_variant();
2352        let v2 = "this is a test".to_variant();
2353        let v3 = "test".to_variant();
2354        let mut set = HashSet::new();
2355        set.insert(v1);
2356        assert!(set.contains(&v2));
2357        assert!(!set.contains(&v3));
2358
2359        assert_eq!(
2360            <HashMap<&str, (&str, u8, u32)>>::static_variant_type().as_str(),
2361            "a{s(syu)}"
2362        );
2363    }
2364
2365    #[test]
2366    fn test_array() {
2367        assert_eq!(<Vec<&str>>::static_variant_type().as_str(), "as");
2368        assert_eq!(
2369            <Vec<(&str, u8, u32)>>::static_variant_type().as_str(),
2370            "a(syu)"
2371        );
2372        let a = ["foo", "bar", "baz"].to_variant();
2373        assert_eq!(a.normal_form(), a);
2374        assert_eq!(a.array_iter_str().unwrap().len(), 3);
2375        let o = 0u32.to_variant();
2376        assert!(o.array_iter_str().is_err());
2377    }
2378
2379    #[test]
2380    fn test_array_from_iter() {
2381        let a = Variant::array_from_iter::<String>(
2382            ["foo", "bar", "baz"].into_iter().map(|s| s.to_variant()),
2383        );
2384        assert_eq!(a.type_().as_str(), "as");
2385        assert_eq!(a.n_children(), 3);
2386
2387        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2388        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
2389        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
2390    }
2391
2392    #[test]
2393    fn test_array_collect() {
2394        let a = ["foo", "bar", "baz"].into_iter().collect::<Variant>();
2395        assert_eq!(a.type_().as_str(), "as");
2396        assert_eq!(a.n_children(), 3);
2397
2398        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2399        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
2400        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
2401    }
2402
2403    #[test]
2404    fn test_tuple() {
2405        assert_eq!(<(&str, u32)>::static_variant_type().as_str(), "(su)");
2406        assert_eq!(<(&str, u8, u32)>::static_variant_type().as_str(), "(syu)");
2407        let a = ("test", 1u8, 2u32).to_variant();
2408        assert_eq!(a.normal_form(), a);
2409        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("test"))));
2410        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
2411        assert_eq!(a.try_child_get::<u32>(2), Ok(Some(2u32)));
2412        assert_eq!(
2413            a.try_get::<(String, u8, u32)>(),
2414            Ok((String::from("test"), 1u8, 2u32))
2415        );
2416    }
2417
2418    #[test]
2419    fn test_tuple_from_iter() {
2420        let a = Variant::tuple_from_iter(["foo".to_variant(), 1u8.to_variant(), 2i32.to_variant()]);
2421        assert_eq!(a.type_().as_str(), "(syi)");
2422        assert_eq!(a.n_children(), 3);
2423
2424        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2425        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
2426        assert_eq!(a.try_child_get::<i32>(2), Ok(Some(2i32)));
2427    }
2428
2429    #[test]
2430    fn test_empty() {
2431        assert_eq!(<()>::static_variant_type().as_str(), "()");
2432        let a = ().to_variant();
2433        assert_eq!(a.type_().as_str(), "()");
2434        assert_eq!(a.get::<()>(), Some(()));
2435    }
2436
2437    #[test]
2438    fn test_maybe() {
2439        assert!(<Option<()>>::static_variant_type().is_maybe());
2440        let m1 = Some(()).to_variant();
2441        assert_eq!(m1.type_().as_str(), "m()");
2442
2443        assert_eq!(m1.get::<Option<()>>(), Some(Some(())));
2444        assert!(m1.as_maybe().is_some());
2445
2446        let m2 = None::<()>.to_variant();
2447        assert!(m2.as_maybe().is_none());
2448    }
2449
2450    #[test]
2451    fn test_btreemap() {
2452        assert_eq!(
2453            <BTreeMap<String, u32>>::static_variant_type().as_str(),
2454            "a{su}"
2455        );
2456        // Validate that BTreeMap adds entries to dict in sorted order
2457        let mut m = BTreeMap::new();
2458        let total = 20;
2459        for n in 0..total {
2460            let k = format!("v{n:04}");
2461            m.insert(k, n as u32);
2462        }
2463        let v = m.to_variant();
2464        let n = v.n_children();
2465        assert_eq!(total, n);
2466        for n in 0..total {
2467            let child = v
2468                .try_child_get::<DictEntry<String, u32>>(n)
2469                .unwrap()
2470                .unwrap();
2471            assert_eq!(*child.value(), n as u32);
2472        }
2473
2474        assert_eq!(BTreeMap::from_variant(&v).unwrap(), m);
2475    }
2476
2477    #[test]
2478    fn test_get() -> Result<(), Box<dyn std::error::Error>> {
2479        let u = 42u32.to_variant();
2480        assert!(u.get::<i32>().is_none());
2481        assert_eq!(u.get::<u32>().unwrap(), 42);
2482        assert!(u.try_get::<i32>().is_err());
2483        // Test ? conversion
2484        assert_eq!(u.try_get::<u32>()?, 42);
2485        Ok(())
2486    }
2487
2488    #[test]
2489    fn test_byteswap() {
2490        let u = 42u32.to_variant();
2491        assert_eq!(u.byteswap().get::<u32>().unwrap(), 704643072u32);
2492        assert_eq!(u.byteswap().byteswap().get::<u32>().unwrap(), 42u32);
2493    }
2494
2495    #[test]
2496    fn test_try_child() {
2497        let a = ["foo"].to_variant();
2498        assert!(a.try_child_value(0).is_some());
2499        assert_eq!(a.try_child_get::<String>(0).unwrap().unwrap(), "foo");
2500        assert_eq!(a.child_get::<String>(0), "foo");
2501        assert!(a.try_child_get::<u32>(0).is_err());
2502        assert!(a.try_child_value(1).is_none());
2503        assert!(a.try_child_get::<String>(1).unwrap().is_none());
2504        let u = 42u32.to_variant();
2505        assert!(u.try_child_value(0).is_none());
2506        assert!(u.try_child_get::<String>(0).unwrap().is_none());
2507    }
2508
2509    #[test]
2510    fn test_serialize() {
2511        let a = ("test", 1u8, 2u32).to_variant();
2512
2513        let bytes = a.data_as_bytes();
2514        let data = a.data();
2515        let len = a.size();
2516        assert_eq!(bytes.len(), len);
2517        assert_eq!(data.len(), len);
2518
2519        let mut store_data = vec![0u8; len];
2520        assert_eq!(a.store(&mut store_data).unwrap(), len);
2521
2522        assert_eq!(&bytes, data);
2523        assert_eq!(&store_data, data);
2524
2525        let b = Variant::from_data::<(String, u8, u32), _>(store_data);
2526        assert_eq!(a, b);
2527
2528        let c = Variant::from_bytes::<(String, u8, u32)>(&bytes);
2529        assert_eq!(a, c);
2530    }
2531
2532    #[test]
2533    fn test_print_parse() {
2534        let a = ("test", 1u8, 2u32).to_variant();
2535
2536        let a2 = Variant::parse(Some(a.type_()), &a.print(false)).unwrap();
2537        assert_eq!(a, a2);
2538
2539        let a3: Variant = a.to_string().parse().unwrap();
2540        assert_eq!(a, a3);
2541    }
2542
2543    #[cfg(any(unix, windows))]
2544    #[test]
2545    fn test_paths() {
2546        use std::path::PathBuf;
2547
2548        let path = PathBuf::from("foo");
2549        let v = path.to_variant();
2550        assert_eq!(PathBuf::from_variant(&v), Some(path));
2551    }
2552
2553    #[test]
2554    fn test_regression_from_variant_panics() {
2555        let variant = "text".to_variant();
2556        let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
2557        assert!(hashmap.is_none());
2558
2559        let variant = HashMap::<u64, u64>::new().to_variant();
2560        let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
2561        assert!(hashmap.is_some());
2562    }
2563}