1use std::collections::{HashMap, HashSet};
4
5use uuid::Uuid;
6
7const MIN_PREFIX: usize = 4;
8const HEX_LEN: usize = 32;
9const SEPARATOR: &str = ":";
10
11fn cell_safe(raw: &str) -> String {
13 raw.replace("\r\n", " ")
14 .replace('|', "¦")
15 .replace(['\n', '\r'], " ")
16}
17
18fn hex_prefix(hex: &str, length: usize) -> &str {
19 &hex[..length.min(HEX_LEN)]
20}
21
22fn suffixed(base: &str, hex: &str, length: usize) -> String {
23 let padding = "-".repeat(length.saturating_sub(HEX_LEN));
24 format!("{base} ‹{}{padding}›", hex_prefix(hex, length))
25}
26
27fn candidates(path: &[String]) -> Vec<String> {
30 (1..=path.len().max(1))
31 .map(|depth| cell_safe(&path[path.len().saturating_sub(depth)..].join(SEPARATOR)))
32 .collect()
33}
34
35fn is_uuid(text: &str) -> bool {
36 Uuid::parse_str(text.trim()).is_ok()
37}
38
39struct Owners(HashMap<String, HashSet<usize>>);
40
41impl Owners {
42 fn new(forms: &[Vec<String>], fold: fn(&str) -> String) -> Self {
43 let mut owners: HashMap<String, HashSet<usize>> = HashMap::new();
44 for (index, texts) in forms.iter().enumerate() {
45 for text in texts {
46 owners.entry(fold(text)).or_default().insert(index);
47 }
48 }
49 Self(owners)
50 }
51
52 fn only(&self, folded: &str, index: usize) -> bool {
53 self.0
54 .get(folded)
55 .is_none_or(|owners| owners.iter().all(|&owner| owner == index))
56 }
57
58 fn taken(&self, folded: &str) -> bool {
59 self.0.contains_key(folded)
60 }
61}
62
63fn disambiguated(
66 base: &str,
67 id: Uuid,
68 group: &[String],
69 owners: &Owners,
70 fold: fn(&str) -> String,
71) -> String {
72 let hex = id.simple().to_string();
73 let shared = |length: usize| {
74 let own = hex_prefix(&hex, length);
75 group
76 .iter()
77 .filter(|other| hex_prefix(other, length) == own)
78 .count()
79 > 1
80 };
81 (MIN_PREFIX..)
82 .map(|length| (length, suffixed(base, &hex, length)))
83 .find(|(length, label)| !shared(*length) && !owners.taken(&fold(label)))
84 .map_or_else(|| base.to_string(), |(_, label)| label)
85}
86
87pub fn unique_labels(entries: &[(Uuid, Vec<String>)], fold: fn(&str) -> String) -> Vec<String> {
95 let forms: Vec<Vec<String>> = entries.iter().map(|(_, path)| candidates(path)).collect();
96 let owners = Owners::new(&forms, fold);
97 let mut groups: HashMap<String, Vec<String>> = HashMap::new();
98 for ((id, _), texts) in entries.iter().zip(&forms) {
99 let whole = texts.last().map_or_else(String::new, |text| fold(text));
100 groups
101 .entry(whole)
102 .or_default()
103 .push(id.simple().to_string());
104 }
105 entries
106 .iter()
107 .zip(&forms)
108 .enumerate()
109 .map(|(index, ((id, _), texts))| {
110 let free = texts
111 .iter()
112 .find(|text| !is_uuid(text) && owners.only(&fold(text), index));
113 let whole = texts.last().map_or("", String::as_str);
114 free.cloned()
115 .unwrap_or_else(|| disambiguated(whole, *id, &groups[&fold(whole)], &owners, fold))
116 })
117 .collect()
118}
119
120#[cfg(test)]
121mod tests;