texcraft_stdext/
color.rs

1//! Terminal coloring
2//!
3//! The Texcraft project uses the
4//! [Colored crate](https://docs.rs/colored/latest/colored/) for terminal coloring.
5//! However, per [Texcraft's dependency policy](https://texcraft.dev/governance/dependencies.html),
6//! use of this crate must be behind a Cargo feature.
7//! In the case of Colored, the Cargo feature is `color`.
8//!
9//! This module implements the Cargo feature.
10//!
11//! The module contains a single trait [`Colorize`].
12//! When the Cargo feature is enabled, this trait is essentially identical to
13//!     the Colored crate's `Colorize` trait.
14//! Specifically, it just forwards all method calls to the Colored crate.
15//! When the Cargo feature is disabled, the trait is a no-op.
16//! In both cases, downstream code can just call methods on the trait:
17//!
18//! ```
19//! use texcraft_stdext::color::Colorize;
20//! println!["{}", "Hello, World".bold().bright_red()];
21//! ```
22
23#[cfg(feature = "color")]
24pub type ColoredString = colored::ColoredString;
25
26#[cfg(not(feature = "color"))]
27pub type ColoredString = &str;
28
29macro_rules! colorize_impl {
30    ( $( $method_name: ident, )+ ) => {
31        /// Trait that provides coloring methods on strings.
32        ///
33        /// See the module documentation for information.
34        pub trait Colorize {
35            $(
36                fn $method_name(self) -> ColoredString;
37            )+
38        }
39        #[cfg(feature="color")]
40        impl Colorize for ColoredString {
41            $(
42                fn $method_name(self) -> ColoredString {
43                    colored::Colorize::$method_name(self)
44                }
45            )+
46        }
47        #[cfg(feature="color")]
48        impl Colorize for &str {
49            $(
50                fn $method_name(self) -> ColoredString {
51                    colored::Colorize::$method_name(self)
52                }
53            )+
54        }
55        #[cfg(not(feature="color"))]
56        impl Colorize for &str {
57            $(
58                fn $method_name(self) -> ColoredString {
59                    self
60                }
61            )+
62        }
63
64    };
65}
66
67colorize_impl!(
68    bold,
69    bright_cyan,
70    bright_blue,
71    bright_red,
72    bright_yellow,
73    italic,
74);