1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::fmt::{self, Write};

use super::{ANSIFmt, ANSIStr};

/// The structure represents a ANSI color by suffix and prefix.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ANSIBuf {
    prefix: String,
    suffix: String,
}

impl ANSIBuf {
    /// Constructs a new instance with suffix and prefix.
    ///
    /// They are not checked so you should make sure you provide correct ANSI.
    /// Otherwise you may want to use [`TryFrom`].
    ///
    /// [`TryFrom`]: std::convert::TryFrom
    pub fn new<P, S>(prefix: P, suffix: S) -> Self
    where
        P: Into<String>,
        S: Into<String>,
    {
        let prefix = prefix.into();
        let suffix = suffix.into();

        Self { prefix, suffix }
    }

    /// Checks whether the color is not actually set.
    pub fn is_empty(&self) -> bool {
        self.prefix.is_empty() && self.suffix.is_empty()
    }

    /// Gets a reference to a prefix.
    pub fn get_prefix(&self) -> &str {
        &self.prefix
    }

    /// Gets a reference to a suffix.
    pub fn get_suffix(&self) -> &str {
        &self.suffix
    }

    /// Gets a reference as a color.
    pub fn as_ref(&self) -> ANSIStr<'_> {
        ANSIStr::new(&self.prefix, &self.suffix)
    }
}

impl ANSIFmt for ANSIBuf {
    fn fmt_ansi_prefix<W: Write>(&self, f: &mut W) -> fmt::Result {
        f.write_str(&self.prefix)
    }

    fn fmt_ansi_suffix<W: Write>(&self, f: &mut W) -> fmt::Result {
        f.write_str(&self.suffix)
    }
}

#[cfg(feature = "ansi")]
impl std::convert::TryFrom<&str> for ANSIBuf {
    type Error = ();

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        parse_ansi_color(value).ok_or(())
    }
}

#[cfg(feature = "ansi")]
impl std::convert::TryFrom<String> for ANSIBuf {
    type Error = ();

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

#[cfg(feature = "ansi")]
fn parse_ansi_color(s: &str) -> Option<ANSIBuf> {
    let mut blocks = ansi_str::get_blocks(s);
    let block = blocks.next()?;
    let style = block.style();

    let start = style.start().to_string();
    let end = style.end().to_string();

    Some(ANSIBuf::new(start, end))
}

impl From<ANSIStr<'_>> for ANSIBuf {
    fn from(value: ANSIStr<'_>) -> Self {
        Self::new(value.get_prefix(), value.get_suffix())
    }
}