Skip to content
This repository has been archived by the owner on Jun 8, 2021. It is now read-only.

Commit

Permalink
API to create tuple Variant & convert it to/from tuples
Browse files Browse the repository at this point in the history
  • Loading branch information
zeenix committed Sep 2, 2020
1 parent 760d726 commit bf5c327
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion src/variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@
//! let map: HashMap<u16, String> = HashMap::from_variant(&variant).unwrap();
//! assert_eq!(map[&1], "hi");
//! assert_eq!(map[&2], "there");
//!
//! // And conversion to and from tuples.
//! let variant = ("hello", 42u16, vec![ "there", "you" ],).to_variant();
//! assert_eq!(variant.n_children(), 3);
//! assert_eq!(variant.type_().to_str(), "(sqas)");
//! let tuple = <(String, u16, Vec<String>)>::from_variant(&variant).unwrap();
//! assert_eq!(tuple.0, "hello");
//! assert_eq!(tuple.1, 42);
//! assert_eq!(tuple.2, &[ "there", "you"]);
//! ```

use bytes::Bytes;
Expand Down Expand Up @@ -219,6 +228,16 @@ impl Variant {
}
}

/// Creates a new GVariant tuple from children.
pub fn new_tuple(children: &[Variant]) -> Self {
unsafe {
from_glib_none(glib_sys::g_variant_new_tuple(
children.to_glib_none().0,
children.len(),
))
}
}

/// Constructs a new serialised-mode GVariant instance.
pub fn new_from_bytes<T: StaticVariantType>(bytes: &Bytes) -> Self {
unsafe {
Expand Down Expand Up @@ -605,7 +624,6 @@ where
};

Some(DictEntry { key, value })

}
}

Expand Down Expand Up @@ -662,6 +680,36 @@ macro_rules! tuple_impls {
VariantType::new(&signature).expect("incorrect signature").into()
}
}

impl<$($name),+> FromVariant for ($($name,)+)
where
$($name: FromVariant,)+
{
fn from_variant(variant: &Variant) -> Option<Self> {
Some((
$(
match $name::from_variant(&variant.get_child_value($n)) {
Some(field) => field,
None => return None,
},
)+
))
}
}

impl<$($name),+> ToVariant for ($($name,)+)
where
$($name: ToVariant,)+
{
fn to_variant(&self) -> Variant {
let mut fields = Vec::with_capacity($len);
$(
let field = self.$n.to_variant();
fields.push(field);
)+
Variant::new_tuple(&fields)
}
}
)+
}
}
Expand Down

0 comments on commit bf5c327

Please sign in to comment.