2017-03-08 19:34:17 +00:00
|
|
|
//! A module which exports a few traits for converting types to elements and attributes.
|
|
|
|
|
|
|
|
/// A trait for types which can be converted to an attribute value.
|
|
|
|
pub trait IntoAttributeValue {
|
|
|
|
/// Turns this into an attribute string, or None if it shouldn't be added.
|
|
|
|
fn into_attribute_value(self) -> Option<String>;
|
|
|
|
}
|
|
|
|
|
2017-05-27 22:25:57 +00:00
|
|
|
macro_rules! impl_into_attribute_value {
|
|
|
|
($t:ty) => {
|
|
|
|
impl IntoAttributeValue for $t {
|
|
|
|
fn into_attribute_value(self) -> Option<String> {
|
|
|
|
Some(format!("{}", self))
|
|
|
|
}
|
|
|
|
}
|
2017-05-27 21:56:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-27 22:25:57 +00:00
|
|
|
macro_rules! impl_into_attribute_values {
|
|
|
|
($($t:ty),*) => {
|
|
|
|
$(impl_into_attribute_value!($t);)*
|
2017-05-27 21:56:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-29 14:01:11 +00:00
|
|
|
impl_into_attribute_values!(usize, u64, u32, u16, u8, isize, i64, i32, i16, i8, ::std::net::IpAddr);
|
2017-05-27 21:56:17 +00:00
|
|
|
|
2017-03-08 19:34:17 +00:00
|
|
|
impl IntoAttributeValue for String {
|
|
|
|
fn into_attribute_value(self) -> Option<String> {
|
2017-05-22 14:15:04 +00:00
|
|
|
Some(self)
|
2017-03-08 19:34:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-21 20:07:37 +00:00
|
|
|
impl<'a> IntoAttributeValue for &'a String {
|
|
|
|
fn into_attribute_value(self) -> Option<String> {
|
|
|
|
Some(self.to_owned())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-08 19:34:17 +00:00
|
|
|
impl<'a> IntoAttributeValue for &'a str {
|
|
|
|
fn into_attribute_value(self) -> Option<String> {
|
2017-05-22 14:15:26 +00:00
|
|
|
Some(self.to_owned())
|
2017-03-08 19:34:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: IntoAttributeValue> IntoAttributeValue for Option<T> {
|
|
|
|
fn into_attribute_value(self) -> Option<String> {
|
|
|
|
self.and_then(|t| t.into_attribute_value())
|
|
|
|
}
|
|
|
|
}
|
2017-05-27 22:25:57 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::IntoAttributeValue;
|
2018-05-29 14:01:11 +00:00
|
|
|
use std::net::IpAddr;
|
|
|
|
use std::str::FromStr;
|
2017-05-27 22:25:57 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_into_attribute_value_on_ints() {
|
|
|
|
assert_eq!(16u8.into_attribute_value().unwrap() , "16");
|
|
|
|
assert_eq!(17u16.into_attribute_value().unwrap() , "17");
|
|
|
|
assert_eq!(18u32.into_attribute_value().unwrap() , "18");
|
|
|
|
assert_eq!(19u64.into_attribute_value().unwrap() , "19");
|
|
|
|
assert_eq!( 16i8.into_attribute_value().unwrap() , "16");
|
|
|
|
assert_eq!((-17i16).into_attribute_value().unwrap(), "-17");
|
|
|
|
assert_eq!( 18i32.into_attribute_value().unwrap(), "18");
|
|
|
|
assert_eq!((-19i64).into_attribute_value().unwrap(), "-19");
|
2018-05-29 14:01:11 +00:00
|
|
|
assert_eq!(IpAddr::from_str("127.000.0.1").unwrap().into_attribute_value().unwrap(), "127.0.0.1");
|
2017-05-27 22:25:57 +00:00
|
|
|
}
|
|
|
|
}
|