convert.rs

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