papergrid/color/
mod.rs

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
use std::fmt::{self, Display, Formatter};

#[cfg(feature = "color")]
mod ansi_color;

#[cfg(feature = "color")]
pub use ansi_color::AnsiColor;

#[allow(unreachable_pub)]
/// A trait which prints an ANSI prefix and suffix.
pub trait Color {
    /// Print ANSI prefix.
    fn fmt_prefix(&self, f: &mut Formatter<'_>) -> fmt::Result;

    /// Print ANSI suffix.
    fn fmt_suffix(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("\u{1b}[0m")
    }

    /// Print colored text.
    ///
    /// It may not handle `\n` (new lines).
    fn colorize<T>(&self, f: &mut Formatter<'_>, text: T) -> fmt::Result
    where
        T: Display,
    {
        self.fmt_prefix(f)?;
        text.fmt(f)?;
        self.fmt_suffix(f)?;
        Ok(())
    }
}

impl<C> Color for &C
where
    C: Color,
{
    fn fmt_prefix(&self, f: &mut Formatter<'_>) -> fmt::Result {
        C::fmt_prefix(self, f)
    }

    fn fmt_suffix(&self, f: &mut Formatter<'_>) -> fmt::Result {
        C::fmt_suffix(self, f)
    }

    fn colorize<T>(&self, f: &mut Formatter<'_>, text: T) -> fmt::Result
    where
        T: Display,
    {
        C::colorize(self, f, text)
    }
}