ctb_formats_encoding/
line_endings.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Line ending detection, universal line splitting, and format conversion.
21
22#[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
34/// Universal newline delimiter character constants and slices.
35pub 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/// Detects the predominant line ending delimiter in a string.
43///
44/// Returns `None` if the input contains no recognized line ending characters.
45#[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/// Splits a string into lines, recognizing all supported line ending variants:
103/// `\r\n`, `\n\r`, `\r`, `\n`, `\x1E`, and `\u{0085}` (NEL).
104#[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/// Converts all line endings in a string to the specified `LineEndingFormat`.
153#[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/// Normalizes all line endings in the string to standard POSIX LF (`\n`).
180#[must_use]
181pub fn normalize_to_lf(input: &str) -> String {
182    convert_line_endings(
183        input,
184        LineEndingFormat::terminated(LineEndingKind::Lf),
185    )
186}
187
188/// Converts line endings in a string according to a `LineEndingOption` and target encoding.
189pub 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        // Terminated CRLF
277        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        // Separated CRLF
284        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        // Terminated CR (Mac)
291        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        // Acorn LFCR
298        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        // QNX RS
305        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        // IBM NEL
312        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        // MacRoman default -> CR
324        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        // CP437 default -> CRLF
332        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        // Preserve -> identical
340        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        // Unsupported NEL on MacRoman -> error
348        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}