Skip to main content

rpc/
option_labels.rs

1//! The one rule turning entity names into picker labels.
2
3use std::collections::{HashMap, HashSet};
4
5use uuid::Uuid;
6
7const MIN_PREFIX: usize = 4;
8const HEX_LEN: usize = 32;
9const SEPARATOR: &str = ":";
10
11/// Cell-safe text: `|` is the cell separator, line breaks end a cell.
12fn 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
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.
29fn 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
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.
65fn 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
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.
94pub 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;