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    // rustdoc-stripper-ignore-next-stop
125    /// `GVariant` is a variant datatype; it can contain one or more values
126    /// along with information about the type of the values.
127    ///
128    /// A `GVariant` may contain simple types, like an integer, or a boolean value;
129    /// or complex types, like an array of two strings, or a dictionary of key
130    /// value pairs. A `GVariant` is also immutable: once it’s been created neither
131    /// its type nor its content can be modified further.
132    ///
133    /// `GVariant` is useful whenever data needs to be serialized, for example when
134    /// sending method parameters in D-Bus, or when saving settings using
135    /// [`GSettings`](../gio/class.Settings.html).
136    ///
137    /// When creating a new `GVariant`, you pass the data you want to store in it
138    /// along with a string representing the type of data you wish to pass to it.
139    ///
140    /// For instance, if you want to create a `GVariant` holding an integer value you
141    /// can use:
142    ///
143    /// **⚠️ The following code is in c ⚠️**
144    ///
145    /// ```c
146    /// GVariant *v = g_variant_new ("u", 40);
147    /// ```
148    ///
149    /// The string `u` in the first argument tells `GVariant` that the data passed to
150    /// the constructor (`40`) is going to be an unsigned integer.
151    ///
152    /// More advanced examples of `GVariant` in use can be found in documentation for
153    /// [`GVariant` format strings](gvariant-format-strings.html#pointers).
154    ///
155    /// The range of possible values is determined by the type.
156    ///
157    /// The type system used by `GVariant` is [type@GLib.VariantType].
158    ///
159    /// `GVariant` instances always have a type and a value (which are given
160    /// at construction time).  The type and value of a `GVariant` instance
161    /// can never change other than by the `GVariant` itself being
162    /// destroyed.  A `GVariant` cannot contain a pointer.
163    ///
164    /// `GVariant` is reference counted using `GLib::Variant::ref()` and
165    /// `GLib::Variant::unref()`.  `GVariant` also has floating reference counts —
166    /// see [`ref_sink()`][Self::ref_sink()].
167    ///
168    /// `GVariant` is completely threadsafe.  A `GVariant` instance can be
169    /// concurrently accessed in any way from any number of threads without
170    /// problems.
171    ///
172    /// `GVariant` is heavily optimised for dealing with data in serialized
173    /// form.  It works particularly well with data located in memory-mapped
174    /// files.  It can perform nearly all deserialization operations in a
175    /// small constant time, usually touching only a single memory page.
176    /// Serialized `GVariant` data can also be sent over the network.
177    ///
178    /// `GVariant` is largely compatible with D-Bus.  Almost all types of
179    /// `GVariant` instances can be sent over D-Bus.  See [type@GLib.VariantType] for
180    /// exceptions.  (However, `GVariant`’s serialization format is not the same
181    /// as the serialization format of a D-Bus message body: use
182    /// [GDBusMessage](../gio/class.DBusMessage.html), in the GIO library, for those.)
183    ///
184    /// For space-efficiency, the `GVariant` serialization format does not
185    /// automatically include the variant’s length, type or endianness,
186    /// which must either be implied from context (such as knowledge that a
187    /// particular file format always contains a little-endian
188    /// `G_VARIANT_TYPE_VARIANT` which occupies the whole length of the file)
189    /// or supplied out-of-band (for instance, a length, type and/or endianness
190    /// indicator could be placed at the beginning of a file, network message
191    /// or network stream).
192    ///
193    /// A `GVariant`’s size is limited mainly by any lower level operating
194    /// system constraints, such as the number of bits in `gsize`.  For
195    /// example, it is reasonable to have a 2GB file mapped into memory
196    /// with `GLib::MappedFile`, and call `GLib::Variant::new_from_data()` on
197    /// it.
198    ///
199    /// For convenience to C programmers, `GVariant` features powerful
200    /// varargs-based value construction and destruction.  This feature is
201    /// designed to be embedded in other libraries.
202    ///
203    /// There is a Python-inspired text language for describing `GVariant`
204    /// values.  `GVariant` includes a printer for this language and a parser
205    /// with type inferencing.
206    ///
207    /// ## Memory Use
208    ///
209    /// `GVariant` tries to be quite efficient with respect to memory use.
210    /// This section gives a rough idea of how much memory is used by the
211    /// current implementation.  The information here is subject to change
212    /// in the future.
213    ///
214    /// The memory allocated by `GVariant` can be grouped into 4 broad
215    /// purposes: memory for serialized data, memory for the type
216    /// information cache, buffer management memory and memory for the
217    /// `GVariant` structure itself.
218    ///
219    /// ## Serialized Data Memory
220    ///
221    /// This is the memory that is used for storing `GVariant` data in
222    /// serialized form.  This is what would be sent over the network or
223    /// what would end up on disk, not counting any indicator of the
224    /// endianness, or of the length or type of the top-level variant.
225    ///
226    /// The amount of memory required to store a boolean is 1 byte. 16,
227    /// 32 and 64 bit integers and double precision floating point numbers
228    /// use their ‘natural’ size.  Strings (including object path and
229    /// signature strings) are stored with a nul terminator, and as such
230    /// use the length of the string plus 1 byte.
231    ///
232    /// ‘Maybe’ types use no space at all to represent the null value and
233    /// use the same amount of space (sometimes plus one byte) as the
234    /// equivalent non-maybe-typed value to represent the non-null case.
235    ///
236    /// Arrays use the amount of space required to store each of their
237    /// members, concatenated.  Additionally, if the items stored in an
238    /// array are not of a fixed-size (ie: strings, other arrays, etc)
239    /// then an additional framing offset is stored for each item.  The
240    /// size of this offset is either 1, 2 or 4 bytes depending on the
241    /// overall size of the container.  Additionally, extra padding bytes
242    /// are added as required for alignment of child values.
243    ///
244    /// Tuples (including dictionary entries) use the amount of space
245    /// required to store each of their members, concatenated, plus one
246    /// framing offset (as per arrays) for each non-fixed-sized item in
247    /// the tuple, except for the last one.  Additionally, extra padding
248    /// bytes are added as required for alignment of child values.
249    ///
250    /// Variants use the same amount of space as the item inside of the
251    /// variant, plus 1 byte, plus the length of the type string for the
252    /// item inside the variant.
253    ///
254    /// As an example, consider a dictionary mapping strings to variants.
255    /// In the case that the dictionary is empty, 0 bytes are required for
256    /// the serialization.
257    ///
258    /// If we add an item ‘width’ that maps to the int32 value of 500 then
259    /// we will use 4 bytes to store the int32 (so 6 for the variant
260    /// containing it) and 6 bytes for the string.  The variant must be
261    /// aligned to 8 after the 6 bytes of the string, so that’s 2 extra
262    /// bytes.  6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
263    /// for the dictionary entry.  An additional 1 byte is added to the
264    /// array as a framing offset making a total of 15 bytes.
265    ///
266    /// If we add another entry, ‘title’ that maps to a nullable string
267    /// that happens to have a value of null, then we use 0 bytes for the
268    /// null value (and 3 bytes for the variant to contain it along with
269    /// its type string) plus 6 bytes for the string.  Again, we need 2
270    /// padding bytes.  That makes a total of 6 + 2 + 3 = 11 bytes.
271    ///
272    /// We now require extra padding between the two items in the array.
273    /// After the 14 bytes of the first item, that’s 2 bytes required.
274    /// We now require 2 framing offsets for an extra two
275    /// bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
276    /// dictionary.
277    ///
278    /// ## Type Information Cache
279    ///
280    /// For each `GVariant` type that currently exists in the program a type
281    /// information structure is kept in the type information cache.  The
282    /// type information structure is required for rapid deserialization.
283    ///
284    /// Continuing with the above example, if a `GVariant` exists with the
285    /// type `a{sv}` then a type information struct will exist for
286    /// `a{sv}`, `{sv}`, `s`, and `v`.  Multiple uses of the same type
287    /// will share the same type information.  Additionally, all
288    /// single-digit types are stored in read-only static memory and do
289    /// not contribute to the writable memory footprint of a program using
290    /// `GVariant`.
291    ///
292    /// Aside from the type information structures stored in read-only
293    /// memory, there are two forms of type information.  One is used for
294    /// container types where there is a single element type: arrays and
295    /// maybe types.  The other is used for container types where there
296    /// are multiple element types: tuples and dictionary entries.
297    ///
298    /// Array type info structures are `6 * sizeof (void *)`, plus the
299    /// memory required to store the type string itself.  This means that
300    /// on 32-bit systems, the cache entry for `a{sv}` would require 30
301    /// bytes of memory (plus allocation overhead).
302    ///
303    /// Tuple type info structures are `6 * sizeof (void *)`, plus `4 *
304    /// sizeof (void *)` for each item in the tuple, plus the memory
305    /// required to store the type string itself.  A 2-item tuple, for
306    /// example, would have a type information structure that consumed
307    /// writable memory in the size of `14 * sizeof (void *)` (plus type
308    /// string)  This means that on 32-bit systems, the cache entry for
309    /// `{sv}` would require 61 bytes of memory (plus allocation overhead).
310    ///
311    /// This means that in total, for our `a{sv}` example, 91 bytes of
312    /// type information would be allocated.
313    ///
314    /// The type information cache, additionally, uses a `GLib::HashTable` to
315    /// store and look up the cached items and stores a pointer to this
316    /// hash table in static storage.  The hash table is freed when there
317    /// are zero items in the type cache.
318    ///
319    /// Although these sizes may seem large it is important to remember
320    /// that a program will probably only have a very small number of
321    /// different types of values in it and that only one type information
322    /// structure is required for many different values of the same type.
323    ///
324    /// ## Buffer Management Memory
325    ///
326    /// `GVariant` uses an internal buffer management structure to deal
327    /// with the various different possible sources of serialized data
328    /// that it uses.  The buffer is responsible for ensuring that the
329    /// correct call is made when the data is no longer in use by
330    /// `GVariant`.  This may involve a `free()` or
331    /// even `GLib::MappedFile::unref()`.
332    ///
333    /// One buffer management structure is used for each chunk of
334    /// serialized data.  The size of the buffer management structure
335    /// is `4 * (void *)`.  On 32-bit systems, that’s 16 bytes.
336    ///
337    /// ## GVariant structure
338    ///
339    /// The size of a `GVariant` structure is `6 * (void *)`.  On 32-bit
340    /// systems, that’s 24 bytes.
341    ///
342    /// `GVariant` structures only exist if they are explicitly created
343    /// with API calls.  For example, if a `GVariant` is constructed out of
344    /// serialized data for the example given above (with the dictionary)
345    /// then although there are 9 individual values that comprise the
346    /// entire dictionary (two keys, two values, two variants containing
347    /// the values, two dictionary entries, plus the dictionary itself),
348    /// only 1 `GVariant` instance exists — the one referring to the
349    /// dictionary.
350    ///
351    /// If calls are made to start accessing the other values then
352    /// `GVariant` instances will exist for those values only for as long
353    /// as they are in use (ie: until you call `GLib::Variant::unref()`).  The
354    /// type information is shared.  The serialized data and the buffer
355    /// management structure for that serialized data is shared by the
356    /// child.
357    ///
358    /// ## Summary
359    ///
360    /// To put the entire example together, for our dictionary mapping
361    /// strings to variants (with two entries, as given above), we are
362    /// using 91 bytes of memory for type information, 29 bytes of memory
363    /// for the serialized data, 16 bytes for buffer management and 24
364    /// bytes for the `GVariant` instance, or a total of 160 bytes, plus
365    /// allocation overhead.  If we were to use [`child_value()`][Self::child_value()]
366    /// to access the two dictionary entries, we would use an additional 48
367    /// bytes.  If we were to have other dictionaries of the same type, we
368    /// would use more memory for the serialized data and buffer
369    /// management for those dictionaries, but the type information would
370    /// be shared.
371    #[doc(alias = "GVariant")]
372    pub struct Variant(Shared<ffi::GVariant>);
373
374    match fn {
375        ref => |ptr| ffi::g_variant_ref_sink(ptr),
376        unref => |ptr| ffi::g_variant_unref(ptr),
377    }
378}
379
380impl StaticType for Variant {
381    #[inline]
382    fn static_type() -> Type {
383        Type::VARIANT
384    }
385}
386
387#[doc(hidden)]
388impl crate::value::ValueType for Variant {
389    type Type = Variant;
390}
391
392#[doc(hidden)]
393impl crate::value::ValueTypeOptional for Variant {}
394
395#[doc(hidden)]
396unsafe impl<'a> crate::value::FromValue<'a> for Variant {
397    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;
398
399    unsafe fn from_value(value: &'a crate::Value) -> Self {
400        unsafe {
401            let ptr = gobject_ffi::g_value_dup_variant(value.to_glib_none().0);
402            debug_assert!(!ptr.is_null());
403            from_glib_full(ptr)
404        }
405    }
406}
407
408#[doc(hidden)]
409impl crate::value::ToValue for Variant {
410    fn to_value(&self) -> crate::Value {
411        unsafe {
412            let mut value = crate::Value::from_type_unchecked(Variant::static_type());
413            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, self.to_glib_full());
414            value
415        }
416    }
417
418    fn value_type(&self) -> crate::Type {
419        Variant::static_type()
420    }
421}
422
423#[doc(hidden)]
424impl From<Variant> for crate::Value {
425    #[inline]
426    fn from(v: Variant) -> Self {
427        unsafe {
428            let mut value = crate::Value::from_type_unchecked(Variant::static_type());
429            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, v.into_glib_ptr());
430            value
431        }
432    }
433}
434
435#[doc(hidden)]
436impl crate::value::ToValueOptional for Variant {
437    fn to_value_optional(s: Option<&Self>) -> crate::Value {
438        let mut value = crate::Value::for_value_type::<Self>();
439        unsafe {
440            gobject_ffi::g_value_take_variant(value.to_glib_none_mut().0, s.to_glib_full());
441        }
442
443        value
444    }
445}
446
447// rustdoc-stripper-ignore-next
448/// An error returned from the [`try_get`](struct.Variant.html#method.try_get) function
449/// on a [`Variant`](struct.Variant.html) when the expected type does not match the actual type.
450#[derive(Clone, PartialEq, Eq, Debug)]
451pub struct VariantTypeMismatchError {
452    pub actual: VariantType,
453    pub expected: VariantType,
454}
455
456impl VariantTypeMismatchError {
457    pub fn new(actual: VariantType, expected: VariantType) -> Self {
458        Self { actual, expected }
459    }
460}
461
462impl fmt::Display for VariantTypeMismatchError {
463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464        write!(
465            f,
466            "Type mismatch: Expected '{}' got '{}'",
467            self.expected, self.actual
468        )
469    }
470}
471
472impl std::error::Error for VariantTypeMismatchError {}
473
474impl Variant {
475    // rustdoc-stripper-ignore-next
476    /// Returns the type of the value.
477    // rustdoc-stripper-ignore-next-stop
478    /// Determines the type of @self.
479    ///
480    /// The return value is valid for the lifetime of @self and must not
481    /// be freed.
482    ///
483    /// # Returns
484    ///
485    /// a #GVariantType
486    #[doc(alias = "g_variant_get_type")]
487    pub fn type_(&self) -> &VariantTy {
488        unsafe { VariantTy::from_ptr(ffi::g_variant_get_type(self.to_glib_none().0)) }
489    }
490
491    // rustdoc-stripper-ignore-next
492    /// Returns `true` if the type of the value corresponds to `T`.
493    #[inline]
494    #[doc(alias = "g_variant_is_of_type")]
495    pub fn is<T: StaticVariantType>(&self) -> bool {
496        self.is_type(&T::static_variant_type())
497    }
498
499    // rustdoc-stripper-ignore-next
500    /// Returns `true` if the type of the value corresponds to `type_`.
501    ///
502    /// This is equivalent to [`self.type_().is_subtype_of(type_)`](VariantTy::is_subtype_of).
503    #[inline]
504    #[doc(alias = "g_variant_is_of_type")]
505    pub fn is_type(&self, type_: &VariantTy) -> bool {
506        unsafe {
507            from_glib(ffi::g_variant_is_of_type(
508                self.to_glib_none().0,
509                type_.to_glib_none().0,
510            ))
511        }
512    }
513
514    // rustdoc-stripper-ignore-next
515    /// Returns the classification of the variant.
516    // rustdoc-stripper-ignore-next-stop
517    /// Classifies @self according to its top-level type.
518    ///
519    /// # Returns
520    ///
521    /// the #GVariantClass of @self
522    #[doc(alias = "g_variant_classify")]
523    pub fn classify(&self) -> crate::VariantClass {
524        unsafe { from_glib(ffi::g_variant_classify(self.to_glib_none().0)) }
525    }
526
527    // rustdoc-stripper-ignore-next
528    /// Tries to extract a value of type `T`.
529    ///
530    /// Returns `Some` if `T` matches the variant's type.
531    // rustdoc-stripper-ignore-next-stop
532    /// Deconstructs a #GVariant instance.
533    ///
534    /// Think of this function as an analogue to scanf().
535    ///
536    /// The arguments that are expected by this function are entirely
537    /// determined by @format_string.  @format_string also restricts the
538    /// permissible types of @self.  It is an error to give a value with
539    /// an incompatible type.  See the section on
540    /// [GVariant format strings](gvariant-format-strings.html).
541    /// Please note that the syntax of the format string is very likely to be
542    /// extended in the future.
543    ///
544    /// @format_string determines the C types that are used for unpacking
545    /// the values and also determines if the values are copied or borrowed,
546    /// see the section on
547    /// [`GVariant` format strings](gvariant-format-strings.html#pointers).
548    /// ## `format_string`
549    /// a #GVariant format string
550    #[inline]
551    pub fn get<T: FromVariant>(&self) -> Option<T> {
552        T::from_variant(self)
553    }
554
555    // rustdoc-stripper-ignore-next
556    /// Tries to extract a value of type `T`.
557    pub fn try_get<T: FromVariant>(&self) -> Result<T, VariantTypeMismatchError> {
558        self.get().ok_or_else(|| {
559            VariantTypeMismatchError::new(
560                self.type_().to_owned(),
561                T::static_variant_type().into_owned(),
562            )
563        })
564    }
565
566    // rustdoc-stripper-ignore-next
567    /// Boxes value.
568    #[inline]
569    pub fn from_variant(value: &Variant) -> Self {
570        unsafe { from_glib_none(ffi::g_variant_new_variant(value.to_glib_none().0)) }
571    }
572
573    // rustdoc-stripper-ignore-next
574    /// Unboxes self.
575    ///
576    /// Returns `Some` if self contains a `Variant`.
577    #[inline]
578    #[doc(alias = "get_variant")]
579    pub fn as_variant(&self) -> Option<Variant> {
580        unsafe { from_glib_full(ffi::g_variant_get_variant(self.to_glib_none().0)) }
581    }
582
583    // rustdoc-stripper-ignore-next
584    /// Reads a child item out of a container `Variant` instance.
585    ///
586    /// # Panics
587    ///
588    /// * if `self` is not a container type.
589    /// * if given `index` is larger than number of children.
590    // rustdoc-stripper-ignore-next-stop
591    /// Reads a child item out of a container #GVariant instance.  This
592    /// includes variants, maybes, arrays, tuples and dictionary
593    /// entries.  It is an error to call this function on any other type of
594    /// #GVariant.
595    ///
596    /// It is an error if @index_ is greater than the number of child items
597    /// in the container.  See g_variant_n_children().
598    ///
599    /// The returned value is never floating.  You should free it with
600    /// g_variant_unref() when you're done with it.
601    ///
602    /// Note that values borrowed from the returned child are not guaranteed to
603    /// still be valid after the child is freed even if you still hold a reference
604    /// to @self, if @self has not been serialized at the time this function is
605    /// called. To avoid this, you can serialize @self by calling
606    /// g_variant_get_data() and optionally ignoring the return value.
607    ///
608    /// There may be implementation specific restrictions on deeply nested values,
609    /// which would result in the unit tuple being returned as the child value,
610    /// instead of further nested children. #GVariant is guaranteed to handle
611    /// nesting up to at least 64 levels.
612    ///
613    /// This function is O(1).
614    /// ## `index_`
615    /// the index of the child to fetch
616    ///
617    /// # Returns
618    ///
619    /// the child at the specified index
620    #[doc(alias = "get_child_value")]
621    #[doc(alias = "g_variant_get_child_value")]
622    #[must_use]
623    pub fn child_value(&self, index: usize) -> Variant {
624        assert!(self.is_container());
625        assert!(index < self.n_children());
626
627        unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) }
628    }
629
630    // rustdoc-stripper-ignore-next
631    /// Try to read a child item out of a container `Variant` instance.
632    ///
633    /// It returns `None` if `self` is not a container type or if the given
634    /// `index` is larger than number of children.
635    pub fn try_child_value(&self, index: usize) -> Option<Variant> {
636        if !(self.is_container() && index < self.n_children()) {
637            return None;
638        }
639
640        let v =
641            unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) };
642        Some(v)
643    }
644
645    // rustdoc-stripper-ignore-next
646    /// Try to read a child item out of a container `Variant` instance.
647    ///
648    /// It returns `Ok(None)` if `self` is not a container type or if the given
649    /// `index` is larger than number of children.  An error is thrown if the
650    /// type does not match.
651    pub fn try_child_get<T: StaticVariantType + FromVariant>(
652        &self,
653        index: usize,
654    ) -> Result<Option<T>, VariantTypeMismatchError> {
655        // TODO: In the future optimize this by using g_variant_get_child()
656        // directly to avoid allocating a GVariant.
657        self.try_child_value(index).map(|v| v.try_get()).transpose()
658    }
659
660    // rustdoc-stripper-ignore-next
661    /// Read a child item out of a container `Variant` instance.
662    ///
663    /// # Panics
664    ///
665    /// * if `self` is not a container type.
666    /// * if given `index` is larger than number of children.
667    /// * if the expected variant type does not match
668    pub fn child_get<T: StaticVariantType + FromVariant>(&self, index: usize) -> T {
669        // TODO: In the future optimize this by using g_variant_get_child()
670        // directly to avoid allocating a GVariant.
671        self.child_value(index).get().unwrap()
672    }
673
674    // rustdoc-stripper-ignore-next
675    /// Tries to extract a `&str`.
676    ///
677    /// Returns `Some` if the variant has a string type (`s`, `o` or `g` type
678    /// strings).
679    #[doc(alias = "get_str")]
680    #[doc(alias = "g_variant_get_string")]
681    pub fn str(&self) -> Option<&str> {
682        unsafe {
683            match self.type_().as_str() {
684                "s" | "o" | "g" => {
685                    let mut len = 0;
686                    let ptr = ffi::g_variant_get_string(self.to_glib_none().0, &mut len);
687                    if len == 0 {
688                        Some("")
689                    } else {
690                        let ret = str::from_utf8_unchecked(slice::from_raw_parts(
691                            ptr as *const u8,
692                            len as _,
693                        ));
694                        Some(ret)
695                    }
696                }
697                _ => None,
698            }
699        }
700    }
701
702    // rustdoc-stripper-ignore-next
703    /// Tries to extract a `&[T]` from a variant of array type with a suitable element type.
704    ///
705    /// Returns an error if the type is wrong.
706    // rustdoc-stripper-ignore-next-stop
707    /// Provides access to the serialized data for an array of fixed-sized
708    /// items.
709    ///
710    /// @self must be an array with fixed-sized elements.  Numeric types are
711    /// fixed-size, as are tuples containing only other fixed-sized types.
712    ///
713    /// @element_size must be the size of a single element in the array,
714    /// as given by the section on
715    /// [serialized data memory](struct.Variant.html#serialized-data-memory).
716    ///
717    /// In particular, arrays of these fixed-sized types can be interpreted
718    /// as an array of the given C type, with @element_size set to the size
719    /// the appropriate type:
720    ///
721    /// - `G_VARIANT_TYPE_INT16` (etc.): #gint16 (etc.)
722    /// - `G_VARIANT_TYPE_BOOLEAN`: #guchar (not #gboolean!)
723    /// - `G_VARIANT_TYPE_BYTE`: #guint8
724    /// - `G_VARIANT_TYPE_HANDLE`: #guint32
725    /// - `G_VARIANT_TYPE_DOUBLE`: #gdouble
726    ///
727    /// For example, if calling this function for an array of 32-bit integers,
728    /// you might say `sizeof(gint32)`. This value isn't used except for the purpose
729    /// of a double-check that the form of the serialized data matches the caller's
730    /// expectation.
731    ///
732    /// @n_elements, which must be non-[`None`], is set equal to the number of
733    /// items in the array.
734    /// ## `element_size`
735    /// the size of each element
736    ///
737    /// # Returns
738    ///
739    /// a pointer to
740    ///     the fixed array
741    #[doc(alias = "g_variant_get_fixed_array")]
742    pub fn fixed_array<T: FixedSizeVariantType>(&self) -> Result<&[T], VariantTypeMismatchError> {
743        unsafe {
744            let expected_ty = T::static_variant_type().as_array();
745            if self.type_() != expected_ty {
746                return Err(VariantTypeMismatchError {
747                    actual: self.type_().to_owned(),
748                    expected: expected_ty.into_owned(),
749                });
750            }
751
752            let mut n_elements = mem::MaybeUninit::uninit();
753            let ptr = ffi::g_variant_get_fixed_array(
754                self.to_glib_none().0,
755                n_elements.as_mut_ptr(),
756                mem::size_of::<T>(),
757            );
758
759            let n_elements = n_elements.assume_init();
760            if n_elements == 0 {
761                Ok(&[])
762            } else {
763                debug_assert!(!ptr.is_null());
764                Ok(slice::from_raw_parts(ptr as *const T, n_elements))
765            }
766        }
767    }
768
769    // rustdoc-stripper-ignore-next
770    /// Creates a new Variant array from children.
771    ///
772    /// # Panics
773    ///
774    /// This function panics if not all variants are of type `T`.
775    #[doc(alias = "g_variant_new_array")]
776    pub fn array_from_iter<T: StaticVariantType>(
777        children: impl IntoIterator<Item = Variant>,
778    ) -> Self {
779        Self::array_from_iter_with_type(&T::static_variant_type(), children)
780    }
781
782    // rustdoc-stripper-ignore-next
783    /// Creates a new Variant array from children with the specified type.
784    ///
785    /// # Panics
786    ///
787    /// This function panics if not all variants are of type `type_`.
788    #[doc(alias = "g_variant_new_array")]
789    pub fn array_from_iter_with_type(
790        type_: &VariantTy,
791        children: impl IntoIterator<Item = impl AsRef<Variant>>,
792    ) -> Self {
793        unsafe {
794            let mut builder = mem::MaybeUninit::uninit();
795            ffi::g_variant_builder_init(builder.as_mut_ptr(), type_.as_array().to_glib_none().0);
796            let mut builder = builder.assume_init();
797            for value in children.into_iter() {
798                let value = value.as_ref();
799                if ffi::g_variant_is_of_type(value.to_glib_none().0, type_.to_glib_none().0)
800                    == ffi::GFALSE
801                {
802                    ffi::g_variant_builder_clear(&mut builder);
803                    assert!(value.is_type(type_));
804                }
805
806                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
807            }
808            from_glib_none(ffi::g_variant_builder_end(&mut builder))
809        }
810    }
811
812    // rustdoc-stripper-ignore-next
813    /// Creates a new Variant array from a fixed array.
814    #[doc(alias = "g_variant_new_fixed_array")]
815    pub fn array_from_fixed_array<T: FixedSizeVariantType>(array: &[T]) -> Self {
816        let type_ = T::static_variant_type();
817
818        unsafe {
819            from_glib_none(ffi::g_variant_new_fixed_array(
820                type_.as_ptr(),
821                array.as_ptr() as ffi::gconstpointer,
822                array.len(),
823                mem::size_of::<T>(),
824            ))
825        }
826    }
827
828    // rustdoc-stripper-ignore-next
829    /// Creates a new Variant tuple from children.
830    #[doc(alias = "g_variant_new_tuple")]
831    pub fn tuple_from_iter(children: impl IntoIterator<Item = impl AsRef<Variant>>) -> Self {
832        unsafe {
833            let mut builder = mem::MaybeUninit::uninit();
834            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
835            let mut builder = builder.assume_init();
836            for value in children.into_iter() {
837                ffi::g_variant_builder_add_value(&mut builder, value.as_ref().to_glib_none().0);
838            }
839            from_glib_none(ffi::g_variant_builder_end(&mut builder))
840        }
841    }
842
843    // rustdoc-stripper-ignore-next
844    /// Creates a new dictionary entry Variant.
845    ///
846    /// [DictEntry] should be preferred over this when the types are known statically.
847    #[doc(alias = "g_variant_new_dict_entry")]
848    pub fn from_dict_entry(key: &Variant, value: &Variant) -> Self {
849        unsafe {
850            from_glib_none(ffi::g_variant_new_dict_entry(
851                key.to_glib_none().0,
852                value.to_glib_none().0,
853            ))
854        }
855    }
856
857    // rustdoc-stripper-ignore-next
858    /// Creates a new maybe Variant.
859    #[doc(alias = "g_variant_new_maybe")]
860    pub fn from_maybe<T: StaticVariantType>(child: Option<&Variant>) -> Self {
861        let type_ = T::static_variant_type();
862        match child {
863            Some(child) => {
864                assert_eq!(type_, child.type_());
865
866                Self::from_some(child)
867            }
868            None => Self::from_none(&type_),
869        }
870    }
871
872    // rustdoc-stripper-ignore-next
873    /// Creates a new maybe Variant from a child.
874    #[doc(alias = "g_variant_new_maybe")]
875    pub fn from_some(child: &Variant) -> Self {
876        unsafe {
877            from_glib_none(ffi::g_variant_new_maybe(
878                ptr::null(),
879                child.to_glib_none().0,
880            ))
881        }
882    }
883
884    // rustdoc-stripper-ignore-next
885    /// Creates a new maybe Variant with Nothing.
886    #[doc(alias = "g_variant_new_maybe")]
887    pub fn from_none(type_: &VariantTy) -> Self {
888        unsafe {
889            from_glib_none(ffi::g_variant_new_maybe(
890                type_.to_glib_none().0,
891                ptr::null_mut(),
892            ))
893        }
894    }
895
896    // rustdoc-stripper-ignore-next
897    /// Extract the value of a maybe Variant.
898    ///
899    /// Returns the child value, or `None` if the value is Nothing.
900    ///
901    /// # Panics
902    ///
903    /// Panics if the variant is not maybe-typed.
904    #[inline]
905    pub fn as_maybe(&self) -> Option<Variant> {
906        assert!(self.type_().is_maybe());
907
908        unsafe { from_glib_full(ffi::g_variant_get_maybe(self.to_glib_none().0)) }
909    }
910
911    // rustdoc-stripper-ignore-next
912    /// Pretty-print the contents of this variant in a human-readable form.
913    ///
914    /// A variant can be recreated from this output via [`Variant::parse`].
915    // rustdoc-stripper-ignore-next-stop
916    /// Pretty-prints @self in the format understood by g_variant_parse().
917    ///
918    /// The format is described [here](gvariant-text-format.html).
919    ///
920    /// If @type_annotate is [`true`], then type information is included in
921    /// the output.
922    /// ## `type_annotate`
923    /// [`true`] if type information should be included in
924    ///                 the output
925    ///
926    /// # Returns
927    ///
928    /// a newly-allocated string holding the result.
929    #[doc(alias = "g_variant_print")]
930    pub fn print(&self, type_annotate: bool) -> crate::GString {
931        unsafe {
932            from_glib_full(ffi::g_variant_print(
933                self.to_glib_none().0,
934                type_annotate.into_glib(),
935            ))
936        }
937    }
938
939    // rustdoc-stripper-ignore-next
940    /// Parses a GVariant from the text representation produced by [`print()`](Self::print).
941    #[doc(alias = "g_variant_parse")]
942    pub fn parse(type_: Option<&VariantTy>, text: &str) -> Result<Self, crate::Error> {
943        unsafe {
944            let mut error = ptr::null_mut();
945            let text = text.as_bytes().as_ptr_range();
946            let variant = ffi::g_variant_parse(
947                type_.to_glib_none().0,
948                text.start as *const _,
949                text.end as *const _,
950                ptr::null_mut(),
951                &mut error,
952            );
953            if variant.is_null() {
954                debug_assert!(!error.is_null());
955                Err(from_glib_full(error))
956            } else {
957                debug_assert!(error.is_null());
958                Ok(from_glib_full(variant))
959            }
960        }
961    }
962
963    // rustdoc-stripper-ignore-next
964    /// Constructs a new serialized-mode GVariant instance.
965    // rustdoc-stripper-ignore-next-stop
966    /// Constructs a new serialized-mode #GVariant instance.  This is the
967    /// inner interface for creation of new serialized values that gets
968    /// called from various functions in gvariant.c.
969    ///
970    /// A reference is taken on @bytes.
971    ///
972    /// The data in @bytes must be aligned appropriately for the @type_ being loaded.
973    /// Otherwise this function will internally create a copy of the memory (since
974    /// GLib 2.60) or (in older versions) fail and exit the process.
975    /// ## `type_`
976    /// a #GVariantType
977    /// ## `bytes`
978    /// a #GBytes
979    /// ## `trusted`
980    /// if the contents of @bytes are trusted
981    ///
982    /// # Returns
983    ///
984    /// a new #GVariant with a floating reference
985    #[doc(alias = "g_variant_new_from_bytes")]
986    pub fn from_bytes<T: StaticVariantType>(bytes: &Bytes) -> Self {
987        Variant::from_bytes_with_type(bytes, &T::static_variant_type())
988    }
989
990    // rustdoc-stripper-ignore-next
991    /// Constructs a new serialized-mode GVariant instance.
992    ///
993    /// This is the same as `from_bytes`, except that checks on the passed
994    /// data are skipped.
995    ///
996    /// You should not use this function on data from external sources.
997    ///
998    /// # Safety
999    ///
1000    /// Since the data is not validated, this is potentially dangerous if called
1001    /// on bytes which are not guaranteed to have come from serialising another
1002    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
1003    pub unsafe fn from_bytes_trusted<T: StaticVariantType>(bytes: &Bytes) -> Self {
1004        unsafe { Variant::from_bytes_with_type_trusted(bytes, &T::static_variant_type()) }
1005    }
1006
1007    // rustdoc-stripper-ignore-next
1008    /// Constructs a new serialized-mode GVariant instance.
1009    // rustdoc-stripper-ignore-next-stop
1010    /// Creates a new #GVariant instance from serialized data.
1011    ///
1012    /// @type_ is the type of #GVariant instance that will be constructed.
1013    /// The interpretation of @data depends on knowing the type.
1014    ///
1015    /// @data is not modified by this function and must remain valid with an
1016    /// unchanging value until such a time as @notify is called with
1017    /// @user_data.  If the contents of @data change before that time then
1018    /// the result is undefined.
1019    ///
1020    /// If @data is trusted to be serialized data in normal form then
1021    /// @trusted should be [`true`].  This applies to serialized data created
1022    /// within this process or read from a trusted location on the disk (such
1023    /// as a file installed in /usr/lib alongside your application).  You
1024    /// should set trusted to [`false`] if @data is read from the network, a
1025    /// file in the user's home directory, etc.
1026    ///
1027    /// If @data was not stored in this machine's native endianness, any multi-byte
1028    /// numeric values in the returned variant will also be in non-native
1029    /// endianness. g_variant_byteswap() can be used to recover the original values.
1030    ///
1031    /// @notify will be called with @user_data when @data is no longer
1032    /// needed.  The exact time of this call is unspecified and might even be
1033    /// before this function returns.
1034    ///
1035    /// Note: @data must be backed by memory that is aligned appropriately for the
1036    /// @type_ being loaded. Otherwise this function will internally create a copy of
1037    /// the memory (since GLib 2.60) or (in older versions) fail and exit the
1038    /// process.
1039    /// ## `type_`
1040    /// a definite #GVariantType
1041    /// ## `data`
1042    /// the serialized data
1043    /// ## `trusted`
1044    /// [`true`] if @data is definitely in normal form
1045    /// ## `notify`
1046    /// function to call when @data is no longer needed
1047    ///
1048    /// # Returns
1049    ///
1050    /// a new floating #GVariant of type @type_
1051    #[doc(alias = "g_variant_new_from_data")]
1052    pub fn from_data<T: StaticVariantType, A: AsRef<[u8]> + 'static>(data: A) -> Self {
1053        Variant::from_data_with_type(data, &T::static_variant_type())
1054    }
1055
1056    // rustdoc-stripper-ignore-next
1057    /// Constructs a new serialized-mode GVariant instance.
1058    ///
1059    /// This is the same as `from_data`, except that checks on the passed
1060    /// data are skipped.
1061    ///
1062    /// You should not use this function on data from external sources.
1063    ///
1064    /// # Safety
1065    ///
1066    /// Since the data is not validated, this is potentially dangerous if called
1067    /// on bytes which are not guaranteed to have come from serialising another
1068    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
1069    pub unsafe fn from_data_trusted<T: StaticVariantType, A: AsRef<[u8]> + 'static>(
1070        data: A,
1071    ) -> Self {
1072        unsafe { Variant::from_data_with_type_trusted(data, &T::static_variant_type()) }
1073    }
1074
1075    // rustdoc-stripper-ignore-next
1076    /// Constructs a new serialized-mode GVariant instance with a given type.
1077    #[doc(alias = "g_variant_new_from_bytes")]
1078    pub fn from_bytes_with_type(bytes: &Bytes, type_: &VariantTy) -> Self {
1079        unsafe {
1080            from_glib_none(ffi::g_variant_new_from_bytes(
1081                type_.as_ptr() as *const _,
1082                bytes.to_glib_none().0,
1083                false.into_glib(),
1084            ))
1085        }
1086    }
1087
1088    // rustdoc-stripper-ignore-next
1089    /// Constructs a new serialized-mode GVariant instance with a given type.
1090    ///
1091    /// This is the same as `from_bytes`, except that checks on the passed
1092    /// data are skipped.
1093    ///
1094    /// You should not use this function on data from external sources.
1095    ///
1096    /// # Safety
1097    ///
1098    /// Since the data is not validated, this is potentially dangerous if called
1099    /// on bytes which are not guaranteed to have come from serialising another
1100    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
1101    pub unsafe fn from_bytes_with_type_trusted(bytes: &Bytes, type_: &VariantTy) -> Self {
1102        unsafe {
1103            from_glib_none(ffi::g_variant_new_from_bytes(
1104                type_.as_ptr() as *const _,
1105                bytes.to_glib_none().0,
1106                true.into_glib(),
1107            ))
1108        }
1109    }
1110
1111    // rustdoc-stripper-ignore-next
1112    /// Constructs a new serialized-mode GVariant instance with a given type.
1113    #[doc(alias = "g_variant_new_from_data")]
1114    pub fn from_data_with_type<A: AsRef<[u8]> + 'static>(data: A, type_: &VariantTy) -> Self {
1115        unsafe {
1116            let data = Box::new(data);
1117            let (data_ptr, len) = {
1118                let data = (*data).as_ref();
1119                (data.as_ptr(), data.len())
1120            };
1121
1122            unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
1123                unsafe {
1124                    let _ = Box::from_raw(ptr as *mut A);
1125                }
1126            }
1127
1128            from_glib_none(ffi::g_variant_new_from_data(
1129                type_.as_ptr() as *const _,
1130                data_ptr as ffi::gconstpointer,
1131                len,
1132                false.into_glib(),
1133                Some(free_data::<A>),
1134                Box::into_raw(data) as ffi::gpointer,
1135            ))
1136        }
1137    }
1138
1139    // rustdoc-stripper-ignore-next
1140    /// Constructs a new serialized-mode GVariant instance with a given type.
1141    ///
1142    /// This is the same as `from_data`, except that checks on the passed
1143    /// data are skipped.
1144    ///
1145    /// You should not use this function on data from external sources.
1146    ///
1147    /// # Safety
1148    ///
1149    /// Since the data is not validated, this is potentially dangerous if called
1150    /// on bytes which are not guaranteed to have come from serialising another
1151    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
1152    pub unsafe fn from_data_with_type_trusted<A: AsRef<[u8]> + 'static>(
1153        data: A,
1154        type_: &VariantTy,
1155    ) -> Self {
1156        unsafe {
1157            let data = Box::new(data);
1158            let (data_ptr, len) = {
1159                let data = (*data).as_ref();
1160                (data.as_ptr(), data.len())
1161            };
1162
1163            unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
1164                unsafe {
1165                    let _ = Box::from_raw(ptr as *mut A);
1166                }
1167            }
1168
1169            from_glib_none(ffi::g_variant_new_from_data(
1170                type_.as_ptr() as *const _,
1171                data_ptr as ffi::gconstpointer,
1172                len,
1173                true.into_glib(),
1174                Some(free_data::<A>),
1175                Box::into_raw(data) as ffi::gpointer,
1176            ))
1177        }
1178    }
1179
1180    // rustdoc-stripper-ignore-next
1181    /// Returns the serialized form of a GVariant instance.
1182    // rustdoc-stripper-ignore-next-stop
1183    /// Returns a pointer to the serialized form of a #GVariant instance.
1184    /// The semantics of this function are exactly the same as
1185    /// g_variant_get_data(), except that the returned #GBytes holds
1186    /// a reference to the variant data.
1187    ///
1188    /// # Returns
1189    ///
1190    /// A new #GBytes representing the variant data
1191    #[doc(alias = "get_data_as_bytes")]
1192    #[doc(alias = "g_variant_get_data_as_bytes")]
1193    pub fn data_as_bytes(&self) -> Bytes {
1194        unsafe { from_glib_full(ffi::g_variant_get_data_as_bytes(self.to_glib_none().0)) }
1195    }
1196
1197    // rustdoc-stripper-ignore-next
1198    /// Returns the serialized form of a GVariant instance.
1199    // rustdoc-stripper-ignore-next-stop
1200    /// Returns a pointer to the serialized form of a #GVariant instance.
1201    /// The returned data may not be in fully-normalised form if read from an
1202    /// untrusted source.  The returned data must not be freed; it remains
1203    /// valid for as long as @self exists.
1204    ///
1205    /// If @self is a fixed-sized value that was deserialized from a
1206    /// corrupted serialized container then [`None`] may be returned.  In this
1207    /// case, the proper thing to do is typically to use the appropriate
1208    /// number of nul bytes in place of @self.  If @self is not fixed-sized
1209    /// then [`None`] is never returned.
1210    ///
1211    /// In the case that @self is already in serialized form, this function
1212    /// is O(1).  If the value is not already in serialized form,
1213    /// serialization occurs implicitly and is approximately O(n) in the size
1214    /// of the result.
1215    ///
1216    /// To deserialize the data returned by this function, in addition to the
1217    /// serialized data, you must know the type of the #GVariant, and (if the
1218    /// machine might be different) the endianness of the machine that stored
1219    /// it. As a result, file formats or network messages that incorporate
1220    /// serialized #GVariants must include this information either
1221    /// implicitly (for instance "the file always contains a
1222    /// `G_VARIANT_TYPE_VARIANT` and it is always in little-endian order") or
1223    /// explicitly (by storing the type and/or endianness in addition to the
1224    /// serialized data).
1225    ///
1226    /// # Returns
1227    ///
1228    /// the serialized form of @self, or [`None`]
1229    #[doc(alias = "g_variant_get_data")]
1230    pub fn data(&self) -> &[u8] {
1231        unsafe {
1232            let selfv = self.to_glib_none();
1233            let len = ffi::g_variant_get_size(selfv.0);
1234            if len == 0 {
1235                return &[];
1236            }
1237            let ptr = ffi::g_variant_get_data(selfv.0);
1238            slice::from_raw_parts(ptr as *const _, len as _)
1239        }
1240    }
1241
1242    // rustdoc-stripper-ignore-next
1243    /// Returns the size of serialized form of a GVariant instance.
1244    // rustdoc-stripper-ignore-next-stop
1245    /// Determines the number of bytes that would be required to store @self
1246    /// with g_variant_store().
1247    ///
1248    /// If @self has a fixed-sized type then this function always returned
1249    /// that fixed size.
1250    ///
1251    /// In the case that @self is already in serialized form or the size has
1252    /// already been calculated (ie: this function has been called before)
1253    /// then this function is O(1).  Otherwise, the size is calculated, an
1254    /// operation which is approximately O(n) in the number of values
1255    /// involved.
1256    ///
1257    /// # Returns
1258    ///
1259    /// the serialized size of @self
1260    #[doc(alias = "g_variant_get_size")]
1261    pub fn size(&self) -> usize {
1262        unsafe { ffi::g_variant_get_size(self.to_glib_none().0) }
1263    }
1264
1265    // rustdoc-stripper-ignore-next
1266    /// Stores the serialized form of a GVariant instance into the given slice.
1267    ///
1268    /// The slice needs to be big enough.
1269    // rustdoc-stripper-ignore-next-stop
1270    /// Stores the serialized form of @self at @data.  @data should be
1271    /// large enough.  See g_variant_get_size().
1272    ///
1273    /// The stored data is in machine native byte order but may not be in
1274    /// fully-normalised form if read from an untrusted source.  See
1275    /// g_variant_get_normal_form() for a solution.
1276    ///
1277    /// As with g_variant_get_data(), to be able to deserialize the
1278    /// serialized variant successfully, its type and (if the destination
1279    /// machine might be different) its endianness must also be available.
1280    ///
1281    /// This function is approximately O(n) in the size of @data.
1282    #[doc(alias = "g_variant_store")]
1283    pub fn store(&self, data: &mut [u8]) -> Result<usize, crate::BoolError> {
1284        unsafe {
1285            let size = ffi::g_variant_get_size(self.to_glib_none().0);
1286            if data.len() < size {
1287                return Err(bool_error!("Provided slice is too small"));
1288            }
1289
1290            ffi::g_variant_store(self.to_glib_none().0, data.as_mut_ptr() as ffi::gpointer);
1291
1292            Ok(size)
1293        }
1294    }
1295
1296    // rustdoc-stripper-ignore-next
1297    /// Returns a copy of the variant in normal form.
1298    // rustdoc-stripper-ignore-next-stop
1299    /// Gets a #GVariant instance that has the same value as @self and is
1300    /// trusted to be in normal form.
1301    ///
1302    /// If @self is already trusted to be in normal form then a new
1303    /// reference to @self is returned.
1304    ///
1305    /// If @self is not already trusted, then it is scanned to check if it
1306    /// is in normal form.  If it is found to be in normal form then it is
1307    /// marked as trusted and a new reference to it is returned.
1308    ///
1309    /// If @self is found not to be in normal form then a new trusted
1310    /// #GVariant is created with the same value as @self. The non-normal parts of
1311    /// @self will be replaced with default values which are guaranteed to be in
1312    /// normal form.
1313    ///
1314    /// It makes sense to call this function if you've received #GVariant
1315    /// data from untrusted sources and you want to ensure your serialized
1316    /// output is definitely in normal form.
1317    ///
1318    /// If @self is already in normal form, a new reference will be returned
1319    /// (which will be floating if @self is floating). If it is not in normal form,
1320    /// the newly created #GVariant will be returned with a single non-floating
1321    /// reference. Typically, g_variant_take_ref() should be called on the return
1322    /// value from this function to guarantee ownership of a single non-floating
1323    /// reference to it.
1324    ///
1325    /// # Returns
1326    ///
1327    /// a trusted #GVariant
1328    #[doc(alias = "g_variant_get_normal_form")]
1329    #[must_use]
1330    pub fn normal_form(&self) -> Self {
1331        unsafe { from_glib_full(ffi::g_variant_get_normal_form(self.to_glib_none().0)) }
1332    }
1333
1334    // rustdoc-stripper-ignore-next
1335    /// Returns a copy of the variant in the opposite endianness.
1336    // rustdoc-stripper-ignore-next-stop
1337    /// Performs a byteswapping operation on the contents of @self.  The
1338    /// result is that all multi-byte numeric data contained in @self is
1339    /// byteswapped.  That includes 16, 32, and 64bit signed and unsigned
1340    /// integers as well as file handles and double precision floating point
1341    /// values.
1342    ///
1343    /// This function is an identity mapping on any value that does not
1344    /// contain multi-byte numeric data.  That include strings, booleans,
1345    /// bytes and containers containing only these things (recursively).
1346    ///
1347    /// While this function can safely handle untrusted, non-normal data, it is
1348    /// recommended to check whether the input is in normal form beforehand, using
1349    /// g_variant_is_normal_form(), and to reject non-normal inputs if your
1350    /// application can be strict about what inputs it rejects.
1351    ///
1352    /// The returned value is always in normal form and is marked as trusted.
1353    /// A full, not floating, reference is returned.
1354    ///
1355    /// # Returns
1356    ///
1357    /// the byteswapped form of @self
1358    #[doc(alias = "g_variant_byteswap")]
1359    #[must_use]
1360    pub fn byteswap(&self) -> Self {
1361        unsafe { from_glib_full(ffi::g_variant_byteswap(self.to_glib_none().0)) }
1362    }
1363
1364    // rustdoc-stripper-ignore-next
1365    /// Determines the number of children in a container GVariant instance.
1366    // rustdoc-stripper-ignore-next-stop
1367    /// Determines the number of children in a container #GVariant instance.
1368    /// This includes variants, maybes, arrays, tuples and dictionary
1369    /// entries.  It is an error to call this function on any other type of
1370    /// #GVariant.
1371    ///
1372    /// For variants, the return value is always 1.  For values with maybe
1373    /// types, it is always zero or one.  For arrays, it is the length of the
1374    /// array.  For tuples it is the number of tuple items (which depends
1375    /// only on the type).  For dictionary entries, it is always 2
1376    ///
1377    /// This function is O(1).
1378    ///
1379    /// # Returns
1380    ///
1381    /// the number of children in the container
1382    #[doc(alias = "g_variant_n_children")]
1383    pub fn n_children(&self) -> usize {
1384        assert!(self.is_container());
1385
1386        unsafe { ffi::g_variant_n_children(self.to_glib_none().0) }
1387    }
1388
1389    // rustdoc-stripper-ignore-next
1390    /// Create an iterator over items in the variant.
1391    ///
1392    /// Note that this heap allocates a variant for each element,
1393    /// which can be particularly expensive for large arrays.
1394    pub fn iter(&self) -> VariantIter {
1395        assert!(self.is_container());
1396
1397        VariantIter::new(self.clone())
1398    }
1399
1400    // rustdoc-stripper-ignore-next
1401    /// Create an iterator over borrowed strings from a GVariant of type `as` (array of string).
1402    ///
1403    /// This will fail if the variant is not an array of with
1404    /// the expected child type.
1405    ///
1406    /// A benefit of this API over [`Self::iter()`] is that it
1407    /// minimizes allocation, and provides strongly typed access.
1408    ///
1409    /// ```
1410    /// # use glib::prelude::*;
1411    /// let strs = &["foo", "bar"];
1412    /// let strs_variant: glib::Variant = strs.to_variant();
1413    /// for s in strs_variant.array_iter_str()? {
1414    ///     println!("{}", s);
1415    /// }
1416    /// # Ok::<(), Box<dyn std::error::Error>>(())
1417    /// ```
1418    pub fn array_iter_str(&self) -> Result<VariantStrIter<'_>, VariantTypeMismatchError> {
1419        let child_ty = String::static_variant_type();
1420        let actual_ty = self.type_();
1421        let expected_ty = child_ty.as_array();
1422        if actual_ty != expected_ty {
1423            return Err(VariantTypeMismatchError {
1424                actual: actual_ty.to_owned(),
1425                expected: expected_ty.into_owned(),
1426            });
1427        }
1428
1429        Ok(VariantStrIter::new(self))
1430    }
1431
1432    // rustdoc-stripper-ignore-next
1433    /// Return whether this Variant is a container type.
1434    // rustdoc-stripper-ignore-next-stop
1435    /// Checks if @self is a container.
1436    ///
1437    /// # Returns
1438    ///
1439    /// [`true`] if @self is a container
1440    #[doc(alias = "g_variant_is_container")]
1441    pub fn is_container(&self) -> bool {
1442        unsafe { from_glib(ffi::g_variant_is_container(self.to_glib_none().0)) }
1443    }
1444
1445    // rustdoc-stripper-ignore-next
1446    /// Return whether this Variant is in normal form.
1447    // rustdoc-stripper-ignore-next-stop
1448    /// Checks if @self is in normal form.
1449    ///
1450    /// The main reason to do this is to detect if a given chunk of
1451    /// serialized data is in normal form: load the data into a #GVariant
1452    /// using g_variant_new_from_data() and then use this function to
1453    /// check.
1454    ///
1455    /// If @self is found to be in normal form then it will be marked as
1456    /// being trusted.  If the value was already marked as being trusted then
1457    /// this function will immediately return [`true`].
1458    ///
1459    /// There may be implementation specific restrictions on deeply nested values.
1460    /// GVariant is guaranteed to handle nesting up to at least 64 levels.
1461    ///
1462    /// # Returns
1463    ///
1464    /// [`true`] if @self is in normal form
1465    #[doc(alias = "g_variant_is_normal_form")]
1466    pub fn is_normal_form(&self) -> bool {
1467        unsafe { from_glib(ffi::g_variant_is_normal_form(self.to_glib_none().0)) }
1468    }
1469
1470    // rustdoc-stripper-ignore-next
1471    /// Return whether input string is a valid `VariantClass::ObjectPath`.
1472    // rustdoc-stripper-ignore-next-stop
1473    /// Determines if a given string is a valid D-Bus object path.  You
1474    /// should ensure that a string is a valid D-Bus object path before
1475    /// passing it to g_variant_new_object_path().
1476    ///
1477    /// A valid object path starts with `/` followed by zero or more
1478    /// sequences of characters separated by `/` characters.  Each sequence
1479    /// must contain only the characters `[A-Z][a-z][0-9]_`.  No sequence
1480    /// (including the one following the final `/` character) may be empty.
1481    /// ## `string`
1482    /// a normal C nul-terminated string
1483    ///
1484    /// # Returns
1485    ///
1486    /// [`true`] if @string is a D-Bus object path
1487    #[doc(alias = "g_variant_is_object_path")]
1488    pub fn is_object_path(string: &str) -> bool {
1489        unsafe { from_glib(ffi::g_variant_is_object_path(string.to_glib_none().0)) }
1490    }
1491
1492    // rustdoc-stripper-ignore-next
1493    /// Return whether input string is a valid `VariantClass::Signature`.
1494    // rustdoc-stripper-ignore-next-stop
1495    /// Determines if a given string is a valid D-Bus type signature.  You
1496    /// should ensure that a string is a valid D-Bus type signature before
1497    /// passing it to g_variant_new_signature().
1498    ///
1499    /// D-Bus type signatures consist of zero or more definite #GVariantType
1500    /// strings in sequence.
1501    /// ## `string`
1502    /// a normal C nul-terminated string
1503    ///
1504    /// # Returns
1505    ///
1506    /// [`true`] if @string is a D-Bus type signature
1507    #[doc(alias = "g_variant_is_signature")]
1508    pub fn is_signature(string: &str) -> bool {
1509        unsafe { from_glib(ffi::g_variant_is_signature(string.to_glib_none().0)) }
1510    }
1511}
1512
1513unsafe impl Send for Variant {}
1514unsafe impl Sync for Variant {}
1515
1516impl fmt::Debug for Variant {
1517    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1518        f.debug_struct("Variant")
1519            .field("ptr", &ToGlibPtr::<*const _>::to_glib_none(self).0)
1520            .field("type", &self.type_())
1521            .field("value", &self.to_string())
1522            .finish()
1523    }
1524}
1525
1526impl fmt::Display for Variant {
1527    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1528        f.write_str(&self.print(true))
1529    }
1530}
1531
1532impl str::FromStr for Variant {
1533    type Err = crate::Error;
1534
1535    fn from_str(s: &str) -> Result<Self, Self::Err> {
1536        Self::parse(None, s)
1537    }
1538}
1539
1540impl PartialEq for Variant {
1541    #[doc(alias = "g_variant_equal")]
1542    fn eq(&self, other: &Self) -> bool {
1543        unsafe {
1544            from_glib(ffi::g_variant_equal(
1545                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
1546                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
1547            ))
1548        }
1549    }
1550}
1551
1552impl Eq for Variant {}
1553
1554impl PartialOrd for Variant {
1555    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1556        unsafe {
1557            if ffi::g_variant_classify(self.to_glib_none().0)
1558                != ffi::g_variant_classify(other.to_glib_none().0)
1559            {
1560                return None;
1561            }
1562
1563            if self.is_container() {
1564                return None;
1565            }
1566
1567            let res = ffi::g_variant_compare(
1568                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
1569                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
1570            );
1571
1572            Some(res.cmp(&0))
1573        }
1574    }
1575}
1576
1577impl Hash for Variant {
1578    #[doc(alias = "g_variant_hash")]
1579    fn hash<H: Hasher>(&self, state: &mut H) {
1580        unsafe {
1581            state.write_u32(ffi::g_variant_hash(
1582                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
1583            ))
1584        }
1585    }
1586}
1587
1588impl AsRef<Variant> for Variant {
1589    #[inline]
1590    fn as_ref(&self) -> &Self {
1591        self
1592    }
1593}
1594
1595// rustdoc-stripper-ignore-next
1596/// Converts to `Variant`.
1597pub trait ToVariant {
1598    // rustdoc-stripper-ignore-next
1599    /// Returns a `Variant` clone of `self`.
1600    fn to_variant(&self) -> Variant;
1601}
1602
1603// rustdoc-stripper-ignore-next
1604/// Extracts a value.
1605pub trait FromVariant: Sized + StaticVariantType {
1606    // rustdoc-stripper-ignore-next
1607    /// Tries to extract a value.
1608    ///
1609    /// Returns `Some` if the variant's type matches `Self`.
1610    fn from_variant(variant: &Variant) -> Option<Self>;
1611}
1612
1613// rustdoc-stripper-ignore-next
1614/// Returns `VariantType` of `Self`.
1615pub trait StaticVariantType {
1616    // rustdoc-stripper-ignore-next
1617    /// Returns the `VariantType` corresponding to `Self`.
1618    fn static_variant_type() -> Cow<'static, VariantTy>;
1619}
1620
1621impl StaticVariantType for Variant {
1622    fn static_variant_type() -> Cow<'static, VariantTy> {
1623        Cow::Borrowed(VariantTy::VARIANT)
1624    }
1625}
1626
1627impl<T: ?Sized + ToVariant> ToVariant for &T {
1628    fn to_variant(&self) -> Variant {
1629        <T as ToVariant>::to_variant(self)
1630    }
1631}
1632
1633impl<'a, T: Into<Variant> + Clone> From<&'a T> for Variant {
1634    #[inline]
1635    fn from(v: &'a T) -> Self {
1636        v.clone().into()
1637    }
1638}
1639
1640impl<T: ?Sized + StaticVariantType> StaticVariantType for &T {
1641    fn static_variant_type() -> Cow<'static, VariantTy> {
1642        <T as StaticVariantType>::static_variant_type()
1643    }
1644}
1645
1646macro_rules! impl_numeric {
1647    ($name:ty, $typ:expr, $new_fn:ident, $get_fn:ident) => {
1648        impl StaticVariantType for $name {
1649            fn static_variant_type() -> Cow<'static, VariantTy> {
1650                Cow::Borrowed($typ)
1651            }
1652        }
1653
1654        impl ToVariant for $name {
1655            fn to_variant(&self) -> Variant {
1656                unsafe { from_glib_none(ffi::$new_fn(*self)) }
1657            }
1658        }
1659
1660        impl From<$name> for Variant {
1661            #[inline]
1662            fn from(v: $name) -> Self {
1663                v.to_variant()
1664            }
1665        }
1666
1667        impl FromVariant for $name {
1668            fn from_variant(variant: &Variant) -> Option<Self> {
1669                unsafe {
1670                    if variant.is::<Self>() {
1671                        Some(ffi::$get_fn(variant.to_glib_none().0))
1672                    } else {
1673                        None
1674                    }
1675                }
1676            }
1677        }
1678    };
1679}
1680
1681impl_numeric!(u8, VariantTy::BYTE, g_variant_new_byte, g_variant_get_byte);
1682impl_numeric!(
1683    i16,
1684    VariantTy::INT16,
1685    g_variant_new_int16,
1686    g_variant_get_int16
1687);
1688impl_numeric!(
1689    u16,
1690    VariantTy::UINT16,
1691    g_variant_new_uint16,
1692    g_variant_get_uint16
1693);
1694impl_numeric!(
1695    i32,
1696    VariantTy::INT32,
1697    g_variant_new_int32,
1698    g_variant_get_int32
1699);
1700impl_numeric!(
1701    u32,
1702    VariantTy::UINT32,
1703    g_variant_new_uint32,
1704    g_variant_get_uint32
1705);
1706impl_numeric!(
1707    i64,
1708    VariantTy::INT64,
1709    g_variant_new_int64,
1710    g_variant_get_int64
1711);
1712impl_numeric!(
1713    u64,
1714    VariantTy::UINT64,
1715    g_variant_new_uint64,
1716    g_variant_get_uint64
1717);
1718impl_numeric!(
1719    f64,
1720    VariantTy::DOUBLE,
1721    g_variant_new_double,
1722    g_variant_get_double
1723);
1724
1725impl StaticVariantType for () {
1726    fn static_variant_type() -> Cow<'static, VariantTy> {
1727        Cow::Borrowed(VariantTy::UNIT)
1728    }
1729}
1730
1731impl ToVariant for () {
1732    fn to_variant(&self) -> Variant {
1733        unsafe { from_glib_none(ffi::g_variant_new_tuple(ptr::null(), 0)) }
1734    }
1735}
1736
1737impl From<()> for Variant {
1738    #[inline]
1739    fn from(_: ()) -> Self {
1740        ().to_variant()
1741    }
1742}
1743
1744impl FromVariant for () {
1745    fn from_variant(variant: &Variant) -> Option<Self> {
1746        if variant.is::<Self>() { Some(()) } else { None }
1747    }
1748}
1749
1750impl StaticVariantType for bool {
1751    fn static_variant_type() -> Cow<'static, VariantTy> {
1752        Cow::Borrowed(VariantTy::BOOLEAN)
1753    }
1754}
1755
1756impl ToVariant for bool {
1757    fn to_variant(&self) -> Variant {
1758        unsafe { from_glib_none(ffi::g_variant_new_boolean(self.into_glib())) }
1759    }
1760}
1761
1762impl From<bool> for Variant {
1763    #[inline]
1764    fn from(v: bool) -> Self {
1765        v.to_variant()
1766    }
1767}
1768
1769impl FromVariant for bool {
1770    fn from_variant(variant: &Variant) -> Option<Self> {
1771        unsafe {
1772            if variant.is::<Self>() {
1773                Some(from_glib(ffi::g_variant_get_boolean(
1774                    variant.to_glib_none().0,
1775                )))
1776            } else {
1777                None
1778            }
1779        }
1780    }
1781}
1782
1783impl StaticVariantType for String {
1784    fn static_variant_type() -> Cow<'static, VariantTy> {
1785        Cow::Borrowed(VariantTy::STRING)
1786    }
1787}
1788
1789impl ToVariant for String {
1790    fn to_variant(&self) -> Variant {
1791        self[..].to_variant()
1792    }
1793}
1794
1795impl From<String> for Variant {
1796    #[inline]
1797    fn from(s: String) -> Self {
1798        s.to_variant()
1799    }
1800}
1801
1802impl FromVariant for String {
1803    fn from_variant(variant: &Variant) -> Option<Self> {
1804        variant.str().map(String::from)
1805    }
1806}
1807
1808impl StaticVariantType for str {
1809    fn static_variant_type() -> Cow<'static, VariantTy> {
1810        String::static_variant_type()
1811    }
1812}
1813
1814impl ToVariant for str {
1815    fn to_variant(&self) -> Variant {
1816        unsafe { from_glib_none(ffi::g_variant_new_take_string(self.to_glib_full())) }
1817    }
1818}
1819
1820impl From<&str> for Variant {
1821    #[inline]
1822    fn from(s: &str) -> Self {
1823        s.to_variant()
1824    }
1825}
1826
1827impl StaticVariantType for std::path::PathBuf {
1828    fn static_variant_type() -> Cow<'static, VariantTy> {
1829        std::path::Path::static_variant_type()
1830    }
1831}
1832
1833impl ToVariant for std::path::PathBuf {
1834    fn to_variant(&self) -> Variant {
1835        self.as_path().to_variant()
1836    }
1837}
1838
1839impl From<std::path::PathBuf> for Variant {
1840    #[inline]
1841    fn from(p: std::path::PathBuf) -> Self {
1842        p.to_variant()
1843    }
1844}
1845
1846impl FromVariant for std::path::PathBuf {
1847    fn from_variant(variant: &Variant) -> Option<Self> {
1848        unsafe {
1849            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
1850            Some(crate::translate::c_to_path_buf(ptr as *const _))
1851        }
1852    }
1853}
1854
1855impl StaticVariantType for std::path::Path {
1856    fn static_variant_type() -> Cow<'static, VariantTy> {
1857        <&[u8]>::static_variant_type()
1858    }
1859}
1860
1861impl ToVariant for std::path::Path {
1862    fn to_variant(&self) -> Variant {
1863        let tmp = crate::translate::path_to_c(self);
1864        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
1865    }
1866}
1867
1868impl From<&std::path::Path> for Variant {
1869    #[inline]
1870    fn from(p: &std::path::Path) -> Self {
1871        p.to_variant()
1872    }
1873}
1874
1875impl StaticVariantType for std::ffi::OsString {
1876    fn static_variant_type() -> Cow<'static, VariantTy> {
1877        std::ffi::OsStr::static_variant_type()
1878    }
1879}
1880
1881impl ToVariant for std::ffi::OsString {
1882    fn to_variant(&self) -> Variant {
1883        self.as_os_str().to_variant()
1884    }
1885}
1886
1887impl From<std::ffi::OsString> for Variant {
1888    #[inline]
1889    fn from(s: std::ffi::OsString) -> Self {
1890        s.to_variant()
1891    }
1892}
1893
1894impl FromVariant for std::ffi::OsString {
1895    fn from_variant(variant: &Variant) -> Option<Self> {
1896        unsafe {
1897            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
1898            Some(crate::translate::c_to_os_string(ptr as *const _))
1899        }
1900    }
1901}
1902
1903impl StaticVariantType for std::ffi::OsStr {
1904    fn static_variant_type() -> Cow<'static, VariantTy> {
1905        <&[u8]>::static_variant_type()
1906    }
1907}
1908
1909impl ToVariant for std::ffi::OsStr {
1910    fn to_variant(&self) -> Variant {
1911        let tmp = crate::translate::os_str_to_c(self);
1912        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
1913    }
1914}
1915
1916impl From<&std::ffi::OsStr> for Variant {
1917    #[inline]
1918    fn from(s: &std::ffi::OsStr) -> Self {
1919        s.to_variant()
1920    }
1921}
1922
1923impl<T: StaticVariantType> StaticVariantType for Option<T> {
1924    fn static_variant_type() -> Cow<'static, VariantTy> {
1925        Cow::Owned(VariantType::new_maybe(&T::static_variant_type()))
1926    }
1927}
1928
1929impl<T: StaticVariantType + ToVariant> ToVariant for Option<T> {
1930    fn to_variant(&self) -> Variant {
1931        Variant::from_maybe::<T>(self.as_ref().map(|m| m.to_variant()).as_ref())
1932    }
1933}
1934
1935impl<T: StaticVariantType + Into<Variant>> From<Option<T>> for Variant {
1936    #[inline]
1937    fn from(v: Option<T>) -> Self {
1938        Variant::from_maybe::<T>(v.map(|v| v.into()).as_ref())
1939    }
1940}
1941
1942impl<T: StaticVariantType + FromVariant> FromVariant for Option<T> {
1943    fn from_variant(variant: &Variant) -> Option<Self> {
1944        unsafe {
1945            if variant.is::<Self>() {
1946                let c_child = ffi::g_variant_get_maybe(variant.to_glib_none().0);
1947                if !c_child.is_null() {
1948                    let child: Variant = from_glib_full(c_child);
1949
1950                    Some(T::from_variant(&child))
1951                } else {
1952                    Some(None)
1953                }
1954            } else {
1955                None
1956            }
1957        }
1958    }
1959}
1960
1961impl<T: StaticVariantType> StaticVariantType for [T] {
1962    fn static_variant_type() -> Cow<'static, VariantTy> {
1963        T::static_variant_type().as_array()
1964    }
1965}
1966
1967impl<T: StaticVariantType + ToVariant> ToVariant for [T] {
1968    fn to_variant(&self) -> Variant {
1969        unsafe {
1970            if self.is_empty() {
1971                return from_glib_none(ffi::g_variant_new_array(
1972                    T::static_variant_type().to_glib_none().0,
1973                    ptr::null(),
1974                    0,
1975                ));
1976            }
1977
1978            let mut builder = mem::MaybeUninit::uninit();
1979            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
1980            let mut builder = builder.assume_init();
1981            for value in self {
1982                let value = value.to_variant();
1983                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
1984            }
1985            from_glib_none(ffi::g_variant_builder_end(&mut builder))
1986        }
1987    }
1988}
1989
1990impl<T: StaticVariantType + ToVariant> From<&[T]> for Variant {
1991    #[inline]
1992    fn from(s: &[T]) -> Self {
1993        s.to_variant()
1994    }
1995}
1996
1997impl<T: FromVariant> FromVariant for Vec<T> {
1998    fn from_variant(variant: &Variant) -> Option<Self> {
1999        if !variant.is_container() {
2000            return None;
2001        }
2002
2003        let mut vec = Vec::with_capacity(variant.n_children());
2004
2005        for i in 0..variant.n_children() {
2006            match variant.child_value(i).get() {
2007                Some(child) => vec.push(child),
2008                None => return None,
2009            }
2010        }
2011
2012        Some(vec)
2013    }
2014}
2015
2016impl<T: StaticVariantType + ToVariant> ToVariant for Vec<T> {
2017    fn to_variant(&self) -> Variant {
2018        self.as_slice().to_variant()
2019    }
2020}
2021
2022impl<T: StaticVariantType + Into<Variant>> From<Vec<T>> for Variant {
2023    fn from(v: Vec<T>) -> Self {
2024        unsafe {
2025            if v.is_empty() {
2026                return from_glib_none(ffi::g_variant_new_array(
2027                    T::static_variant_type().to_glib_none().0,
2028                    ptr::null(),
2029                    0,
2030                ));
2031            }
2032
2033            let mut builder = mem::MaybeUninit::uninit();
2034            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
2035            let mut builder = builder.assume_init();
2036            for value in v {
2037                let value = value.into();
2038                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
2039            }
2040            from_glib_none(ffi::g_variant_builder_end(&mut builder))
2041        }
2042    }
2043}
2044
2045impl<T: StaticVariantType> StaticVariantType for Vec<T> {
2046    fn static_variant_type() -> Cow<'static, VariantTy> {
2047        <[T]>::static_variant_type()
2048    }
2049}
2050
2051impl<K, V, H> FromVariant for HashMap<K, V, H>
2052where
2053    K: FromVariant + Eq + Hash,
2054    V: FromVariant,
2055    H: BuildHasher + Default,
2056{
2057    fn from_variant(variant: &Variant) -> Option<Self> {
2058        if !variant.is_container() {
2059            return None;
2060        }
2061
2062        let mut map = HashMap::default();
2063
2064        for i in 0..variant.n_children() {
2065            let entry = variant.child_value(i);
2066            let key = entry.child_value(0).get()?;
2067            let val = entry.child_value(1).get()?;
2068
2069            map.insert(key, val);
2070        }
2071
2072        Some(map)
2073    }
2074}
2075
2076impl<K, V> FromVariant for BTreeMap<K, V>
2077where
2078    K: FromVariant + Eq + Ord,
2079    V: FromVariant,
2080{
2081    fn from_variant(variant: &Variant) -> Option<Self> {
2082        if !variant.is_container() {
2083            return None;
2084        }
2085
2086        let mut map = BTreeMap::default();
2087
2088        for i in 0..variant.n_children() {
2089            let entry = variant.child_value(i);
2090            let key = entry.child_value(0).get()?;
2091            let val = entry.child_value(1).get()?;
2092
2093            map.insert(key, val);
2094        }
2095
2096        Some(map)
2097    }
2098}
2099
2100impl<K, V> ToVariant for HashMap<K, V>
2101where
2102    K: StaticVariantType + ToVariant + Eq + Hash,
2103    V: StaticVariantType + ToVariant,
2104{
2105    fn to_variant(&self) -> Variant {
2106        unsafe {
2107            if self.is_empty() {
2108                return from_glib_none(ffi::g_variant_new_array(
2109                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
2110                    ptr::null(),
2111                    0,
2112                ));
2113            }
2114
2115            let mut builder = mem::MaybeUninit::uninit();
2116            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
2117            let mut builder = builder.assume_init();
2118            for (key, value) in self {
2119                let entry = DictEntry::new(key, value).to_variant();
2120                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
2121            }
2122            from_glib_none(ffi::g_variant_builder_end(&mut builder))
2123        }
2124    }
2125}
2126
2127impl<K, V> From<HashMap<K, V>> for Variant
2128where
2129    K: StaticVariantType + Into<Variant> + Eq + Hash,
2130    V: StaticVariantType + Into<Variant>,
2131{
2132    fn from(m: HashMap<K, V>) -> Self {
2133        unsafe {
2134            if m.is_empty() {
2135                return from_glib_none(ffi::g_variant_new_array(
2136                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
2137                    ptr::null(),
2138                    0,
2139                ));
2140            }
2141
2142            let mut builder = mem::MaybeUninit::uninit();
2143            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
2144            let mut builder = builder.assume_init();
2145            for (key, value) in m {
2146                let entry = Variant::from(DictEntry::new(key, value));
2147                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
2148            }
2149            from_glib_none(ffi::g_variant_builder_end(&mut builder))
2150        }
2151    }
2152}
2153
2154impl<K, V> ToVariant for BTreeMap<K, V>
2155where
2156    K: StaticVariantType + ToVariant + Eq + Hash,
2157    V: StaticVariantType + ToVariant,
2158{
2159    fn to_variant(&self) -> Variant {
2160        unsafe {
2161            if self.is_empty() {
2162                return from_glib_none(ffi::g_variant_new_array(
2163                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
2164                    ptr::null(),
2165                    0,
2166                ));
2167            }
2168
2169            let mut builder = mem::MaybeUninit::uninit();
2170            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
2171            let mut builder = builder.assume_init();
2172            for (key, value) in self {
2173                let entry = DictEntry::new(key, value).to_variant();
2174                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
2175            }
2176            from_glib_none(ffi::g_variant_builder_end(&mut builder))
2177        }
2178    }
2179}
2180
2181impl<K, V> From<BTreeMap<K, V>> for Variant
2182where
2183    K: StaticVariantType + Into<Variant> + Eq + Hash,
2184    V: StaticVariantType + Into<Variant>,
2185{
2186    fn from(m: BTreeMap<K, V>) -> Self {
2187        unsafe {
2188            if m.is_empty() {
2189                return from_glib_none(ffi::g_variant_new_array(
2190                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
2191                    ptr::null(),
2192                    0,
2193                ));
2194            }
2195
2196            let mut builder = mem::MaybeUninit::uninit();
2197            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
2198            let mut builder = builder.assume_init();
2199            for (key, value) in m {
2200                let entry = Variant::from(DictEntry::new(key, value));
2201                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
2202            }
2203            from_glib_none(ffi::g_variant_builder_end(&mut builder))
2204        }
2205    }
2206}
2207
2208/// A Dictionary entry.
2209///
2210/// While GVariant format allows a dictionary entry to be an independent type, typically you'll need
2211/// to use this in a dictionary, which is simply an array of dictionary entries. The following code
2212/// creates a dictionary:
2213///
2214/// ```
2215///# use glib::prelude::*; // or `use gtk::prelude::*;`
2216/// use glib::variant::{Variant, FromVariant, DictEntry};
2217///
2218/// let entries = [
2219///     DictEntry::new("uuid", 1000u32),
2220///     DictEntry::new("guid", 1001u32),
2221/// ];
2222/// let dict = entries.into_iter().collect::<Variant>();
2223/// assert_eq!(dict.n_children(), 2);
2224/// assert_eq!(dict.type_().as_str(), "a{su}");
2225/// ```
2226#[derive(Debug, Clone)]
2227pub struct DictEntry<K, V> {
2228    key: K,
2229    value: V,
2230}
2231
2232impl<K, V> DictEntry<K, V>
2233where
2234    K: StaticVariantType,
2235    V: StaticVariantType,
2236{
2237    pub fn new(key: K, value: V) -> Self {
2238        Self { key, value }
2239    }
2240
2241    pub fn key(&self) -> &K {
2242        &self.key
2243    }
2244
2245    pub fn value(&self) -> &V {
2246        &self.value
2247    }
2248}
2249
2250impl<K, V> FromVariant for DictEntry<K, V>
2251where
2252    K: FromVariant,
2253    V: FromVariant,
2254{
2255    fn from_variant(variant: &Variant) -> Option<Self> {
2256        if !variant.type_().is_subtype_of(VariantTy::DICT_ENTRY) {
2257            return None;
2258        }
2259
2260        let key = variant.child_value(0).get()?;
2261        let value = variant.child_value(1).get()?;
2262
2263        Some(Self { key, value })
2264    }
2265}
2266
2267impl<K, V> ToVariant for DictEntry<K, V>
2268where
2269    K: StaticVariantType + ToVariant,
2270    V: StaticVariantType + ToVariant,
2271{
2272    fn to_variant(&self) -> Variant {
2273        Variant::from_dict_entry(&self.key.to_variant(), &self.value.to_variant())
2274    }
2275}
2276
2277impl<K, V> From<DictEntry<K, V>> for Variant
2278where
2279    K: StaticVariantType + Into<Variant>,
2280    V: StaticVariantType + Into<Variant>,
2281{
2282    fn from(e: DictEntry<K, V>) -> Self {
2283        Variant::from_dict_entry(&e.key.into(), &e.value.into())
2284    }
2285}
2286
2287impl ToVariant for Variant {
2288    fn to_variant(&self) -> Variant {
2289        Variant::from_variant(self)
2290    }
2291}
2292
2293impl FromVariant for Variant {
2294    fn from_variant(variant: &Variant) -> Option<Self> {
2295        variant.as_variant()
2296    }
2297}
2298
2299impl<K: StaticVariantType, V: StaticVariantType> StaticVariantType for DictEntry<K, V> {
2300    fn static_variant_type() -> Cow<'static, VariantTy> {
2301        Cow::Owned(VariantType::new_dict_entry(
2302            &K::static_variant_type(),
2303            &V::static_variant_type(),
2304        ))
2305    }
2306}
2307
2308fn static_variant_mapping<K, V>() -> Cow<'static, VariantTy>
2309where
2310    K: StaticVariantType,
2311    V: StaticVariantType,
2312{
2313    use std::fmt::Write;
2314
2315    let key_type = K::static_variant_type();
2316    let value_type = V::static_variant_type();
2317
2318    if key_type == VariantTy::STRING && value_type == VariantTy::VARIANT {
2319        return Cow::Borrowed(VariantTy::VARDICT);
2320    }
2321
2322    let mut builder = crate::GStringBuilder::default();
2323    write!(builder, "a{{{}{}}}", key_type.as_str(), value_type.as_str()).unwrap();
2324
2325    Cow::Owned(VariantType::from_string(builder.into_string()).unwrap())
2326}
2327
2328impl<K, V, H> StaticVariantType for HashMap<K, V, H>
2329where
2330    K: StaticVariantType,
2331    V: StaticVariantType,
2332    H: BuildHasher + Default,
2333{
2334    fn static_variant_type() -> Cow<'static, VariantTy> {
2335        static_variant_mapping::<K, V>()
2336    }
2337}
2338
2339impl<K, V> StaticVariantType for BTreeMap<K, V>
2340where
2341    K: StaticVariantType,
2342    V: StaticVariantType,
2343{
2344    fn static_variant_type() -> Cow<'static, VariantTy> {
2345        static_variant_mapping::<K, V>()
2346    }
2347}
2348
2349macro_rules! tuple_impls {
2350    ($($len:expr => ($($n:tt $name:ident)+))+) => {
2351        $(
2352            impl<$($name),+> StaticVariantType for ($($name,)+)
2353            where
2354                $($name: StaticVariantType,)+
2355            {
2356                fn static_variant_type() -> Cow<'static, VariantTy> {
2357                    Cow::Owned(VariantType::new_tuple(&[
2358                        $(
2359                            $name::static_variant_type(),
2360                        )+
2361                    ]))
2362                }
2363            }
2364
2365            impl<$($name),+> FromVariant for ($($name,)+)
2366            where
2367                $($name: FromVariant,)+
2368            {
2369                fn from_variant(variant: &Variant) -> Option<Self> {
2370                    if !variant.type_().is_subtype_of(VariantTy::TUPLE) {
2371                        return None;
2372                    }
2373
2374                    Some((
2375                        $(
2376                            match variant.try_child_get::<$name>($n) {
2377                                Ok(Some(field)) => field,
2378                                _ => return None,
2379                            },
2380                        )+
2381                    ))
2382                }
2383            }
2384
2385            impl<$($name),+> ToVariant for ($($name,)+)
2386            where
2387                $($name: ToVariant,)+
2388            {
2389                fn to_variant(&self) -> Variant {
2390                    unsafe {
2391                        let mut builder = mem::MaybeUninit::uninit();
2392                        ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
2393                        let mut builder = builder.assume_init();
2394
2395                        $(
2396                            let field = self.$n.to_variant();
2397                            ffi::g_variant_builder_add_value(&mut builder, field.to_glib_none().0);
2398                        )+
2399
2400                        from_glib_none(ffi::g_variant_builder_end(&mut builder))
2401                    }
2402                }
2403            }
2404
2405            impl<$($name),+> From<($($name,)+)> for Variant
2406            where
2407                $($name: Into<Variant>,)+
2408            {
2409                fn from(t: ($($name,)+)) -> Self {
2410                    unsafe {
2411                        let mut builder = mem::MaybeUninit::uninit();
2412                        ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
2413                        let mut builder = builder.assume_init();
2414
2415                        $(
2416                            let field = t.$n.into();
2417                            ffi::g_variant_builder_add_value(&mut builder, field.to_glib_none().0);
2418                        )+
2419
2420                        from_glib_none(ffi::g_variant_builder_end(&mut builder))
2421                    }
2422                }
2423            }
2424        )+
2425    }
2426}
2427
2428tuple_impls! {
2429    1 => (0 T0)
2430    2 => (0 T0 1 T1)
2431    3 => (0 T0 1 T1 2 T2)
2432    4 => (0 T0 1 T1 2 T2 3 T3)
2433    5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
2434    6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
2435    7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
2436    8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
2437    9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
2438    10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
2439    11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
2440    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)
2441    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)
2442    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)
2443    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)
2444    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)
2445}
2446
2447impl<T: Into<Variant> + StaticVariantType> FromIterator<T> for Variant {
2448    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2449        Variant::array_from_iter::<T>(iter.into_iter().map(|v| v.into()))
2450    }
2451}
2452
2453/// Trait for fixed size variant types.
2454pub unsafe trait FixedSizeVariantType: StaticVariantType + Sized + Copy {}
2455unsafe impl FixedSizeVariantType for u8 {}
2456unsafe impl FixedSizeVariantType for i16 {}
2457unsafe impl FixedSizeVariantType for u16 {}
2458unsafe impl FixedSizeVariantType for i32 {}
2459unsafe impl FixedSizeVariantType for u32 {}
2460unsafe impl FixedSizeVariantType for i64 {}
2461unsafe impl FixedSizeVariantType for u64 {}
2462unsafe impl FixedSizeVariantType for f64 {}
2463unsafe impl FixedSizeVariantType for bool {}
2464
2465/// Wrapper type for fixed size type arrays.
2466///
2467/// Converting this from/to a `Variant` is generally more efficient than working on the type
2468/// directly. This is especially important when deriving `Variant` trait implementations on custom
2469/// types.
2470///
2471/// This wrapper type can hold for example `Vec<u8>`, `Box<[u8]>` and similar types.
2472#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2473pub struct FixedSizeVariantArray<A, T>(A, std::marker::PhantomData<T>)
2474where
2475    A: AsRef<[T]>,
2476    T: FixedSizeVariantType;
2477
2478impl<A: AsRef<[T]>, T: FixedSizeVariantType> From<A> for FixedSizeVariantArray<A, T> {
2479    fn from(array: A) -> Self {
2480        FixedSizeVariantArray(array, std::marker::PhantomData)
2481    }
2482}
2483
2484impl<A: AsRef<[T]>, T: FixedSizeVariantType> FixedSizeVariantArray<A, T> {
2485    pub fn into_inner(self) -> A {
2486        self.0
2487    }
2488}
2489
2490impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::Deref for FixedSizeVariantArray<A, T> {
2491    type Target = A;
2492
2493    #[inline]
2494    fn deref(&self) -> &Self::Target {
2495        &self.0
2496    }
2497}
2498
2499impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::DerefMut for FixedSizeVariantArray<A, T> {
2500    #[inline]
2501    fn deref_mut(&mut self) -> &mut Self::Target {
2502        &mut self.0
2503    }
2504}
2505
2506impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<A> for FixedSizeVariantArray<A, T> {
2507    #[inline]
2508    fn as_ref(&self) -> &A {
2509        &self.0
2510    }
2511}
2512
2513impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsMut<A> for FixedSizeVariantArray<A, T> {
2514    #[inline]
2515    fn as_mut(&mut self) -> &mut A {
2516        &mut self.0
2517    }
2518}
2519
2520impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<[T]> for FixedSizeVariantArray<A, T> {
2521    #[inline]
2522    fn as_ref(&self) -> &[T] {
2523        self.0.as_ref()
2524    }
2525}
2526
2527impl<A: AsRef<[T]> + AsMut<[T]>, T: FixedSizeVariantType> AsMut<[T]>
2528    for FixedSizeVariantArray<A, T>
2529{
2530    #[inline]
2531    fn as_mut(&mut self) -> &mut [T] {
2532        self.0.as_mut()
2533    }
2534}
2535
2536impl<A: AsRef<[T]>, T: FixedSizeVariantType> StaticVariantType for FixedSizeVariantArray<A, T> {
2537    fn static_variant_type() -> Cow<'static, VariantTy> {
2538        <[T]>::static_variant_type()
2539    }
2540}
2541
2542impl<A: AsRef<[T]> + for<'a> From<&'a [T]>, T: FixedSizeVariantType> FromVariant
2543    for FixedSizeVariantArray<A, T>
2544{
2545    fn from_variant(variant: &Variant) -> Option<Self> {
2546        Some(FixedSizeVariantArray(
2547            A::from(variant.fixed_array::<T>().ok()?),
2548            std::marker::PhantomData,
2549        ))
2550    }
2551}
2552
2553impl<A: AsRef<[T]>, T: FixedSizeVariantType> ToVariant for FixedSizeVariantArray<A, T> {
2554    fn to_variant(&self) -> Variant {
2555        Variant::array_from_fixed_array(self.0.as_ref())
2556    }
2557}
2558
2559impl<A: AsRef<[T]>, T: FixedSizeVariantType> From<FixedSizeVariantArray<A, T>> for Variant {
2560    #[doc(alias = "g_variant_new_from_data")]
2561    fn from(a: FixedSizeVariantArray<A, T>) -> Self {
2562        unsafe {
2563            let data = Box::new(a.0);
2564            let (data_ptr, len) = {
2565                let data = (*data).as_ref();
2566                (data.as_ptr(), mem::size_of_val(data))
2567            };
2568
2569            unsafe extern "C" fn free_data<A: AsRef<[T]>, T: FixedSizeVariantType>(
2570                ptr: ffi::gpointer,
2571            ) {
2572                unsafe {
2573                    let _ = Box::from_raw(ptr as *mut A);
2574                }
2575            }
2576
2577            from_glib_none(ffi::g_variant_new_from_data(
2578                T::static_variant_type().to_glib_none().0,
2579                data_ptr as ffi::gconstpointer,
2580                len,
2581                false.into_glib(),
2582                Some(free_data::<A, T>),
2583                Box::into_raw(data) as ffi::gpointer,
2584            ))
2585        }
2586    }
2587}
2588
2589/// A wrapper type around `Variant` handles.
2590#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2591pub struct Handle(pub i32);
2592
2593impl From<i32> for Handle {
2594    fn from(v: i32) -> Self {
2595        Handle(v)
2596    }
2597}
2598
2599impl From<Handle> for i32 {
2600    fn from(v: Handle) -> Self {
2601        v.0
2602    }
2603}
2604
2605impl StaticVariantType for Handle {
2606    fn static_variant_type() -> Cow<'static, VariantTy> {
2607        Cow::Borrowed(VariantTy::HANDLE)
2608    }
2609}
2610
2611impl ToVariant for Handle {
2612    fn to_variant(&self) -> Variant {
2613        unsafe { from_glib_none(ffi::g_variant_new_handle(self.0)) }
2614    }
2615}
2616
2617impl From<Handle> for Variant {
2618    #[inline]
2619    fn from(h: Handle) -> Self {
2620        h.to_variant()
2621    }
2622}
2623
2624impl FromVariant for Handle {
2625    fn from_variant(variant: &Variant) -> Option<Self> {
2626        unsafe {
2627            if variant.is::<Self>() {
2628                Some(Handle(ffi::g_variant_get_handle(variant.to_glib_none().0)))
2629            } else {
2630                None
2631            }
2632        }
2633    }
2634}
2635
2636/// A wrapper type around `Variant` object paths.
2637///
2638/// Values of these type are guaranteed to be valid object paths.
2639#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2640pub struct ObjectPath(String);
2641
2642impl ObjectPath {
2643    pub fn as_str(&self) -> &str {
2644        &self.0
2645    }
2646}
2647
2648impl Display for ObjectPath {
2649    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2650        self.0.fmt(f)
2651    }
2652}
2653
2654impl std::ops::Deref for ObjectPath {
2655    type Target = str;
2656
2657    #[inline]
2658    fn deref(&self) -> &Self::Target {
2659        &self.0
2660    }
2661}
2662
2663impl TryFrom<String> for ObjectPath {
2664    type Error = crate::BoolError;
2665
2666    fn try_from(v: String) -> Result<Self, Self::Error> {
2667        if !Variant::is_object_path(&v) {
2668            return Err(bool_error!("Invalid object path"));
2669        }
2670
2671        Ok(ObjectPath(v))
2672    }
2673}
2674
2675impl<'a> TryFrom<&'a str> for ObjectPath {
2676    type Error = crate::BoolError;
2677
2678    fn try_from(v: &'a str) -> Result<Self, Self::Error> {
2679        ObjectPath::try_from(String::from(v))
2680    }
2681}
2682
2683impl From<ObjectPath> for String {
2684    fn from(v: ObjectPath) -> Self {
2685        v.0
2686    }
2687}
2688
2689impl StaticVariantType for ObjectPath {
2690    fn static_variant_type() -> Cow<'static, VariantTy> {
2691        Cow::Borrowed(VariantTy::OBJECT_PATH)
2692    }
2693}
2694
2695impl ToVariant for ObjectPath {
2696    fn to_variant(&self) -> Variant {
2697        unsafe { from_glib_none(ffi::g_variant_new_object_path(self.0.to_glib_none().0)) }
2698    }
2699}
2700
2701impl From<ObjectPath> for Variant {
2702    #[inline]
2703    fn from(p: ObjectPath) -> Self {
2704        let mut s = p.0;
2705        s.push('\0');
2706        unsafe { Self::from_data_trusted::<ObjectPath, _>(s) }
2707    }
2708}
2709
2710impl FromVariant for ObjectPath {
2711    #[allow(unused_unsafe)]
2712    fn from_variant(variant: &Variant) -> Option<Self> {
2713        unsafe {
2714            if variant.is::<Self>() {
2715                Some(ObjectPath(String::from(variant.str().unwrap())))
2716            } else {
2717                None
2718            }
2719        }
2720    }
2721}
2722
2723/// A wrapper type around `Variant` signatures.
2724///
2725/// Values of these type are guaranteed to be valid signatures.
2726#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2727pub struct Signature(String);
2728
2729impl Signature {
2730    pub fn as_str(&self) -> &str {
2731        &self.0
2732    }
2733}
2734
2735impl std::ops::Deref for Signature {
2736    type Target = str;
2737
2738    #[inline]
2739    fn deref(&self) -> &Self::Target {
2740        &self.0
2741    }
2742}
2743
2744impl TryFrom<String> for Signature {
2745    type Error = crate::BoolError;
2746
2747    fn try_from(v: String) -> Result<Self, Self::Error> {
2748        if !Variant::is_signature(&v) {
2749            return Err(bool_error!("Invalid signature"));
2750        }
2751
2752        Ok(Signature(v))
2753    }
2754}
2755
2756impl<'a> TryFrom<&'a str> for Signature {
2757    type Error = crate::BoolError;
2758
2759    fn try_from(v: &'a str) -> Result<Self, Self::Error> {
2760        Signature::try_from(String::from(v))
2761    }
2762}
2763
2764impl From<Signature> for String {
2765    fn from(v: Signature) -> Self {
2766        v.0
2767    }
2768}
2769
2770impl StaticVariantType for Signature {
2771    fn static_variant_type() -> Cow<'static, VariantTy> {
2772        Cow::Borrowed(VariantTy::SIGNATURE)
2773    }
2774}
2775
2776impl ToVariant for Signature {
2777    fn to_variant(&self) -> Variant {
2778        unsafe { from_glib_none(ffi::g_variant_new_signature(self.0.to_glib_none().0)) }
2779    }
2780}
2781
2782impl From<Signature> for Variant {
2783    #[inline]
2784    fn from(s: Signature) -> Self {
2785        let mut s = s.0;
2786        s.push('\0');
2787        unsafe { Self::from_data_trusted::<Signature, _>(s) }
2788    }
2789}
2790
2791impl FromVariant for Signature {
2792    #[allow(unused_unsafe)]
2793    fn from_variant(variant: &Variant) -> Option<Self> {
2794        unsafe {
2795            if variant.is::<Self>() {
2796                Some(Signature(String::from(variant.str().unwrap())))
2797            } else {
2798                None
2799            }
2800        }
2801    }
2802}
2803
2804#[cfg(test)]
2805mod tests {
2806    use std::collections::{HashMap, HashSet};
2807
2808    use super::*;
2809
2810    macro_rules! unsigned {
2811        ($name:ident, $ty:ident) => {
2812            #[test]
2813            fn $name() {
2814                let mut n = $ty::MAX;
2815                while n > 0 {
2816                    let v = n.to_variant();
2817                    assert_eq!(v.get(), Some(n));
2818                    n /= 2;
2819                }
2820            }
2821        };
2822    }
2823
2824    macro_rules! signed {
2825        ($name:ident, $ty:ident) => {
2826            #[test]
2827            fn $name() {
2828                let mut n = $ty::MAX;
2829                while n > 0 {
2830                    let v = n.to_variant();
2831                    assert_eq!(v.get(), Some(n));
2832                    let v = (-n).to_variant();
2833                    assert_eq!(v.get(), Some(-n));
2834                    n /= 2;
2835                }
2836            }
2837        };
2838    }
2839
2840    unsigned!(test_u8, u8);
2841    unsigned!(test_u16, u16);
2842    unsigned!(test_u32, u32);
2843    unsigned!(test_u64, u64);
2844    signed!(test_i16, i16);
2845    signed!(test_i32, i32);
2846    signed!(test_i64, i64);
2847
2848    #[test]
2849    fn test_str() {
2850        let s = "this is a test";
2851        let v = s.to_variant();
2852        assert_eq!(v.str(), Some(s));
2853        assert_eq!(42u32.to_variant().str(), None);
2854    }
2855
2856    #[test]
2857    fn test_fixed_array() {
2858        let b = b"this is a test";
2859        let v = Variant::array_from_fixed_array(&b[..]);
2860        assert_eq!(v.type_().as_str(), "ay");
2861        assert_eq!(v.fixed_array::<u8>().unwrap(), b);
2862        assert!(42u32.to_variant().fixed_array::<u8>().is_err());
2863
2864        let b = [1u32, 10u32, 100u32];
2865        let v = Variant::array_from_fixed_array(&b);
2866        assert_eq!(v.type_().as_str(), "au");
2867        assert_eq!(v.fixed_array::<u32>().unwrap(), b);
2868        assert!(v.fixed_array::<u8>().is_err());
2869
2870        let b = [true, false, true];
2871        let v = Variant::array_from_fixed_array(&b);
2872        assert_eq!(v.type_().as_str(), "ab");
2873        assert_eq!(v.fixed_array::<bool>().unwrap(), b);
2874        assert!(v.fixed_array::<u8>().is_err());
2875
2876        let b = [1.0f64, 2.0f64, 3.0f64];
2877        let v = Variant::array_from_fixed_array(&b);
2878        assert_eq!(v.type_().as_str(), "ad");
2879        #[allow(clippy::float_cmp)]
2880        {
2881            assert_eq!(v.fixed_array::<f64>().unwrap(), b);
2882        }
2883        assert!(v.fixed_array::<u64>().is_err());
2884    }
2885
2886    #[test]
2887    fn test_fixed_variant_array() {
2888        let b = FixedSizeVariantArray::from(&b"this is a test"[..]);
2889        let v = b.to_variant();
2890        assert_eq!(v.type_().as_str(), "ay");
2891        assert_eq!(
2892            &*v.get::<FixedSizeVariantArray<Vec<u8>, u8>>().unwrap(),
2893            &*b
2894        );
2895
2896        let b = FixedSizeVariantArray::from(vec![1i32, 2, 3]);
2897        let v = b.to_variant();
2898        assert_eq!(v.type_().as_str(), "ai");
2899        assert_eq!(v.get::<FixedSizeVariantArray<Vec<i32>, i32>>().unwrap(), b);
2900    }
2901
2902    #[test]
2903    fn test_string() {
2904        let s = String::from("this is a test");
2905        let v = s.to_variant();
2906        assert_eq!(v.get(), Some(s));
2907        assert_eq!(v.normal_form(), v);
2908    }
2909
2910    #[test]
2911    fn test_eq() {
2912        let v1 = "this is a test".to_variant();
2913        let v2 = "this is a test".to_variant();
2914        let v3 = "test".to_variant();
2915        assert_eq!(v1, v2);
2916        assert_ne!(v1, v3);
2917    }
2918
2919    #[test]
2920    fn test_hash() {
2921        let v1 = "this is a test".to_variant();
2922        let v2 = "this is a test".to_variant();
2923        let v3 = "test".to_variant();
2924        let mut set = HashSet::new();
2925        set.insert(v1);
2926        assert!(set.contains(&v2));
2927        assert!(!set.contains(&v3));
2928
2929        assert_eq!(
2930            <HashMap<&str, (&str, u8, u32)>>::static_variant_type().as_str(),
2931            "a{s(syu)}"
2932        );
2933    }
2934
2935    #[test]
2936    fn test_array() {
2937        assert_eq!(<Vec<&str>>::static_variant_type().as_str(), "as");
2938        assert_eq!(
2939            <Vec<(&str, u8, u32)>>::static_variant_type().as_str(),
2940            "a(syu)"
2941        );
2942        let a = ["foo", "bar", "baz"].to_variant();
2943        assert_eq!(a.normal_form(), a);
2944        assert_eq!(a.array_iter_str().unwrap().len(), 3);
2945        let o = 0u32.to_variant();
2946        assert!(o.array_iter_str().is_err());
2947    }
2948
2949    #[test]
2950    fn test_array_from_iter() {
2951        let a = Variant::array_from_iter::<String>(
2952            ["foo", "bar", "baz"].into_iter().map(|s| s.to_variant()),
2953        );
2954        assert_eq!(a.type_().as_str(), "as");
2955        assert_eq!(a.n_children(), 3);
2956
2957        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2958        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
2959        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
2960    }
2961
2962    #[test]
2963    fn test_array_collect() {
2964        let a = ["foo", "bar", "baz"].into_iter().collect::<Variant>();
2965        assert_eq!(a.type_().as_str(), "as");
2966        assert_eq!(a.n_children(), 3);
2967
2968        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2969        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
2970        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
2971    }
2972
2973    #[test]
2974    fn test_tuple() {
2975        assert_eq!(<(&str, u32)>::static_variant_type().as_str(), "(su)");
2976        assert_eq!(<(&str, u8, u32)>::static_variant_type().as_str(), "(syu)");
2977        let a = ("test", 1u8, 2u32).to_variant();
2978        assert_eq!(a.normal_form(), a);
2979        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("test"))));
2980        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
2981        assert_eq!(a.try_child_get::<u32>(2), Ok(Some(2u32)));
2982        assert_eq!(
2983            a.try_get::<(String, u8, u32)>(),
2984            Ok((String::from("test"), 1u8, 2u32))
2985        );
2986    }
2987
2988    #[test]
2989    fn test_tuple_from_iter() {
2990        let a = Variant::tuple_from_iter(["foo".to_variant(), 1u8.to_variant(), 2i32.to_variant()]);
2991        assert_eq!(a.type_().as_str(), "(syi)");
2992        assert_eq!(a.n_children(), 3);
2993
2994        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
2995        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
2996        assert_eq!(a.try_child_get::<i32>(2), Ok(Some(2i32)));
2997    }
2998
2999    #[test]
3000    fn test_empty() {
3001        assert_eq!(<()>::static_variant_type().as_str(), "()");
3002        let a = ().to_variant();
3003        assert_eq!(a.type_().as_str(), "()");
3004        assert_eq!(a.get::<()>(), Some(()));
3005    }
3006
3007    #[test]
3008    fn test_maybe() {
3009        assert!(<Option<()>>::static_variant_type().is_maybe());
3010        let m1 = Some(()).to_variant();
3011        assert_eq!(m1.type_().as_str(), "m()");
3012
3013        assert_eq!(m1.get::<Option<()>>(), Some(Some(())));
3014        assert!(m1.as_maybe().is_some());
3015
3016        let m2 = None::<()>.to_variant();
3017        assert!(m2.as_maybe().is_none());
3018    }
3019
3020    #[test]
3021    fn test_btreemap() {
3022        assert_eq!(
3023            <BTreeMap<String, u32>>::static_variant_type().as_str(),
3024            "a{su}"
3025        );
3026        // Validate that BTreeMap adds entries to dict in sorted order
3027        let mut m = BTreeMap::new();
3028        let total = 20;
3029        for n in 0..total {
3030            let k = format!("v{n:04}");
3031            m.insert(k, n as u32);
3032        }
3033        let v = m.to_variant();
3034        let n = v.n_children();
3035        assert_eq!(total, n);
3036        for n in 0..total {
3037            let child = v
3038                .try_child_get::<DictEntry<String, u32>>(n)
3039                .unwrap()
3040                .unwrap();
3041            assert_eq!(*child.value(), n as u32);
3042        }
3043
3044        assert_eq!(BTreeMap::from_variant(&v).unwrap(), m);
3045    }
3046
3047    #[test]
3048    fn test_get() -> Result<(), Box<dyn std::error::Error>> {
3049        let u = 42u32.to_variant();
3050        assert!(u.get::<i32>().is_none());
3051        assert_eq!(u.get::<u32>().unwrap(), 42);
3052        assert!(u.try_get::<i32>().is_err());
3053        // Test ? conversion
3054        assert_eq!(u.try_get::<u32>()?, 42);
3055        Ok(())
3056    }
3057
3058    #[test]
3059    fn test_byteswap() {
3060        let u = 42u32.to_variant();
3061        assert_eq!(u.byteswap().get::<u32>().unwrap(), 704643072u32);
3062        assert_eq!(u.byteswap().byteswap().get::<u32>().unwrap(), 42u32);
3063    }
3064
3065    #[test]
3066    fn test_try_child() {
3067        let a = ["foo"].to_variant();
3068        assert!(a.try_child_value(0).is_some());
3069        assert_eq!(a.try_child_get::<String>(0).unwrap().unwrap(), "foo");
3070        assert_eq!(a.child_get::<String>(0), "foo");
3071        assert!(a.try_child_get::<u32>(0).is_err());
3072        assert!(a.try_child_value(1).is_none());
3073        assert!(a.try_child_get::<String>(1).unwrap().is_none());
3074        let u = 42u32.to_variant();
3075        assert!(u.try_child_value(0).is_none());
3076        assert!(u.try_child_get::<String>(0).unwrap().is_none());
3077    }
3078
3079    #[test]
3080    fn test_serialize() {
3081        let a = ("test", 1u8, 2u32).to_variant();
3082
3083        let bytes = a.data_as_bytes();
3084        let data = a.data();
3085        let len = a.size();
3086        assert_eq!(bytes.len(), len);
3087        assert_eq!(data.len(), len);
3088
3089        let mut store_data = vec![0u8; len];
3090        assert_eq!(a.store(&mut store_data).unwrap(), len);
3091
3092        assert_eq!(&bytes, data);
3093        assert_eq!(&store_data, data);
3094
3095        let b = Variant::from_data::<(String, u8, u32), _>(store_data);
3096        assert_eq!(a, b);
3097
3098        let c = Variant::from_bytes::<(String, u8, u32)>(&bytes);
3099        assert_eq!(a, c);
3100    }
3101
3102    #[test]
3103    fn test_print_parse() {
3104        let a = ("test", 1u8, 2u32).to_variant();
3105
3106        let a2 = Variant::parse(Some(a.type_()), &a.print(false)).unwrap();
3107        assert_eq!(a, a2);
3108
3109        let a3: Variant = a.to_string().parse().unwrap();
3110        assert_eq!(a, a3);
3111    }
3112
3113    #[cfg(any(unix, windows))]
3114    #[test]
3115    fn test_paths() {
3116        use std::path::PathBuf;
3117
3118        let path = PathBuf::from("foo");
3119        let v = path.to_variant();
3120        assert_eq!(PathBuf::from_variant(&v), Some(path));
3121    }
3122
3123    #[test]
3124    fn test_regression_from_variant_panics() {
3125        let variant = "text".to_variant();
3126        let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
3127        assert!(hashmap.is_none());
3128
3129        let variant = HashMap::<u64, u64>::new().to_variant();
3130        let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
3131        assert!(hashmap.is_some());
3132    }
3133}