1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#![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);
}
}