use std::string::String;
use std::str::replace;
use common::{CR, LF, CRLF};
#[inline]
pub fn remove_trailing_crlf(string: &str) -> &str {
if string.ends_with(CRLF) {
string.slice_to(string.len() - 2)
} else if string.ends_with(CR) {
string.slice_to(string.len() - 1)
} else {
string
}
}
#[inline]
pub fn get_first_word(string: &str) -> &str {
string.split_str(CRLF).next().unwrap().splitn(1, ' ').next().unwrap()
}
#[inline]
pub fn escape_crlf(string: &str) -> String {
replace(string, CRLF, "<CR><LF>")
}
#[inline]
pub fn escape_dot(string: &str) -> String {
if string.starts_with(".") {
format!(".{}", string)
} else {
string.to_string()
}.replace(format!("{}.", CR).as_slice(), format!("{}..", CR).as_slice())
.replace(format!("{}.", LF).as_slice(), format!("{}..", LF).as_slice())
}
#[cfg(test)]
mod test {
use super::{remove_trailing_crlf, get_first_word, escape_crlf, escape_dot};
#[test]
fn test_remove_trailing_crlf() {
assert_eq!(remove_trailing_crlf("word"), "word");
assert_eq!(remove_trailing_crlf("word\r\n"), "word");
assert_eq!(remove_trailing_crlf("word\r\n "), "word\r\n ");
assert_eq!(remove_trailing_crlf("word\r"), "word");
assert_eq!(remove_trailing_crlf("\r\n"), "");
assert_eq!(remove_trailing_crlf("\r"), "");
assert_eq!(remove_trailing_crlf("a"), "a");
assert_eq!(remove_trailing_crlf(""), "");
}
#[test]
fn test_get_first_word() {
assert_eq!(get_first_word("first word"), "first");
assert_eq!(get_first_word("first word\r\ntest"), "first");
assert_eq!(get_first_word("first"), "first");
assert_eq!(get_first_word(""), "");
assert_eq!(get_first_word("\r\n"), "");
assert_eq!(get_first_word("a\r\n"), "a");
assert_eq!(get_first_word(" \r\n"), "");
assert_eq!(get_first_word("\r\n "), "");
}
#[test]
fn test_escape_crlf() {
assert_eq!(escape_crlf("\r\n").as_slice(), "<CR><LF>");
assert_eq!(escape_crlf("EHLO my_name\r\n").as_slice(), "EHLO my_name<CR><LF>");
assert_eq!(
escape_crlf("EHLO my_name\r\nSIZE 42\r\n").as_slice(),
"EHLO my_name<CR><LF>SIZE 42<CR><LF>"
);
}
#[test]
fn test_escape_dot() {
assert_eq!(escape_dot(".test").as_slice(), "..test");
assert_eq!(escape_dot("\r.\n.\r\n").as_slice(), "\r..\n..\r\n");
assert_eq!(escape_dot("test\r\n.test\r\n").as_slice(), "test\r\n..test\r\n");
assert_eq!(escape_dot("test\r\n.\r\ntest").as_slice(), "test\r\n..\r\ntest");
}
}