owo_colors/
supports_colors.rs

1use core::fmt;
2
3#[cfg(feature = "supports-colors")]
4/// A display wrapper which applies a transformation based on if the given stream supports
5/// colored terminal output
6pub struct SupportsColorsDisplay<'a, InVal, Out, ApplyFn>(
7    pub(crate) &'a InVal,
8    pub(crate) ApplyFn,
9    pub(crate) supports_color::Stream,
10)
11where
12    InVal: ?Sized,
13    ApplyFn: Fn(&'a InVal) -> Out;
14
15use crate::OVERRIDE;
16
17macro_rules! impl_fmt_for {
18    ($($trait:path),* $(,)?) => {
19        $(
20            impl<'a, In, Out, F> $trait for SupportsColorsDisplay<'a, In, Out, F>
21                where In: $trait,
22                      Out: $trait,
23                      F: Fn(&'a In) -> Out,
24            {
25                #[inline(always)]
26                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27                    let (force_enabled, force_disabled) = OVERRIDE.is_force_enabled_or_disabled();
28                    if force_enabled || (
29                        supports_color::on_cached(self.2)
30                            .map(|level| level.has_basic)
31                            .unwrap_or(false)
32                        && !force_disabled
33                    ) {
34                        <Out as $trait>::fmt(&self.1(self.0), f)
35                    } else {
36                        <In as $trait>::fmt(self.0, f)
37                    }
38                }
39            }
40        )*
41    };
42}
43
44impl_fmt_for! {
45    fmt::Display,
46    fmt::Debug,
47    fmt::UpperHex,
48    fmt::LowerHex,
49    fmt::Binary,
50    fmt::UpperExp,
51    fmt::LowerExp,
52    fmt::Octal,
53    fmt::Pointer,
54}