papergrid/color/
mod.rs

1use std::fmt::{self, Display, Formatter};
2
3#[cfg(feature = "color")]
4mod ansi_color;
5
6#[cfg(feature = "color")]
7pub use ansi_color::AnsiColor;
8
9#[allow(unreachable_pub)]
10/// A trait which prints an ANSI prefix and suffix.
11pub trait Color {
12    /// Print ANSI prefix.
13    fn fmt_prefix(&self, f: &mut Formatter<'_>) -> fmt::Result;
14
15    /// Print ANSI suffix.
16    fn fmt_suffix(&self, f: &mut Formatter<'_>) -> fmt::Result {
17        f.write_str("\u{1b}[0m")
18    }
19
20    /// Print colored text.
21    ///
22    /// It may not handle `\n` (new lines).
23    fn colorize<T>(&self, f: &mut Formatter<'_>, text: T) -> fmt::Result
24    where
25        T: Display,
26    {
27        self.fmt_prefix(f)?;
28        text.fmt(f)?;
29        self.fmt_suffix(f)?;
30        Ok(())
31    }
32}
33
34impl<C> Color for &C
35where
36    C: Color,
37{
38    fn fmt_prefix(&self, f: &mut Formatter<'_>) -> fmt::Result {
39        C::fmt_prefix(self, f)
40    }
41
42    fn fmt_suffix(&self, f: &mut Formatter<'_>) -> fmt::Result {
43        C::fmt_suffix(self, f)
44    }
45
46    fn colorize<T>(&self, f: &mut Formatter<'_>, text: T) -> fmt::Result
47    where
48        T: Display,
49    {
50        C::colorize(self, f, text)
51    }
52}