Skip to main content

str_utils/
normalize_newlines.rs

1use alloc::borrow::Cow;
2
3/// To extend `str` and `Cow<str>` to have `normalize_newlines` method.
4///
5/// This converts Unicode newline sequences to LF (`\n`) while avoiding allocation when the text is already normalized.
6pub trait NormalizeNewlines<'a> {
7    /// Returns a `Cow<str>` where newline sequences are normalized to LF (`\n`).
8    ///
9    /// Handles LF, VT, FF, CRLF, CR, NEL, LS, and PS. CRLF is treated as one newline sequence.
10    fn normalize_newlines(self) -> Cow<'a, str>;
11}
12
13impl<'a> NormalizeNewlines<'a> for &'a str {
14    #[inline]
15    fn normalize_newlines(self) -> Cow<'a, str> {
16        crate::newlines::replace_newlines_with(self, b'\n')
17    }
18}
19
20impl<'a> NormalizeNewlines<'a> for Cow<'a, str> {
21    #[inline]
22    fn normalize_newlines(self) -> Cow<'a, str> {
23        match self {
24            Cow::Borrowed(s) => s.normalize_newlines(),
25            Cow::Owned(s) => {
26                Cow::Owned(crate::cow_into_owned!(s, s.as_str().normalize_newlines(),))
27            },
28        }
29    }
30}