utils 0.0.3

Common utilities suitable for use in Rust Builders
/// `Empty` trait definition.
///
/// The `Empty` trait wraps `is_empty` calls for various types.  Use with
/// `to_opt` to convert different types to `Option`.
///
/// ```rust
/// use utils::empty::to_opt;
///
/// let opt = to_opt("val");                 // Some("val")
/// let opt1 = to_opt("".to_string());       // None
/// let opt2 = to_opt(Vec::<&str>::new());   // None
/// let opt3 = to_opt(Vec::<String>::new()); // None
/// ```
#[experimental]
pub trait Empty {
    /// Return true if self is empty, false otherwise.
    fn empty(&self) -> bool;
}

/// `Empty` implementation for string slice.
#[experimental]
impl <'a>Empty for &'a str {
    fn empty(&self) -> bool {
        self.is_empty()
    }
}

/// `Empty` implementation for String.
#[experimental]
impl Empty for String {
    fn empty(&self) -> bool {
        self.as_slice().is_empty()
    }
}

/// `Empty` implementation for Vec<String>.
#[experimental]
impl Empty for Vec<String> {
    fn empty(&self) -> bool {
        self.is_empty()
    }
}

/// `Empty` implementation for Vec<&str>.
#[experimental]
impl <'a>Empty for Vec<&'a str> {
    fn empty(&self) -> bool {
        self.is_empty()
    }
}

/// Convert an `Empty` element of type `T` to an `Option` of type `T`.
///
///
/// ```rust
/// use utils::empty::to_opt;
///
/// let opt = to_opt("val"); // Some("val")
/// ```
///
/// # Arguments
/// * `arg` - The element to convert from an `Empty` to an `Option`.
#[experimental]
pub fn to_opt<T: Empty>(arg: T) -> Option<T> {
    if arg.empty() {
        None
    } else {
        Some(arg)
    }
}

#[cfg(test)]
mod test {
    use super::to_opt;

    #[test]
    fn test_to_opt() {
        assert_eq!(to_opt(""), None);
        assert_eq!(to_opt("val"), Some("val"));
        assert_eq!(to_opt("".to_string()), None);
        assert_eq!(to_opt("val".to_string()), Some("val".to_string()));
        assert_eq!(to_opt(Vec::<&str>::new()), None);
        assert_eq!(to_opt(vec!["a"]), Some(vec!["a"]));
        assert_eq!(to_opt(Vec::<String>::new()), None);
        assert_eq!(to_opt(vec!["a".to_string()]),
                   Some(vec!["a".to_string()]));
    }
}