convert.rs

 1//! A module which exports a few traits for converting types to elements and attributes.
 2
 3use element::{Element, ElementBuilder};
 4
 5/// A trait for types which can be converted to an attribute value.
 6pub trait IntoAttributeValue {
 7    /// Turns this into an attribute string, or None if it shouldn't be added.
 8    fn into_attribute_value(self) -> Option<String>;
 9}
10
11macro_rules! impl_into_attribute_value {
12    ($t:ty) => {
13        impl IntoAttributeValue for $t {
14            fn into_attribute_value(self) -> Option<String> {
15                Some(format!("{}", self))
16            }
17        }
18    }
19}
20
21macro_rules! impl_into_attribute_values {
22    ($($t:ty),*) => {
23        $(impl_into_attribute_value!($t);)*
24    }
25}
26
27impl_into_attribute_values!(usize, u64, u32, u16, u8, isize, i64, i32, i16, i8, ::std::net::IpAddr);
28
29impl IntoAttributeValue for String {
30    fn into_attribute_value(self) -> Option<String> {
31        Some(self)
32    }
33}
34
35impl<'a> IntoAttributeValue for &'a String {
36    fn into_attribute_value(self) -> Option<String> {
37        Some(self.to_owned())
38    }
39}
40
41impl<'a> IntoAttributeValue for &'a str {
42    fn into_attribute_value(self) -> Option<String> {
43        Some(self.to_owned())
44    }
45}
46
47impl<T: IntoAttributeValue> IntoAttributeValue for Option<T> {
48    fn into_attribute_value(self) -> Option<String> {
49        self.and_then(|t| t.into_attribute_value())
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::IntoAttributeValue;
56    use std::net::IpAddr;
57    use std::str::FromStr;
58
59    #[test]
60    fn test_into_attribute_value_on_ints() {
61        assert_eq!(16u8.into_attribute_value().unwrap()    , "16");
62        assert_eq!(17u16.into_attribute_value().unwrap()   , "17");
63        assert_eq!(18u32.into_attribute_value().unwrap()   , "18");
64        assert_eq!(19u64.into_attribute_value().unwrap()   , "19");
65        assert_eq!(   16i8.into_attribute_value().unwrap() , "16");
66        assert_eq!((-17i16).into_attribute_value().unwrap(), "-17");
67        assert_eq!(   18i32.into_attribute_value().unwrap(), "18");
68        assert_eq!((-19i64).into_attribute_value().unwrap(), "-19");
69        assert_eq!(IpAddr::from_str("127.000.0.1").unwrap().into_attribute_value().unwrap(), "127.0.0.1");
70    }
71}