#![warn(missing_docs)]
fn is_newline(c: char) -> bool {
c == '\r' || c == '\n'
}
pub trait Chomp<'a> {
fn chomp(Self) -> &'a str;
}
impl<'a> Chomp<'a> for &'a str {
fn chomp(string: Self) -> &'a str {
string.trim_right_matches(is_newline)
}
}
impl<'a> Chomp<'a> for &'a String {
fn chomp(string: Self) -> &'a str {
string.trim_right_matches(is_newline)
}
}
pub trait ChompInPlace {
fn chomp(&mut self);
}
impl ChompInPlace for String {
fn chomp(&mut self) {
let len = self.len();
let newline_count = self.chars().rev()
.take_while(|&c| is_newline(c))
.count();
self.truncate(len - newline_count);
}
}
pub fn chomp<'a, C: Chomp<'a>>(string: C) -> &'a str {
Chomp::chomp(string)
}
#[cfg(test)]
mod tests {
use super::{ChompInPlace, chomp};
#[test]
fn test_chomp() {
assert_eq!("", chomp(""));
assert_eq!("test", chomp("test"));
assert_eq!("test", chomp("test\n"));
assert_eq!(" test ", chomp(" test \n"));
assert_eq!(" test ", chomp(" test \r"));
assert_eq!(" test ", chomp(" test \r\n"));
assert_eq!("\r\n test ", chomp("\r\n test \r\n"));
assert_eq!("\r\n test \r\n ", chomp("\r\n test \r\n \r\n"));
assert_eq!("", chomp(&"".to_string()));
assert_eq!("test", chomp(&"test".to_string()));
assert_eq!("test", chomp(&"test\n".to_string()));
assert_eq!(" test ", chomp(&" test \n".to_string()));
assert_eq!(" test ", chomp(&" test \r".to_string()));
assert_eq!(" test ", chomp(&" test \r\n".to_string()));
assert_eq!("\r\n test ", chomp(&"\r\n test \r\n".to_string()));
assert_eq!("\r\n test \r\n ", chomp(&"\r\n test \r\n \r\n".to_string()));
}
#[test]
fn test_chomp_inplace() {
let mut string = "".to_string();
string.chomp();
assert_eq!("", string);
let mut string = "test".to_string();
string.chomp();
assert_eq!("test", string);
let mut string = "test\n".to_string();
string.chomp();
assert_eq!("test", string);
let mut string = " test \n".to_string();
string.chomp();
assert_eq!(" test ", string);
let mut string = " test \r".to_string();
string.chomp();
assert_eq!(" test ", string);
let mut string = " test \r\n".to_string();
string.chomp();
assert_eq!(" test ", string);
let mut string = "\r\n test \r\n".to_string();
string.chomp();
assert_eq!("\r\n test ", string);
let mut string = "\r\n test \r\n \r\n".to_string();
string.chomp();
assert_eq!("\r\n test \r\n ", string);
}
}