owo_colors/
overrides.rs

1use core::sync::atomic::{AtomicU8, Ordering};
2
3/// Set an override value for whether or not colors are supported.
4///
5/// If `true` is passed, [`if_supports_color`](crate::OwoColorize::if_supports_color) will always
6/// act as if colors are supported.
7///
8/// If `false` is passed, [`if_supports_color`](crate::OwoColorize::if_supports_color) will always
9/// act as if colors are **not** supported.
10///
11/// This behavior can be disabled using [`unset_override`], allowing `owo-colors` to return to
12/// inferring if colors are supported.
13#[cfg(feature = "supports-colors")]
14pub fn set_override(enabled: bool) {
15    OVERRIDE.set_force(enabled)
16}
17
18/// Remove any override value for whether or not colors are supported. This means
19/// [`if_supports_color`](crate::OwoColorize::if_supports_color) will resume checking if the given
20/// terminal output ([`Stream`](crate::Stream)) supports colors.
21///
22/// This override can be set using [`set_override`].
23#[cfg(feature = "supports-colors")]
24pub fn unset_override() {
25    OVERRIDE.unset()
26}
27
28pub(crate) static OVERRIDE: Override = Override::none();
29
30pub(crate) struct Override(AtomicU8);
31
32const FORCE_MASK: u8 = 0b10;
33const FORCE_ENABLE: u8 = 0b11;
34const FORCE_DISABLE: u8 = 0b10;
35const NO_FORCE: u8 = 0b00;
36
37impl Override {
38    const fn none() -> Self {
39        Self(AtomicU8::new(NO_FORCE))
40    }
41
42    fn inner(&self) -> u8 {
43        self.0.load(Ordering::SeqCst)
44    }
45
46    pub(crate) fn is_force_enabled_or_disabled(&self) -> (bool, bool) {
47        let inner = self.inner();
48
49        (inner == FORCE_ENABLE, inner == FORCE_DISABLE)
50    }
51
52    fn set_force(&self, enable: bool) {
53        self.0.store(FORCE_MASK | (enable as u8), Ordering::SeqCst)
54    }
55
56    fn unset(&self) {
57        self.0.store(0, Ordering::SeqCst);
58    }
59}