lichtung_plot/spec/
categorical.rs1use std::sync::Arc;
2
3use crate::Error;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ValueSort {
8 Ascending,
10 Descending,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, Default)]
16pub enum CategoryOrder {
17 #[default]
19 Observed,
20 Explicit(Vec<String>),
22 Value(ValueSort),
24}
25
26impl CategoryOrder {
27 #[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#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct CategoricalColorMap {
46 entries: Arc<Vec<(String, crate::theme::OpaqueColor)>>,
47}
48
49impl CategoricalColorMap {
50 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(
66 format!("categorical color label {key:?} is duplicated").into(),
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 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 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}