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!(
26    usize,
27    u64,
28    u32,
29    u16,
30    u8,
31    isize,
32    i64,
33    i32,
34    i16,
35    i8,
36    ::std::net::IpAddr
37);
38
39impl IntoAttributeValue for String {
40    fn into_attribute_value(self) -> Option<String> {
41        Some(self)
42    }
43}
44
45impl<'a> IntoAttributeValue for &'a String {
46    fn into_attribute_value(self) -> Option<String> {
47        Some(self.to_owned())
48    }
49}
50
51impl<'a> IntoAttributeValue for &'a str {
52    fn into_attribute_value(self) -> Option<String> {
53        Some(self.to_owned())
54    }
55}
56
57impl<T: IntoAttributeValue> IntoAttributeValue for Option<T> {
58    fn into_attribute_value(self) -> Option<String> {
59        self.and_then(IntoAttributeValue::into_attribute_value)
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::IntoAttributeValue;
66    use std::net::IpAddr;
67    use std::str::FromStr;
68
69    #[test]
70    fn test_into_attribute_value_on_ints() {
71        assert_eq!(16u8.into_attribute_value().unwrap(), "16");
72        assert_eq!(17u16.into_attribute_value().unwrap(), "17");
73        assert_eq!(18u32.into_attribute_value().unwrap(), "18");
74        assert_eq!(19u64.into_attribute_value().unwrap(), "19");
75        assert_eq!(16i8.into_attribute_value().unwrap(), "16");
76        assert_eq!((-17i16).into_attribute_value().unwrap(), "-17");
77        assert_eq!(18i32.into_attribute_value().unwrap(), "18");
78        assert_eq!((-19i64).into_attribute_value().unwrap(), "-19");
79        assert_eq!(
80            IpAddr::from_str("127.000.0.1")
81                .unwrap()
82                .into_attribute_value()
83                .unwrap(),
84            "127.0.0.1"
85        );
86    }
87}