Skip to main content

lichtung_plot/spec/
categorical.rs

1use std::sync::Arc;
2
3use crate::Error;
4
5/// Direction used to order categories by their prepared rendered value.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ValueSort {
8    /// Sort from the smallest rendered value to the largest.
9    Ascending,
10    /// Sort from the largest rendered value to the smallest.
11    Descending,
12}
13
14/// Display ordering for one categorical plot channel.
15#[derive(Debug, Clone, PartialEq, Eq, Default)]
16pub enum CategoryOrder {
17    /// Preserve deterministic first-observed category order.
18    #[default]
19    Observed,
20    /// Render category identities in this exact caller-supplied order.
21    Explicit(Vec<String>),
22    /// Sort categories by the scalar value prepared for each rendered category.
23    Value(ValueSort),
24}
25
26impl CategoryOrder {
27    /// Construct an exact caller-supplied category order.
28    #[must_use]
29    pub fn explicit<S>(levels: impl IntoIterator<Item = S>) -> Self
30    where
31        S: Into<String>,
32    {
33        Self::Explicit(levels.into_iter().map(Into::into).collect())
34    }
35}
36
37impl From<ValueSort> for CategoryOrder {
38    fn from(sort: ValueSort) -> Self {
39        Self::Value(sort)
40    }
41}
42
43/// Exact caller-owned colors for categorical plot levels.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct CategoricalColorMap {
46    entries: Arc<Vec<(String, crate::theme::OpaqueColor)>>,
47}
48
49impl CategoricalColorMap {
50    /// Constructs a non-empty color map with unique, exact category labels.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error when a label is empty, has surrounding whitespace or
55    /// control characters, or appears more than once.
56    pub fn new(
57        input: impl IntoIterator<Item = (String, crate::theme::OpaqueColor)>,
58    ) -> Result<Self, Error> {
59        let mut entries: Vec<(String, crate::theme::OpaqueColor)> = Vec::new();
60        for (key, color) in input {
61            if key.is_empty() || key.trim() != key || key.chars().any(char::is_control) {
62                return Err(Error::Data("categorical color labels must be non-empty and contain no surrounding whitespace or control characters".into()));
63            }
64            if entries.iter().any(|(previous, _)| previous == &key) {
65                return Err(Error::Data(format!(
66                    "categorical color label {key:?} is duplicated"
67                )));
68            }
69            entries
70                .len()
71                .checked_add(1)
72                .ok_or_else(|| Error::Data("categorical map length overflow".into()))?;
73            entries
74                .try_reserve_exact(1)
75                .map_err(|_| Error::Data("cannot reserve categorical color map".into()))?;
76            entries.push((key, color));
77        }
78        if entries.is_empty() {
79            return Err(Error::Data(
80                "categorical colors require at least one category label".into(),
81            ));
82        }
83        Ok(Self {
84            entries: Arc::new(entries),
85        })
86    }
87
88    /// Inspect supplied raw keys and opaque colors in construction order.
89    pub fn entries(&self) -> impl ExactSizeIterator<Item = (&str, crate::theme::OpaqueColor)> + '_ {
90        self.entries
91            .iter()
92            .map(|(key, color)| (key.as_str(), *color))
93    }
94
95    /// Look up one exact raw key without trimming, display aliases or normalization.
96    pub fn color(&self, label: &str) -> Option<crate::theme::OpaqueColor> {
97        self.entries
98            .iter()
99            .find(|(key, _)| key == label)
100            .map(|(_, color)| *color)
101    }
102
103    pub(crate) fn color_in(&self, label: &str) -> Option<crate::theme::OpaqueColor> {
104        for (candidate, color) in self.entries() {
105            if crate::font::canonical::same_bytes(candidate, label) {
106                return Some(color);
107            }
108        }
109        None
110    }
111}