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
#![warn(missing_docs)]
pub struct Normalized<I>
where I: Iterator<Item=char> {
iter: I,
prev_was_cr: bool
}
pub fn normalized<I>(iter: I) -> Normalized<I>
where I: Iterator<Item=char> {
Normalized { iter: iter, prev_was_cr: false }
}
impl<I: Iterator<Item=char>> Iterator for Normalized<I> {
type Item = char;
fn next(&mut self) -> Option<char> {
match self.iter.next() {
Some('\n') if self.prev_was_cr => {
self.prev_was_cr = false;
match self.iter.next() {
Some('\r') => {
self.prev_was_cr = true;
Some('\n')
},
any => {
self.prev_was_cr = false;
any
}
}
},
Some('\r') => {
self.prev_was_cr = true;
Some('\n')
},
any => {
self.prev_was_cr = false;
any
}
}
}
}
#[cfg(test)]
mod tests {
use std::io::prelude::*;
use std::iter::FromIterator;
#[test]
fn normalized() {
let input = "This is a string \n with \r some \n\r\n random newlines\r\r\n\n";
assert_eq!(
&String::from_iter(super::normalized(input.chars())),
"This is a string \n with \n some \n\n random newlines\n\n\n"
);
}
}