autolink 0.2.0

HTML auto-linking
Documentation
extern crate regex;
use regex::Regex;

/// Wrap URLs in text with HTML A tags.
///
/// # Examples
///
/// ```
///   use autolink::auto_link;
///
///   let before = "Share code on https://crates.io";
///   let after = "Share code on <a href=\"https://crates.io\" target=\"_blank\">https://crates.io</a>";
///   assert!(auto_link(before, &vec!["target=\"_blank\""]) == after)
/// ```
pub fn auto_link(text: &str, attrs: &[&str]) -> String {
    if text.len() == 0 {
        return String::new()
    }

    let re = Regex::new(r"(?ix)
        (?: ((?:ed2k|ftp|http|https|irc|mailto|news|gopher|nntp|telnet|webcal|xmpp|callto|feed|svn|urn|aim|rsync|tag|ssh|sftp|rtsp|afs|file):)// | www\. )
        [^\s<\x{00A0}\x{0022}]+
    ").unwrap();

    let attr_str = match attrs.len() {
        0 => "".to_string(),
        _ => " ".to_string() + &(attrs.join(" ")),
    };
    let replace_str = format!("<a href=\"$0\"{}>$0</a>", attr_str);

    re.replace_all(text, &replace_str as &str)
}

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

    #[test]
    fn test_empty_string() {
        assert!(auto_link("", &[]) == "")
    }

    #[test]
    fn test_string_without_urls() {
        let src = "<p>Some HTML</p>";
        assert!(auto_link(src, &[]) == src)
    }

    #[test]
    fn test_string_with_http_urls() {
        let src = "Check this out: https://doc.rust-lang.org/\n
               https://fr.wikipedia.org/wiki/Caf%C3%A9ine";
        let linked = "Check this out: <a href=\"https://doc.rust-lang.org/\">https://doc.rust-lang.org/</a>\n
               <a href=\"https://fr.wikipedia.org/wiki/Caf%C3%A9ine\">https://fr.wikipedia.org/wiki/Caf%C3%A9ine</a>";
        assert!(auto_link(src, &[]) == linked)
    }

    #[test]
    fn test_string_with_blank_target() {
        let src = "Check this out: https://doc.rust-lang.org/\n
               https://fr.wikipedia.org/wiki/Caf%C3%A9ine";
        let linked = "Check this out: <a href=\"https://doc.rust-lang.org/\" target=\"_blank\">https://doc.rust-lang.org/</a>\n
               <a href=\"https://fr.wikipedia.org/wiki/Caf%C3%A9ine\" target=\"_blank\">https://fr.wikipedia.org/wiki/Caf%C3%A9ine</a>";
        assert!(auto_link(src, &vec!["target=\"_blank\""]) == linked)
    }

    #[test]
    fn test_string_with_mailto_urls() {
        let src = "Send spam to mailto://oz@cypr.io";
        assert!(auto_link(src, &[]) == "Send spam to <a href=\"mailto://oz@cypr.io\">mailto://oz@cypr.io</a>")
    }
}