Skip to main content

minus/
color.rs

1use std::borrow::Cow;
2
3mod palette;
4mod perceptual;
5mod sgr;
6
7pub use palette::ansi256_to_rgb;
8
9/// The maximum color depth accepted by the output terminal.
10#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
11pub enum ColorDepth {
12    /// Standard and bright ANSI colors, encoded without indexed color sequences.
13    Ansi16,
14    /// The 256-color ANSI palette.
15    Ansi256,
16    /// Preserve the original color sequences.
17    #[default]
18    TrueColor,
19}
20
21impl ColorDepth {
22    /// Limit SGR colors while preserving text and non-color controls.
23    /// ANSI 16 preserves hue families and separates distinct foreground/background
24    /// colors that would otherwise collapse to one palette entry.
25    #[must_use]
26    pub fn adapt<'a>(self, text: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
27        let text = text.into();
28        if self == Self::TrueColor
29            || !text.as_bytes().contains(&b'\x1b')
30            || !["38;", "48;", "58;", "38:", "48:", "58:"]
31                .iter()
32                .any(|pattern| text.contains(pattern))
33        {
34            return text;
35        }
36        match sgr::adapt(&text, self) {
37            Cow::Borrowed(_) => text,
38            Cow::Owned(converted) => Cow::Owned(converted),
39        }
40    }
41}
42
43#[cfg(test)]
44mod tests;