papergrid/ansi/
ansi_str.rs

1use core::fmt::{self, Write};
2
3use super::ANSIFmt;
4
5/// The structure represents a ANSI color by suffix and prefix.
6#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
7pub struct ANSIStr<'a> {
8    prefix: &'a str,
9    suffix: &'a str,
10}
11
12impl<'a> ANSIStr<'a> {
13    /// Constructs a new instance with suffix and prefix.
14    ///
15    /// They are not checked so you should make sure you provide correct ANSI.
16    /// Otherwise you may want to use [`TryFrom`].
17    ///
18    /// [`TryFrom`]: std::convert::TryFrom
19    pub const fn new(prefix: &'a str, suffix: &'a str) -> Self {
20        Self { prefix, suffix }
21    }
22
23    /// Constructs a new instance with suffix and prefix set to empty strings.
24    pub const fn empty() -> Self {
25        Self::new("", "")
26    }
27
28    /// Verifies if anything was actually set.
29    pub const fn is_empty(&self) -> bool {
30        self.prefix.is_empty() && self.suffix.is_empty()
31    }
32
33    /// Gets a reference to a prefix.
34    pub const fn get_prefix(&self) -> &'a str {
35        self.prefix
36    }
37
38    /// Gets a reference to a suffix.
39    pub const fn get_suffix(&self) -> &'a str {
40        self.suffix
41    }
42}
43
44impl ANSIFmt for ANSIStr<'_> {
45    fn fmt_ansi_prefix<W: Write>(&self, f: &mut W) -> fmt::Result {
46        f.write_str(self.prefix)
47    }
48
49    fn fmt_ansi_suffix<W: Write>(&self, f: &mut W) -> fmt::Result {
50        f.write_str(self.suffix)
51    }
52}