1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub use ctb_formats_utilities::encoding::{
30 CharEncoding, LineEndingFormat, LineEndingKind, LineEndingOption,
31 TerminationMode,
32};
33
34pub const LF: &str = "\n";
36pub const CR: &str = "\r";
37pub const CRLF: &str = "\r\n";
38pub const LFCR: &str = "\n\r";
39pub const RS: &str = "\x1E";
40pub const NEL: &str = "\u{0085}";
41
42#[must_use]
46pub fn detect_line_ending(s: &str) -> Option<LineEndingKind> {
47 let mut crlf_count = 0usize;
48 let mut lfcr_count = 0usize;
49 let mut cr_count = 0usize;
50 let mut lf_count = 0usize;
51 let mut rs_count = 0usize;
52 let mut nl_count = 0usize;
53
54 let bytes = s.as_bytes();
55 let mut i = 0usize;
56 while i < bytes.len() {
57 if let Some(rem) = s.get(i..) {
58 if rem.starts_with(CRLF) {
59 crlf_count = crlf_count.saturating_add(1);
60 i = i.saturating_add(2);
61 continue;
62 }
63 if rem.starts_with(LFCR) {
64 lfcr_count = lfcr_count.saturating_add(1);
65 i = i.saturating_add(2);
66 continue;
67 }
68 if rem.starts_with(NEL) {
69 nl_count = nl_count.saturating_add(1);
70 i = i.saturating_add(NEL.len());
71 continue;
72 }
73 }
74
75 if let Some(&b) = bytes.get(i) {
76 match b {
77 b'\r' => cr_count = cr_count.saturating_add(1),
78 b'\n' => lf_count = lf_count.saturating_add(1),
79 0x1E => rs_count = rs_count.saturating_add(1),
80 _ => {}
81 }
82 }
83 i = i.saturating_add(1);
84 }
85
86 let candidates = [
87 (crlf_count, LineEndingKind::CrLf),
88 (lf_count, LineEndingKind::Lf),
89 (cr_count, LineEndingKind::Cr),
90 (lfcr_count, LineEndingKind::LfCr),
91 (rs_count, LineEndingKind::Rs),
92 (nl_count, LineEndingKind::Nl),
93 ];
94
95 candidates
96 .into_iter()
97 .filter(|(count, _)| *count > 0)
98 .max_by_key(|(count, _)| *count)
99 .map(|(_, kind)| kind)
100}
101
102#[must_use]
105pub fn split_lines_universal(input: &str) -> Vec<&str> {
106 if input.is_empty() {
107 return Vec::new();
108 }
109
110 let mut lines = Vec::new();
111 let mut start = 0usize;
112 let mut i = 0usize;
113 let bytes = input.as_bytes();
114
115 while i < bytes.len() {
116 let delim_len = if let Some(rem) = input.get(i..) {
117 if rem.starts_with(CRLF) || rem.starts_with(LFCR) {
118 2
119 } else if rem.starts_with(NEL) {
120 NEL.len()
121 } else {
122 usize::from(
123 rem.starts_with(LF)
124 || rem.starts_with(CR)
125 || rem.starts_with(RS),
126 )
127 }
128 } else {
129 0
130 };
131
132 if delim_len > 0 {
133 if let Some(line) = input.get(start..i) {
134 lines.push(line);
135 }
136 i = i.saturating_add(delim_len);
137 start = i;
138 } else {
139 i = i.saturating_add(1);
140 }
141 }
142
143 if start < input.len() {
144 if let Some(line) = input.get(start..) {
145 lines.push(line);
146 }
147 }
148
149 lines
150}
151
152#[must_use]
154pub fn convert_line_endings(input: &str, format: LineEndingFormat) -> String {
155 if input.is_empty() {
156 return String::new();
157 }
158
159 let lines = split_lines_universal(input);
160 let delim = format.kind.as_str();
161
162 match format.mode {
163 TerminationMode::Terminated => {
164 let mut result = String::with_capacity(
165 input
166 .len()
167 .saturating_add(lines.len().saturating_mul(delim.len())),
168 );
169 for line in lines {
170 result.push_str(line);
171 result.push_str(delim);
172 }
173 result
174 }
175 TerminationMode::Separated => lines.join(delim),
176 }
177}
178
179#[must_use]
181pub fn normalize_to_lf(input: &str) -> String {
182 convert_line_endings(
183 input,
184 LineEndingFormat::terminated(LineEndingKind::Lf),
185 )
186}
187
188pub fn apply_line_ending_option(
190 input: &str,
191 target_enc: CharEncoding,
192 option: LineEndingOption,
193) -> Result<String> {
194 match option {
195 LineEndingOption::Preserve => Ok(input.to_string()),
196 LineEndingOption::EncodingDefault => {
197 let kind = target_enc.default_line_ending();
198 Ok(convert_line_endings(
199 input,
200 LineEndingFormat::terminated(kind),
201 ))
202 }
203 LineEndingOption::Specific(format) => {
204 if !target_enc.supports_line_ending(format.kind) {
205 bail!(
206 "Line ending {:?} is not supported by target encoding {:?}",
207 format.kind,
208 target_enc
209 );
210 }
211 Ok(convert_line_endings(input, format))
212 }
213 }
214}
215
216#[cfg(test)]
217#[allow(
218 clippy::panic,
219 clippy::expect_used,
220 clippy::unwrap_used,
221 clippy::unwrap_in_result,
222 clippy::panic_in_result_fn,
223 clippy::indexing_slicing,
224 clippy::arithmetic_side_effects,
225 reason = "Standard repository test boilerplate"
226)]
227mod tests {
228 use super::*;
229
230 #[crate::ctb_test]
231 fn test_split_lines_universal() {
232 let mixed = "Line 1\r\nLine 2\nLine 3\rLine 4\n\rLine 5\x1ELine 6\u{0085}Line 7";
233 let lines = split_lines_universal(mixed);
234 assert_eq!(
235 lines,
236 vec![
237 "Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6",
238 "Line 7"
239 ]
240 );
241 }
242
243 #[crate::ctb_test]
244 fn test_detect_line_ending() {
245 assert_eq!(
246 detect_line_ending("Hello\r\nWorld\r\nAgain\r\n"),
247 Some(LineEndingKind::CrLf)
248 );
249 assert_eq!(
250 detect_line_ending("Hello\nWorld\nAgain\n"),
251 Some(LineEndingKind::Lf)
252 );
253 assert_eq!(
254 detect_line_ending("Hello\rWorld\rAgain\r"),
255 Some(LineEndingKind::Cr)
256 );
257 assert_eq!(
258 detect_line_ending("Hello\n\rWorld\n\r"),
259 Some(LineEndingKind::LfCr)
260 );
261 assert_eq!(
262 detect_line_ending("Hello\x1EWorld\x1E"),
263 Some(LineEndingKind::Rs)
264 );
265 assert_eq!(
266 detect_line_ending("Hello\u{0085}World\u{0085}"),
267 Some(LineEndingKind::Nl)
268 );
269 assert_eq!(detect_line_ending("Single line no newline"), None);
270 }
271
272 #[crate::ctb_test]
273 fn test_convert_line_endings_terminated_and_separated() {
274 let input = "alpha\nbeta\ngamma";
275
276 let crlf_term = convert_line_endings(
278 input,
279 LineEndingFormat::terminated(LineEndingKind::CrLf),
280 );
281 assert_eq!(crlf_term, "alpha\r\nbeta\r\ngamma\r\n");
282
283 let crlf_sep = convert_line_endings(
285 input,
286 LineEndingFormat::separated(LineEndingKind::CrLf),
287 );
288 assert_eq!(crlf_sep, "alpha\r\nbeta\r\ngamma");
289
290 let cr_term = convert_line_endings(
292 input,
293 LineEndingFormat::terminated(LineEndingKind::Cr),
294 );
295 assert_eq!(cr_term, "alpha\rbeta\rgamma\r");
296
297 let lfcr_term = convert_line_endings(
299 input,
300 LineEndingFormat::terminated(LineEndingKind::LfCr),
301 );
302 assert_eq!(lfcr_term, "alpha\n\rbeta\n\rgamma\n\r");
303
304 let rs_term = convert_line_endings(
306 input,
307 LineEndingFormat::terminated(LineEndingKind::Rs),
308 );
309 assert_eq!(rs_term, "alpha\x1Ebeta\x1Egamma\x1E");
310
311 let nel_term = convert_line_endings(
313 input,
314 LineEndingFormat::terminated(LineEndingKind::Nl),
315 );
316 assert_eq!(nel_term, "alpha\u{0085}beta\u{0085}gamma\u{0085}");
317 }
318
319 #[crate::ctb_test]
320 fn test_apply_line_ending_option() -> Result<()> {
321 let text = "Line A\nLine B\n";
322
323 let res_mac = apply_line_ending_option(
325 text,
326 CharEncoding::mac_roman(),
327 LineEndingOption::EncodingDefault,
328 )?;
329 assert_eq!(res_mac, "Line A\rLine B\r");
330
331 let res_cp437 = apply_line_ending_option(
333 text,
334 CharEncoding::cp437(),
335 LineEndingOption::EncodingDefault,
336 )?;
337 assert_eq!(res_cp437, "Line A\r\nLine B\r\n");
338
339 let res_pres = apply_line_ending_option(
341 text,
342 CharEncoding::mac_roman(),
343 LineEndingOption::Preserve,
344 )?;
345 assert_eq!(res_pres, text);
346
347 let err = apply_line_ending_option(
349 text,
350 CharEncoding::mac_roman(),
351 LineEndingOption::Specific(LineEndingFormat::terminated(
352 LineEndingKind::Nl,
353 )),
354 );
355 err.unwrap_err();
356
357 Ok(())
358 }
359}