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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Global override of color control

#![cfg_attr(not(test), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(missing_docs)]
#![warn(clippy::print_stderr)]
#![warn(clippy::print_stdout)]

use core::sync::atomic::{AtomicUsize, Ordering};

/// Selection for overriding color output
#[allow(clippy::exhaustive_enums)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ColorChoice {
    /// Use colors if the output device appears to support them
    Auto,
    /// Like `Always`, except it never tries to use anything other than emitting ANSI
    /// color codes.
    AlwaysAnsi,
    /// Try very hard to emit colors.
    ///
    /// This includes emitting ANSI colors on Windows if the console API is unavailable.
    Always,
    /// Never emit colors.
    Never,
}

impl ColorChoice {
    /// Get the current [`ColorChoice`] state
    pub fn global() -> Self {
        USER.get()
    }

    /// Override the detected [`ColorChoice`]
    pub fn write_global(self) {
        USER.set(self);
    }
}

impl Default for ColorChoice {
    fn default() -> Self {
        Self::Auto
    }
}

static USER: AtomicChoice = AtomicChoice::new();

#[derive(Debug)]
pub(crate) struct AtomicChoice(AtomicUsize);

impl AtomicChoice {
    pub(crate) const fn new() -> Self {
        Self(AtomicUsize::new(Self::from_choice(ColorChoice::Auto)))
    }

    pub(crate) fn get(&self) -> ColorChoice {
        let choice = self.0.load(Ordering::SeqCst);
        Self::to_choice(choice).expect("Only `ColorChoice` values can be `set`")
    }

    pub(crate) fn set(&self, choice: ColorChoice) {
        let choice = Self::from_choice(choice);
        self.0.store(choice, Ordering::SeqCst);
    }

    const fn from_choice(choice: ColorChoice) -> usize {
        match choice {
            ColorChoice::Auto => 0,
            ColorChoice::AlwaysAnsi => 1,
            ColorChoice::Always => 2,
            ColorChoice::Never => 3,
        }
    }

    const fn to_choice(choice: usize) -> Option<ColorChoice> {
        match choice {
            0 => Some(ColorChoice::Auto),
            1 => Some(ColorChoice::AlwaysAnsi),
            2 => Some(ColorChoice::Always),
            3 => Some(ColorChoice::Never),
            _ => None,
        }
    }
}

impl Default for AtomicChoice {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn choice_serialization() {
        let expected = vec![
            ColorChoice::Auto,
            ColorChoice::AlwaysAnsi,
            ColorChoice::Always,
            ColorChoice::Never,
        ];
        let values: Vec<_> = expected
            .iter()
            .cloned()
            .map(AtomicChoice::from_choice)
            .collect();
        let actual: Vec<_> = values
            .iter()
            .cloned()
            .filter_map(AtomicChoice::to_choice)
            .collect();
        assert_eq!(expected, actual);
    }
}