1#![warn(missing_docs)]
25
26fn is_newline(c: char) -> bool {
28 c == '\r' || c == '\n'
29}
30
31pub trait Chomp<'a> {
33 fn chomp(Self) -> &'a str;
35}
36
37impl<'a> Chomp<'a> for &'a str {
38 fn chomp(string: Self) -> &'a str {
39 string.trim_right_matches(is_newline)
40 }
41}
42
43impl<'a> Chomp<'a> for &'a String {
44 fn chomp(string: Self) -> &'a str {
45 string.trim_right_matches(is_newline)
46 }
47}
48
49pub trait ChompInPlace {
51 fn chomp(&mut self);
53}
54
55impl ChompInPlace for String {
56 fn chomp(&mut self) {
57 let len = self.len();
58 let newline_count = self.chars().rev()
59 .take_while(|&c| is_newline(c))
60 .count();
61 self.truncate(len - newline_count);
62 }
63}
64
65pub fn chomp<'a, C: Chomp<'a>>(string: C) -> &'a str {
67 Chomp::chomp(string)
68}
69
70#[cfg(test)]
71mod tests {
72 use super::{ChompInPlace, chomp};
73
74 #[test]
75 fn test_chomp() {
76 assert_eq!("", chomp(""));
77 assert_eq!("test", chomp("test"));
78 assert_eq!("test", chomp("test\n"));
79 assert_eq!(" test ", chomp(" test \n"));
80 assert_eq!(" test ", chomp(" test \r"));
81 assert_eq!(" test ", chomp(" test \r\n"));
82 assert_eq!("\r\n test ", chomp("\r\n test \r\n"));
83 assert_eq!("\r\n test \r\n ", chomp("\r\n test \r\n \r\n"));
84
85 assert_eq!("", chomp(&"".to_string()));
86 assert_eq!("test", chomp(&"test".to_string()));
87 assert_eq!("test", chomp(&"test\n".to_string()));
88 assert_eq!(" test ", chomp(&" test \n".to_string()));
89 assert_eq!(" test ", chomp(&" test \r".to_string()));
90 assert_eq!(" test ", chomp(&" test \r\n".to_string()));
91 assert_eq!("\r\n test ", chomp(&"\r\n test \r\n".to_string()));
92 assert_eq!("\r\n test \r\n ", chomp(&"\r\n test \r\n \r\n".to_string()));
93 }
94
95 #[test]
96 fn test_chomp_inplace() {
97 let mut string = "".to_string();
98 string.chomp();
99 assert_eq!("", string);
100
101 let mut string = "test".to_string();
102 string.chomp();
103 assert_eq!("test", string);
104
105 let mut string = "test\n".to_string();
106 string.chomp();
107 assert_eq!("test", string);
108
109 let mut string = " test \n".to_string();
110 string.chomp();
111 assert_eq!(" test ", string);
112
113 let mut string = " test \r".to_string();
114 string.chomp();
115 assert_eq!(" test ", string);
116
117 let mut string = " test \r\n".to_string();
118 string.chomp();
119 assert_eq!(" test ", string);
120
121 let mut string = "\r\n test \r\n".to_string();
122 string.chomp();
123 assert_eq!("\r\n test ", string);
124
125 let mut string = "\r\n test \r\n \r\n".to_string();
126 string.chomp();
127 assert_eq!("\r\n test \r\n ", string);
128 }
129}