string_auto_indent/
line_ending.rs

1/// Enum representing the detected line ending style.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3#[allow(clippy::upper_case_acronyms)]
4pub enum LineEnding {
5    LF,   // "\n" (Unix, Linux, macOS)
6    CRLF, // "\r\n" (Windows)
7    CR,   // "\r" (old macOS)
8}
9
10impl LineEnding {
11    /// Detects the line ending style used in the input string.
12    pub fn detect(s: &str) -> Self {
13        if s.contains("\r\n") {
14            Self::CRLF
15        } else if s.contains("\r") {
16            Self::CR
17        } else {
18            Self::LF
19        }
20    }
21
22    /// Returns the string representation of the line ending.
23    pub fn as_str(&self) -> &'static str {
24        match self {
25            Self::LF => "\n",
26            Self::CRLF => "\r\n",
27            Self::CR => "\r",
28        }
29    }
30
31    /// Normalize to `\n` for consistent processing.
32    pub fn normalize(s: &str) -> String {
33        s.replace("\r\n", "\n").replace("\r", "\n")
34    }
35
36    /// Restores line endings back to their original value.
37    #[allow(dead_code)]
38    pub fn restore(&self, s: &str) -> String {
39        s.replace("\n", self.as_str())
40    }
41
42    /// Applies the line endiing to the given lines.
43    pub fn restore_from_lines(&self, lines: Vec<String>) -> String {
44        lines.join(self.as_str())
45    }
46}