use std::sync::Arc;
use crate::{data::RawKey, Error, Result};
pub(crate) fn shared_text(source: &str) -> Result<Arc<str>> {
let bytes = std::alloc::Layout::array::<u8>(source.len())
.map_err(|_| Error::Render("guide identity text layout overflow".into()))?;
std::alloc::Layout::new::<[std::sync::atomic::AtomicUsize; 2]>()
.extend(bytes)
.map_err(|_| Error::Render("guide identity Arc layout overflow".into()))?;
Ok(Arc::from(super::source::copy_source_string(source)?))
}
macro_rules! raw_identity {
($name:ident) => {
#[derive(Debug, Clone)]
pub(crate) struct $name {
token: Arc<str>,
key: Arc<RawKey>,
}
impl $name {
pub(crate) fn new(value: &str) -> Result<Self> {
Ok(Self::from_shared(shared_text(value)?))
}
pub(crate) fn from_shared(token: Arc<str>) -> Self {
let key = RawKey::from(token.as_ref());
Self::from_key(token, key)
}
pub(crate) fn from_key(token: Arc<str>, key: RawKey) -> Self {
Self {
token,
key: Arc::new(key),
}
}
pub(crate) fn as_str(&self) -> &str {
&self.token
}
pub(crate) fn key(&self) -> &RawKey {
&self.key
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
self.key() == other.key()
}
}
impl Eq for $name {}
};
}
raw_identity!(RawField);
raw_identity!(RawCategory);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CategoryKey {
field: RawField,
value: RawCategory,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CategoryRef<'a> {
pub(crate) field: &'a str,
pub(crate) value: &'a str,
}
impl CategoryKey {
#[cfg(test)]
pub(crate) fn new(field: RawField, value: impl Into<Arc<str>>) -> Self {
Self {
field,
value: RawCategory::from_shared(value.into()),
}
}
pub(crate) fn from_raw(field: RawField, value: RawCategory) -> Self {
Self { field, value }
}
pub(crate) fn parts(&self) -> (&RawField, &RawCategory) {
(&self.field, &self.value)
}
pub(crate) fn mapped_color(
&self,
map: &crate::scales::CategoricalColorMap,
) -> Result<crate::style::OpaqueColor> {
let color = match self.value.key() {
RawKey::String(value) => map.color_in(value),
_ => None,
};
color.ok_or_else(|| {
Error::Data(
format!(
"categorical color map has no color for used raw key {:?}",
self.value.key()
)
.into(),
)
})
}
pub(crate) fn as_ref(&self) -> CategoryRef<'_> {
CategoryRef {
field: self.field.as_str(),
value: self.value.as_str(),
}
}
}
#[derive(Debug)]
pub(crate) struct CategoryDomain {
pub(crate) ordered: Vec<CategoryKey>,
}
impl CategoryDomain {
#[cfg(test)]
pub(crate) fn from_values(field: Option<&RawField>, values: Vec<String>) -> Result<Self> {
Ok(Self {
ordered: super::source::collect_source(values.into_iter().map(|value| {
Ok(CategoryKey::new(
field.expect("prepared categorical field").clone(),
value,
))
}))?,
})
}
pub(crate) fn from_source(
field: &RawField,
levels: impl IntoIterator<Item = impl AsRef<str>>,
values: &crate::CategoryValues,
) -> Result<Self> {
let mut ordered = Vec::new();
for level in levels {
let key = CategoryKey::from_raw(field.clone(), values.raw_category(level.as_ref())?);
if ordered.contains(&key) {
return Err(Error::Data(
format!(
"resolved categorical domain repeats raw key {:?}",
key.value.key()
)
.into(),
));
}
super::source::reserve_source(&mut ordered, 1)?;
ordered.push(key);
}
Ok(Self { ordered })
}
pub(crate) fn project_for(
&self,
field: &RawField,
values: &crate::CategoryValues,
) -> Result<Self> {
let local = super::source::collect_source(
values
.levels()
.iter()
.map(|level| values.raw_category(level)),
)?;
let mut ordered: Vec<CategoryKey> = Vec::new();
super::source::reserve_source(&mut ordered, self.ordered.len())?;
for (index, key) in self.ordered.iter().enumerate() {
let value = if let Some(value) = local.iter().find(|value| **value == key.value) {
value.clone()
} else {
let mut value = key.value.clone();
let occupied = |token: &str| {
local.iter().any(|other| other.as_str() == token)
|| ordered.iter().any(|entry| entry.value.as_str() == token)
};
if occupied(value.as_str()) {
let mut token = format!("__lichtung_unused_color_{index}");
while occupied(&token) {
super::source::reserve_source_string(&mut token, 1)?;
token.push('_');
}
value.token = shared_text(&token)?;
}
value
};
ordered.push(CategoryKey::from_raw(field.clone(), value));
}
Ok(Self { ordered })
}
pub(crate) fn values(&self) -> impl ExactSizeIterator<Item = &str> + Clone {
self.ordered.iter().map(|key| key.as_ref().value)
}
}
#[derive(Clone, Copy)]
pub(crate) enum CategoryOrderRef<'a> {
Raw(&'a [String]),
Keys(&'a CategoryDomain),
}
impl CategoryOrderRef<'_> {
pub(crate) fn len(self) -> usize {
match self {
Self::Raw(values) => values.len(),
Self::Keys(domain) => domain.ordered.len(),
}
}
}
impl<'a> CategoryOrderRef<'a> {
pub(crate) fn values(self) -> impl ExactSizeIterator<Item = &'a str> + Clone {
(0..self.len()).map(move |index| match self {
Self::Raw(values) => values[index].as_str(),
Self::Keys(domain) => domain.ordered[index].as_ref().value,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn category_identity_compares_raw_field_and_value_across_independent_storage() {
let field = || RawField::from_shared(Arc::from("cohort"));
let first = CategoryKey::new(field(), String::from(" first "));
let separately_owned = CategoryKey::new(field(), String::from(" first "));
assert!(!Arc::ptr_eq(
&first.value.token,
&separately_owned.value.token
));
assert_eq!(first, separately_owned);
assert_ne!(first, CategoryKey::new(field(), "first"));
assert_ne!(
first,
CategoryKey::new(RawField::from_shared(Arc::from("other")), " first ")
);
assert_eq!(first.as_ref().field, "cohort");
assert_eq!(first.as_ref().value, " first ");
}
}