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
130
131
132
133
134
135
136
137
138
use std::fmt;
use color_eyre::Result;
pub trait Transform {
fn transform(&self, content: String) -> Result<String>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ContentTransformer {
LineTerminator(LineTerminator),
}
impl Transform for ContentTransformer {
fn transform(&self, content: String) -> Result<String> {
match self {
Self::LineTerminator(lt) => lt.transform(content),
}
}
}
impl fmt::Display for ContentTransformer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt::Display::fmt(&self, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LineTerminator {
LF,
CRLF,
}
impl Transform for LineTerminator {
fn transform(&self, mut content: String) -> Result<String> {
match self {
Self::LF => Ok(content.replace("\r\n", "\n")),
Self::CRLF => {
let lf_idxs = content.match_indices('\n');
let mut cr_idxs = content.match_indices('\r').peekable();
#[allow(clippy::needless_collect)]
let lf_idxs = lf_idxs
.filter_map(|(lf_idx, _)| {
while matches!(cr_idxs.peek(), Some((cr_idx,_)) if cr_idx + 1 < lf_idx) {
let _ = cr_idxs.next().expect("Failed to advance peeked iterator");
}
if matches!(cr_idxs.peek(), Some((cr_idx, _)) if cr_idx + 1 == lf_idx) {
let _ = cr_idxs.next().expect("Failed to advance peeked iterator");
None
} else {
Some(lf_idx)
}
})
.collect::<Vec<_>>();
for (offset, lf_idx) in lf_idxs.into_iter().enumerate() {
content.insert(lf_idx + offset, '\r');
}
Ok(content)
}
}
}
}
impl fmt::Display for LineTerminator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&self, f)
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn line_terminator_lf() -> Result<()> {
const CONTENT: &str = "Hello\r\nWorld\nHow\nare\r\nyou today?\r\r\r\nLast line\r\\n";
assert_eq!(
LineTerminator::LF.transform(String::from(CONTENT))?,
"Hello\nWorld\nHow\nare\nyou today?\r\r\nLast line\r\\n"
);
Ok(())
}
#[test]
fn line_terminator_crlf() -> Result<()> {
const CONTENT: &str = "Hello\r\nWorld\nHow\nare\r\nyou today?\r\r\r\nLast line\r\\n";
assert_eq!(
LineTerminator::CRLF.transform(String::from(CONTENT))?,
"Hello\r\nWorld\r\nHow\r\nare\r\nyou today?\r\r\r\nLast line\r\\n"
);
Ok(())
}
}