base64ct/
line_ending.rs

1//! Line endings.
2
3/// Carriage return
4pub(crate) const CHAR_CR: u8 = 0x0d;
5
6/// Line feed
7pub(crate) const CHAR_LF: u8 = 0x0a;
8
9/// Line endings: variants of newline characters that can be used with Base64.
10///
11/// Use [`LineEnding::default`] to get an appropriate line ending for the
12/// current operating system.
13#[allow(clippy::upper_case_acronyms)]
14#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
15pub enum LineEnding {
16    /// Carriage return: `\r` (Pre-OS X Macintosh)
17    CR,
18
19    /// Line feed: `\n` (Unix OSes)
20    LF,
21
22    /// Carriage return + line feed: `\r\n` (Windows)
23    CRLF,
24}
25
26impl Default for LineEnding {
27    // Default line ending matches conventions for target OS
28    #[cfg(windows)]
29    fn default() -> LineEnding {
30        LineEnding::CRLF
31    }
32    #[cfg(not(windows))]
33    fn default() -> LineEnding {
34        LineEnding::LF
35    }
36}
37
38#[allow(clippy::len_without_is_empty)]
39impl LineEnding {
40    /// Get the byte serialization of this [`LineEnding`].
41    pub fn as_bytes(self) -> &'static [u8] {
42        match self {
43            LineEnding::CR => &[CHAR_CR],
44            LineEnding::LF => &[CHAR_LF],
45            LineEnding::CRLF => &[CHAR_CR, CHAR_LF],
46        }
47    }
48
49    /// Get the encoded length of this [`LineEnding`].
50    pub fn len(self) -> usize {
51        self.as_bytes().len()
52    }
53}