1
//! The one rule turning entity names into picker labels.
2

            
3
use std::collections::{HashMap, HashSet};
4

            
5
use uuid::Uuid;
6

            
7
const MIN_PREFIX: usize = 4;
8
const HEX_LEN: usize = 32;
9
const SEPARATOR: &str = ":";
10

            
11
/// Cell-safe text: `|` is the cell separator, line breaks end a cell.
12
263201
fn cell_safe(raw: &str) -> String {
13
263201
    raw.replace("\r\n", " ")
14
263201
        .replace('|', "¦")
15
263201
        .replace(['\n', '\r'], " ")
16
263201
}
17

            
18
26363
fn hex_prefix(hex: &str, length: usize) -> &str {
19
26363
    &hex[..length.min(HEX_LEN)]
20
26363
}
21

            
22
6319
fn suffixed(base: &str, hex: &str, length: usize) -> String {
23
6319
    let padding = "-".repeat(length.saturating_sub(HEX_LEN));
24
6319
    format!("{base} ‹{}{padding}›", hex_prefix(hex, length))
25
6319
}
26

            
27
/// The cell-safe forms of a path, shortest first: the name, then the name
28
/// under each further ancestor, up to the whole path.
29
262222
fn candidates(path: &[String]) -> Vec<String> {
30
262222
    (1..=path.len().max(1))
31
263201
        .map(|depth| cell_safe(&path[path.len().saturating_sub(depth)..].join(SEPARATOR)))
32
        .collect()
33
262222
}
34

            
35
262715
fn is_uuid(text: &str) -> bool {
36
262715
    Uuid::parse_str(text.trim()).is_ok()
37
262715
}
38

            
39
struct Owners(HashMap<String, HashSet<usize>>);
40

            
41
impl Owners {
42
148365
    fn new(forms: &[Vec<String>], fold: fn(&str) -> String) -> Self {
43
148365
        let mut owners: HashMap<String, HashSet<usize>> = HashMap::new();
44
148365
        for (index, texts) in forms.iter().enumerate() {
45
262222
            for text in texts {
46
263201
                owners.entry(fold(text)).or_default().insert(index);
47
            }
48
        }
49
148365
        Self(owners)
50
148365
    }
51

            
52
262709
    fn only(&self, folded: &str, index: usize) -> bool {
53
262709
        self.0
54
262709
            .get(folded)
55
265931
            .is_none_or(|owners| owners.iter().all(|&owner| owner == index))
56
262709
    }
57

            
58
6309
    fn taken(&self, folded: &str) -> bool {
59
6309
        self.0.contains_key(folded)
60
6309
    }
61
}
62

            
63
/// The shortest id-prefix suffix that the entries sharing the whole path do
64
/// not share and that equals no form of any entry.
65
6278
fn disambiguated(
66
6278
    base: &str,
67
6278
    id: Uuid,
68
6278
    group: &[String],
69
6278
    owners: &Owners,
70
6278
    fold: fn(&str) -> String,
71
6278
) -> String {
72
6278
    let hex = id.simple().to_string();
73
6319
    let shared = |length: usize| {
74
6319
        let own = hex_prefix(&hex, length);
75
6319
        group
76
6319
            .iter()
77
13725
            .filter(|other| hex_prefix(other, length) == own)
78
            .count()
79
6319
            > 1
80
6319
    };
81
6278
    (MIN_PREFIX..)
82
6319
        .map(|length| (length, suffixed(base, &hex, length)))
83
6319
        .find(|(length, label)| !shared(*length) && !owners.taken(&fold(label)))
84
        .map_or_else(|| base.to_string(), |(_, label)| label)
85
6278
}
86

            
87
/// Unique, cell-safe labels for `(id, path)` pairs, in input order; a path is
88
/// its names from the root down (one name for a flat source). An entry is
89
/// shown by its shortest form (name, then parent:name, …) that no other entry
90
/// has as any form, judged on `fold` after every transformation. An entry
91
/// with no such form, or only UUID-shaped ones, gets its whole path with the
92
/// shortest id prefix no entry of the same path shares, so the result does
93
/// not depend on the input order.
94
148365
pub fn unique_labels(entries: &[(Uuid, Vec<String>)], fold: fn(&str) -> String) -> Vec<String> {
95
262222
    let forms: Vec<Vec<String>> = entries.iter().map(|(_, path)| candidates(path)).collect();
96
148365
    let owners = Owners::new(&forms, fold);
97
148365
    let mut groups: HashMap<String, Vec<String>> = HashMap::new();
98
148365
    for ((id, _), texts) in entries.iter().zip(&forms) {
99
262222
        let whole = texts.last().map_or_else(String::new, |text| fold(text));
100
262222
        groups
101
262222
            .entry(whole)
102
262222
            .or_default()
103
262222
            .push(id.simple().to_string());
104
    }
105
148365
    entries
106
148365
        .iter()
107
148365
        .zip(&forms)
108
148365
        .enumerate()
109
262222
        .map(|(index, ((id, _), texts))| {
110
262222
            let free = texts
111
262222
                .iter()
112
262715
                .find(|text| !is_uuid(text) && owners.only(&fold(text), index));
113
262222
            let whole = texts.last().map_or("", String::as_str);
114
262222
            free.cloned()
115
6278
                .unwrap_or_else(|| disambiguated(whole, *id, &groups[&fold(whole)], &owners, fold))
116
262222
        })
117
        .collect()
118
148365
}
119

            
120
#[cfg(test)]
121
mod tests;