Skip to main content

yaiko_core/
format_policy.rs

1//! Deterministic source-formatting policy facade.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum LineEnding {
4    Lf,
5    Crlf,
6}
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum FormatError {
9    InvalidIndent,
10    InvalidInput,
11}
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct FormatPolicy {
14    pub indent: usize,
15    pub line_ending: LineEnding,
16    pub trailing_newline: bool,
17}
18impl FormatPolicy {
19    pub fn new(indent: usize) -> Result<Self, FormatError> {
20        if indent == 0 || indent > 8 {
21            return Err(FormatError::InvalidIndent);
22        }
23        Ok(Self {
24            indent,
25            line_ending: LineEnding::Lf,
26            trailing_newline: true,
27        })
28    }
29    pub fn line_ending(mut self, ending: LineEnding) -> Self {
30        self.line_ending = ending;
31        self
32    }
33    pub fn trailing_newline(mut self, enabled: bool) -> Self {
34        self.trailing_newline = enabled;
35        self
36    }
37    pub fn normalize(&self, input: &str) -> Result<String, FormatError> {
38        if input.chars().any(|c| c == '\0') {
39            return Err(FormatError::InvalidInput);
40        }
41        let mut out = input.replace("\r\n", "\n").replace('\r', "\n");
42        let ending = match self.line_ending {
43            LineEnding::Lf => "\n",
44            LineEnding::Crlf => "\r\n",
45        };
46        if self.trailing_newline {
47            while out.ends_with('\n') {
48                out.pop();
49            }
50            out.push('\n');
51        } else {
52            while out.ends_with('\n') {
53                out.pop();
54            }
55        }
56        if ending != "\n" {
57            out = out.replace('\n', ending);
58        }
59        Ok(out)
60    }
61}
62impl Default for FormatPolicy {
63    fn default() -> Self {
64        Self::new(2).unwrap()
65    }
66}
67#[cfg(test)]
68mod tests {
69    use super::*;
70    #[test]
71    fn normalizes_line_endings_and_trailing_newline() {
72        let p = FormatPolicy::new(2).unwrap().line_ending(LineEnding::Crlf);
73        assert_eq!(p.normalize("a\r\nb\r\n").unwrap(), "a\r\nb\r\n");
74        assert_eq!(p.trailing_newline(false).normalize("a\n\n").unwrap(), "a")
75    }
76    #[test]
77    fn validates_indent_and_input() {
78        assert!(FormatPolicy::new(0).is_err());
79        assert!(FormatPolicy::new(9).is_err());
80        assert!(FormatPolicy::default().normalize("a\0").is_err())
81    }
82}