1use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use crate::Error;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9enum LabelMode {
10 Humanized,
11 Raw,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Labels {
21 mode: LabelMode,
22 aliases: Option<Arc<BTreeMap<String, String>>>,
23}
24
25impl Default for Labels {
26 fn default() -> Self {
27 Self::humanized()
28 }
29}
30
31impl Labels {
32 #[must_use]
34 pub const fn humanized() -> Self {
35 Self {
36 mode: LabelMode::Humanized,
37 aliases: None,
38 }
39 }
40
41 #[must_use]
43 pub const fn raw() -> Self {
44 Self {
45 mode: LabelMode::Raw,
46 aliases: None,
47 }
48 }
49
50 #[must_use]
52 pub const fn is_humanized(&self) -> bool {
53 matches!(self.mode, LabelMode::Humanized)
54 }
55
56 pub fn get_aliases(&self) -> Option<impl ExactSizeIterator<Item = (&str, &str)> + '_> {
61 self.aliases.as_ref().map(|aliases| {
62 aliases
63 .iter()
64 .map(|(raw, display)| (raw.as_str(), display.as_str()))
65 })
66 }
67
68 #[must_use]
70 pub fn alias(mut self, raw: impl Into<String>, display: impl Into<String>) -> Self {
71 Arc::make_mut(
72 self.aliases
73 .get_or_insert_with(|| Arc::new(BTreeMap::new())),
74 )
75 .insert(raw.into(), display.into());
76 self
77 }
78
79 #[must_use]
81 pub fn aliases<I, R, D>(mut self, aliases: I) -> Self
82 where
83 I: IntoIterator<Item = (R, D)>,
84 R: Into<String>,
85 D: Into<String>,
86 {
87 for (raw, display) in aliases {
88 self = self.alias(raw, display);
89 }
90 self
91 }
92
93 pub fn resolve(&self, raw: &str) -> Result<String, Error> {
109 let display =
110 if let Some(alias) = self.aliases.as_ref().and_then(|aliases| aliases.get(raw)) {
111 copy_label(alias)
112 } else if self.mode == LabelMode::Humanized {
113 humanize(raw)
114 } else {
115 copy_label(raw)
116 }?;
117 crate::text::validate_for(&display, "label")?;
118 Ok(display)
119 }
120
121 pub(crate) fn resolve_domain<'a>(
122 &self,
123 domain: &str,
124 raw_labels: impl IntoIterator<Item = &'a str>,
125 ) -> Result<Vec<String>, Error> {
126 let mut identities = Vec::new();
127 let mut resolved = Vec::new();
128 let raw_labels = raw_labels.into_iter();
129 let minimum = raw_labels.size_hint().0;
130 crate::data::source::reserve_source(&mut identities, minimum)?;
131 crate::data::source::reserve_source(&mut resolved, minimum)?;
132 for raw in raw_labels {
133 crate::data::source::reserve_source(&mut identities, 1)?;
134 crate::data::source::reserve_source(&mut resolved, 1)?;
135 let display = self.resolve(raw)?;
136 let mut collision = None;
137 for (&previous, prior) in identities.iter().zip(&resolved) {
138 if prior == &display && previous != raw {
139 collision = Some(previous);
140 break;
141 }
142 }
143 if let Some(previous) = collision {
144 let alias_guidance = if self.aliases.as_ref().is_some_and(|aliases| {
145 aliases.contains_key(previous) || aliases.contains_key(raw)
146 }) {
147 "change or remove the colliding aliases; Labels::raw() does not override explicit aliases"
148 } else {
149 "configure an explicit alias or use Labels::raw()"
150 };
151 return Err(Error::Render(format!(
152 "label collision in {domain}: raw identities {previous:?} and {raw:?} both resolve to {display:?}; {alias_guidance}"
153 )));
154 }
155 identities.push(raw);
156 resolved.push(display);
157 }
158 Ok(resolved)
159 }
160}
161
162fn copy_label(raw: &str) -> Result<String, Error> {
163 let mut output = String::new();
164 reserve_label(&mut output, raw.len())?;
165 output.push_str(raw);
166 Ok(output)
167}
168
169fn reserve_label(output: &mut String, count: usize) -> Result<(), Error> {
170 crate::data::source::reserve_source_string(output, count)
171}
172
173fn humanize(raw: &str) -> Result<String, Error> {
174 let mut split = String::new();
175 reserve_label(
176 &mut split,
177 raw.len()
178 .checked_mul(2)
179 .ok_or_else(|| Error::Render("humanized label length overflow".into()))?,
180 )?;
181 let mut chars = raw.chars().peekable();
182 let mut previous = None;
183 let mut last_was_space = true;
184 while let Some(character) = chars.next() {
185 let next = chars.peek().copied();
186 let prior = previous.replace(character);
187 if matches!(character, '_' | '-' | '.' | ' ' | '\t' | '\n' | '\r') {
188 if !last_was_space {
189 split.push(' ');
190 last_was_space = true;
191 }
192 continue;
193 }
194 if should_split_before(prior, character, next) && !last_was_space {
195 split.push(' ');
196 }
197 split.push(character);
198 last_was_space = false;
199 }
200 let mut output = String::new();
201
202 for (index, word) in split.split_whitespace().enumerate() {
203 let acronym = acronym(word);
204 reserve_label(
205 &mut output,
206 word.len()
207 .checked_add(12)
208 .ok_or_else(|| Error::Render("humanized word length overflow".into()))?,
209 )?;
210 if index != 0 {
211 output.push(' ');
212 }
213 if let Some(acronym) = acronym {
214 output.push_str(acronym);
215 } else if word.len() > 1 && word.bytes().all(|c| c.is_ascii_uppercase()) {
216 output.push_str(word);
217 } else {
218 for (offset, character) in word.chars().enumerate() {
219 let character = character.to_ascii_lowercase();
220 if index == 0 && offset == 0 {
221 output.extend(character.to_uppercase());
222 } else {
223 output.push(character);
224 }
225 }
226 }
227 }
228 if output.is_empty() {
229 copy_label(raw)
230 } else {
231 Ok(output)
232 }
233}
234
235fn should_split_before(previous: Option<char>, current: char, next: Option<char>) -> bool {
236 let Some(previous) = previous else {
237 return false;
238 };
239 (previous.is_ascii_lowercase() && current.is_ascii_uppercase())
240 || (previous.is_ascii_digit() && current.is_ascii_alphabetic())
241 || (previous.is_ascii_alphabetic() && current.is_ascii_digit())
242 || (previous.is_ascii_uppercase()
243 && current.is_ascii_uppercase()
244 && next.is_some_and(|character| character.is_ascii_lowercase()))
245}
246
247fn acronym(word: &str) -> Option<&'static str> {
248 [
249 ("ci", "CI"),
250 ("dna", "DNA"),
251 ("hwe", "HWE"),
252 ("id", "ID"),
253 ("ms", "MS"),
254 ("mz", "m/z"),
255 ("m/z", "m/z"),
256 ("pca", "PCA"),
257 ("qc", "QC"),
258 ("rna", "RNA"),
259 ("tsne", "t-SNE"),
260 ("t-sne", "t-SNE"),
261 ("umap", "UMAP"),
262 ("x", "X"),
263 ("y", "Y"),
264 ("z", "Z"),
265 ]
266 .into_iter()
267 .find_map(|(raw, display)| word.eq_ignore_ascii_case(raw).then_some(display))
268}