Skip to main content

str_utils/
replace_newlines_with_space.rs

1use alloc::borrow::Cow;
2
3/// To extend `str` and `Cow<str>` to have `replace_newlines_with_space` method.
4///
5/// This can be useful when you need to normalize multiline strings into a single line for logging, database storage, or display purposes.
6pub trait ReplaceNewlinesWithSpace<'a> {
7    /// Returns a `Cow<str>` where all newline sequences are replaced with a space.
8    ///
9    /// Handles LF, VT, FF, CRLF, CR, NEL, LS, and PS. CRLF is treated as one newline sequence.
10    fn replace_newlines_with_space(self) -> Cow<'a, str>;
11}
12
13impl<'a> ReplaceNewlinesWithSpace<'a> for &'a str {
14    #[inline]
15    fn replace_newlines_with_space(self) -> Cow<'a, str> {
16        crate::newlines::replace_newlines_with(self, b' ')
17    }
18}
19
20impl<'a> ReplaceNewlinesWithSpace<'a> for Cow<'a, str> {
21    #[inline]
22    fn replace_newlines_with_space(self) -> Cow<'a, str> {
23        match self {
24            Cow::Borrowed(s) => s.replace_newlines_with_space(),
25            Cow::Owned(s) => {
26                Cow::Owned(crate::cow_into_owned!(s, s.as_str().replace_newlines_with_space(),))
27            },
28        }
29    }
30}