Skip to main content

maybe_fatal/
color_palette.rs

1pub use ariadne::{Color, ColorGenerator};
2
3/// A selection of colors to use when building [diagnostic](crate::Diagnostic)s.
4#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
5pub struct ColorPalette {
6    /// The primary color to highlight diagnostics with when there is not a more specific option.
7    pub special: Color,
8
9    /// Colors with no assigned meaning.
10    pub random: [Color; Self::N_RANDOM_COLORS],
11}
12
13impl ColorPalette {
14    /// The number of colors in [`Self::random`].
15    pub const N_RANDOM_COLORS: usize = 4;
16
17    /// The default value of [`Self::random`].
18    pub const DEFAULT_RANDOM_COLORS: [Color; Self::N_RANDOM_COLORS] = {
19        // This is by no means the most flexible approach, but `core::array::from_fn` isn't stable
20        // as a `const` function yet, so this is basically the best we can do right now.
21        let mut r#gen = ColorGenerator::new();
22        [r#gen.next(), r#gen.next(), r#gen.next(), r#gen.next()]
23    };
24
25    /// The default value of [`Self::special`].
26    pub const DEFAULT_SPECIAL_COLOR: Color = Color::Fixed(81);
27
28    /// Constructs a new [`ColorPalette`] using the provided color generator.
29    ///
30    /// Builder methods can be chained with this one to further customize the colors.
31    pub const fn new() -> Self {
32        Self {
33            special: Self::DEFAULT_SPECIAL_COLOR,
34            random: Self::DEFAULT_RANDOM_COLORS,
35        }
36    }
37
38    /// Changes the [special](Self::special) color.
39    pub const fn with_special(&mut self, color: Color) -> &mut Self {
40        self.special = color;
41        self
42    }
43
44    /// Changes the [random colors](Self::random).
45    pub const fn with_random_colors(
46        &mut self,
47        colors: [Color; Self::N_RANDOM_COLORS],
48    ) -> &mut Self {
49        self.random = colors;
50        self
51    }
52
53    /// Regenerates the [random colors](Self::random) using the provided color generator.
54    pub fn with_regenerated_random_colors(&mut self, color_gen: &mut ColorGenerator) -> &mut Self {
55        self.with_random_colors(core::array::from_fn(|_| color_gen.next()))
56    }
57}
58
59impl Default for ColorPalette {
60    fn default() -> Self {
61        Self::new()
62    }
63}