Skip to main content

uucore/mods/
line_ending.rs

1// This file is part of the uutils coreutils package.
2//
3// For the full copyright and license information, please view the LICENSE
4// file that was distributed with this source code.
5//! Provides consistent newline/zero terminator handling for `-z`/`--zero` flags.
6//!
7//! See the [`LineEnding`] struct for more information.
8use std::fmt::Display;
9
10/// Line ending of either `\n` or `\0`
11///
12/// Used by various utilities that have the option to separate lines by nul
13/// characters instead of `\n`. Usually, this is specified with the `-z` or
14/// `--zero` flag.
15///
16/// The [`Display`] implementation writes the character corresponding to the
17/// variant to the formatter.
18#[repr(u8)]
19#[derive(Clone, Copy, Debug, Default, PartialEq)]
20pub enum LineEnding {
21    #[default]
22    /// Newline character (`\n`)
23    Newline = b'\n',
24
25    /// Null character (`\0`)
26    Nul = 0,
27}
28
29impl Display for LineEnding {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Self::Newline => writeln!(f),
33            Self::Nul => write!(f, "\0"),
34        }
35    }
36}
37
38impl From<LineEnding> for u8 {
39    fn from(line_ending: LineEnding) -> Self {
40        line_ending as Self
41    }
42}
43
44impl LineEnding {
45    /// Create a [`LineEnding`] from a `-z`/`--zero` flag
46    ///
47    /// If `is_zero_terminated` is true, [`LineEnding::Nul`] is returned,
48    /// otherwise [`LineEnding::Newline`].
49    pub fn from_zero_flag(is_zero_terminated: bool) -> Self {
50        if is_zero_terminated {
51            Self::Nul
52        } else {
53            Self::Newline
54        }
55    }
56}