use std::collections::BTreeMap;
use std::sync::Arc;
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LabelMode {
Humanized,
Raw,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Labels {
mode: LabelMode,
aliases: Option<Arc<BTreeMap<String, String>>>,
captured: Option<Arc<BTreeMap<String, CapturedLabel>>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CapturedLabel {
key: Option<crate::data::RawKey>,
display: String,
}
impl Default for Labels {
fn default() -> Self {
Self::humanized()
}
}
impl Labels {
#[must_use]
pub const fn humanized() -> Self {
Self {
mode: LabelMode::Humanized,
aliases: None,
captured: None,
}
}
#[must_use]
pub const fn raw() -> Self {
Self {
mode: LabelMode::Raw,
aliases: None,
captured: None,
}
}
#[must_use]
pub const fn is_humanized(&self) -> bool {
matches!(self.mode, LabelMode::Humanized)
}
pub fn get_aliases(&self) -> Option<impl ExactSizeIterator<Item = (&str, &str)> + '_> {
if self.aliases.is_none() && self.captured.is_none() {
return None;
}
let keys = self
.aliases
.iter()
.flat_map(|aliases| aliases.keys())
.chain(self.captured.iter().flat_map(|captured| captured.keys()))
.collect::<std::collections::BTreeSet<_>>();
Some(
keys.into_iter()
.map(|raw| (raw.as_str(), self.alias_display(raw).expect("actual alias"))),
)
}
#[must_use]
pub fn alias(mut self, raw: impl Into<String>, display: impl Into<String>) -> Self {
Arc::make_mut(
self.aliases
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert(raw.into(), display.into());
self
}
#[must_use]
pub fn aliases<I, R, D>(mut self, aliases: I) -> Self
where
I: IntoIterator<Item = (R, D)>,
R: Into<String>,
D: Into<String>,
{
for (raw, display) in aliases {
self = self.alias(raw, display);
}
self
}
#[doc(hidden)]
#[must_use]
pub fn capture_alias(
mut self,
raw: impl Into<String>,
key: Option<crate::data::RawKey>,
display: impl Into<String>,
) -> Self {
Arc::make_mut(
self.captured
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert(
raw.into(),
CapturedLabel {
key,
display: display.into(),
},
);
self
}
pub(crate) fn with_captured_aliases_from(mut self, source: &Self) -> Self {
if let Some(captured) = &mut self.captured {
if let Some(source) = &source.captured {
if !Arc::ptr_eq(captured, source) {
let captured = Arc::make_mut(captured);
for (raw, entry) in source.iter() {
captured.entry(raw.clone()).or_insert_with(|| entry.clone());
}
}
}
} else {
self.captured.clone_from(&source.captured);
}
self
}
pub(crate) fn for_captured_source(&self, source: &Self) -> Self {
Self {
mode: self.mode,
aliases: self.aliases.clone(),
captured: source.captured.clone(),
}
}
fn alias_display(&self, raw: &str) -> Option<&str> {
if let Some(display) = self.aliases.as_ref().and_then(|aliases| aliases.get(raw)) {
return Some(display);
}
let capture = self.captured.as_ref()?.get(raw)?;
if let Some(crate::data::RawKey::String(original)) = &capture.key {
if let Some(alias) = self
.aliases
.as_ref()
.and_then(|aliases| aliases.get(original))
{
return Some(alias);
}
}
Some(&capture.display)
}
pub fn resolve(&self, raw: &str) -> Result<String, Error> {
let display = if let Some(alias) = self.alias_display(raw) {
copy_label(alias)
} else if self.mode == LabelMode::Humanized {
humanize(raw)
} else {
copy_label(raw)
}?;
crate::text::validate_for(&display, "label")?;
Ok(display)
}
pub(crate) fn resolve_domain<'a>(
&self,
domain: &str,
raw_labels: impl IntoIterator<Item = &'a str>,
) -> Result<Vec<String>, Error> {
let mut identities = Vec::new();
let mut resolved = Vec::new();
let raw_labels = raw_labels.into_iter();
let minimum = raw_labels.size_hint().0;
crate::data::source::reserve_source(&mut identities, minimum)?;
crate::data::source::reserve_source(&mut resolved, minimum)?;
for raw in raw_labels {
crate::data::source::reserve_source(&mut identities, 1)?;
crate::data::source::reserve_source(&mut resolved, 1)?;
let display = self.resolve(raw)?;
let mut collision = None;
for (&previous, prior) in identities.iter().zip(&resolved) {
if prior == &display && previous != raw {
collision = Some(previous);
break;
}
}
if let Some(previous) = collision {
let alias_guidance = if self.aliases.as_ref().is_some_and(|aliases| {
aliases.contains_key(previous) || aliases.contains_key(raw)
}) {
"change or remove the colliding aliases; Labels::raw() does not override explicit aliases"
} else {
"configure an explicit alias or use Labels::raw()"
};
return Err(Error::Render(format!(
"label collision in {domain}: raw identities {previous:?} and {raw:?} both resolve to {display:?}; {alias_guidance}"
).into()));
}
identities.push(raw);
resolved.push(display);
}
Ok(resolved)
}
}
fn copy_label(raw: &str) -> Result<String, Error> {
let mut output = String::new();
reserve_label(&mut output, raw.len())?;
output.push_str(raw);
Ok(output)
}
fn reserve_label(output: &mut String, count: usize) -> Result<(), Error> {
crate::data::source::reserve_source_string(output, count)
}
fn humanize(raw: &str) -> Result<String, Error> {
let mut split = String::new();
reserve_label(
&mut split,
raw.len()
.checked_mul(2)
.ok_or_else(|| Error::Render("humanized label length overflow".into()))?,
)?;
let mut chars = raw.chars().peekable();
let mut previous = None;
let mut last_was_space = true;
while let Some(character) = chars.next() {
let next = chars.peek().copied();
let prior = previous.replace(character);
if matches!(character, '_' | '-' | '.' | ' ' | '\t' | '\n' | '\r') {
if !last_was_space {
split.push(' ');
last_was_space = true;
}
continue;
}
if should_split_before(prior, character, next) && !last_was_space {
split.push(' ');
}
split.push(character);
last_was_space = false;
}
let mut output = String::new();
for (index, word) in split.split_whitespace().enumerate() {
let acronym = acronym(word);
reserve_label(
&mut output,
word.len()
.checked_add(12)
.ok_or_else(|| Error::Render("humanized word length overflow".into()))?,
)?;
if index != 0 {
output.push(' ');
}
if let Some(acronym) = acronym {
output.push_str(acronym);
} else if word.len() > 1 && word.bytes().all(|c| c.is_ascii_uppercase()) {
output.push_str(word);
} else {
for (offset, character) in word.chars().enumerate() {
let character = character.to_ascii_lowercase();
if index == 0 && offset == 0 {
output.extend(character.to_uppercase());
} else {
output.push(character);
}
}
}
}
if output.is_empty() {
copy_label(raw)
} else {
Ok(output)
}
}
fn should_split_before(previous: Option<char>, current: char, next: Option<char>) -> bool {
let Some(previous) = previous else {
return false;
};
(previous.is_ascii_lowercase() && current.is_ascii_uppercase())
|| (previous.is_ascii_digit() && current.is_ascii_alphabetic())
|| (previous.is_ascii_alphabetic() && current.is_ascii_digit())
|| (previous.is_ascii_uppercase()
&& current.is_ascii_uppercase()
&& next.is_some_and(|character| character.is_ascii_lowercase()))
}
fn acronym(word: &str) -> Option<&'static str> {
[
("ci", "CI"),
("dna", "DNA"),
("hwe", "HWE"),
("id", "ID"),
("ms", "MS"),
("mz", "m/z"),
("m/z", "m/z"),
("pca", "PCA"),
("qc", "QC"),
("rna", "RNA"),
("tsne", "t-SNE"),
("t-sne", "t-SNE"),
("umap", "UMAP"),
("x", "X"),
("y", "Y"),
("z", "Z"),
]
.into_iter()
.find_map(|(raw, display)| word.eq_ignore_ascii_case(raw).then_some(display))
}