use std::sync::Arc;
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueSort {
Ascending,
Descending,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum CategoryOrder {
#[default]
Observed,
Explicit(Vec<String>),
Value(ValueSort),
}
impl CategoryOrder {
#[must_use]
pub fn explicit<S>(levels: impl IntoIterator<Item = S>) -> Self
where
S: Into<String>,
{
Self::Explicit(levels.into_iter().map(Into::into).collect())
}
}
impl From<ValueSort> for CategoryOrder {
fn from(sort: ValueSort) -> Self {
Self::Value(sort)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CategoricalColorMap {
entries: Arc<Vec<(String, crate::theme::OpaqueColor)>>,
}
impl CategoricalColorMap {
pub fn new(
input: impl IntoIterator<Item = (String, crate::theme::OpaqueColor)>,
) -> Result<Self, Error> {
let mut entries: Vec<(String, crate::theme::OpaqueColor)> = Vec::new();
for (key, color) in input {
if key.is_empty() || key.trim() != key || key.chars().any(char::is_control) {
return Err(Error::Data("categorical color labels must be non-empty and contain no surrounding whitespace or control characters".into()));
}
if entries.iter().any(|(previous, _)| previous == &key) {
return Err(Error::Data(format!(
"categorical color label {key:?} is duplicated"
)));
}
entries
.len()
.checked_add(1)
.ok_or_else(|| Error::Data("categorical map length overflow".into()))?;
entries
.try_reserve_exact(1)
.map_err(|_| Error::Data("cannot reserve categorical color map".into()))?;
entries.push((key, color));
}
if entries.is_empty() {
return Err(Error::Data(
"categorical colors require at least one category label".into(),
));
}
Ok(Self {
entries: Arc::new(entries),
})
}
pub fn entries(&self) -> impl ExactSizeIterator<Item = (&str, crate::theme::OpaqueColor)> + '_ {
self.entries
.iter()
.map(|(key, color)| (key.as_str(), *color))
}
pub fn color(&self, label: &str) -> Option<crate::theme::OpaqueColor> {
self.entries
.iter()
.find(|(key, _)| key == label)
.map(|(_, color)| *color)
}
pub(crate) fn color_in(&self, label: &str) -> Option<crate::theme::OpaqueColor> {
for (candidate, color) in self.entries() {
if crate::font::canonical::same_bytes(candidate, label) {
return Some(color);
}
}
None
}
}