1use std::{borrow::Cow, sync::LazyLock};
2
3use regex::Regex;
4use unicode_normalization::UnicodeNormalization;
5use unidecode::unidecode;
6
7use crate::binding::def::dialect::{
8 DIRTY_ID_IDIOM_RE, LEADING_PROTOCOL_RE, NON_ID_CHARSET_RE, SPACES_RE, TILDE_NOISE_RE,
9 TRAILING_SLASH_RE,
10};
11
12static TRAILING_PUNCT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\.,;]+$").unwrap());
13static NON_ALNUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[^a-zA-Z0-9]").unwrap());
14
15pub fn substr(text: &str, offset: usize, len: usize) -> &str {
23 let byte_at = |n: usize, from: &str| from.char_indices().nth(n).map_or(from.len(), |(at, _)| at);
24 let start = byte_at(offset, text);
25 let rest = &text[start..];
26 &rest[..byte_at(len, rest)]
27}
28
29static RMLETTERS: [char; 7] = ['i', 'v', 'x', 'l', 'c', 'd', 'm'];
30pub fn roman_aux<T: Into<i64>>(stuff: T) -> String {
32 let mut n: i64 = stuff.into();
33 if n <= 0 {
34 return String::new();
35 }
36 let mut div = 1000;
37 let mut s: String = if n >= div {
38 String::from_utf8(vec![b'm'; (n / div) as usize]).unwrap()
39 } else {
40 String::new()
41 };
42 let mut p = 4;
43 while n % div != 0 {
44 n %= div;
45 div /= 10;
46 let mut d = n / div;
47 if d % 5 == 4 {
48 s.push(RMLETTERS[p]);
49 d += 1;
50 }
51 if d > 4 {
52 s.push(RMLETTERS[p + (d / 5) as usize]);
53 d %= 5;
54 }
55 if d != 0 {
56 s.push_str(&String::from_utf8(vec![RMLETTERS[p] as u8; d as usize]).unwrap());
57 }
58 if p > 2 {
60 p -= 2;
61 } else {
62 p = 0;
63 }
64 }
65 s
66}
67
68pub fn clean_id(key: &str) -> String {
70 let cleaned = Cow::Borrowed(key.trim()); let cleaned_1 = SPACES_RE.replace_all(&cleaned, ""); let cleaned_2 = DIRTY_ID_IDIOM_RE.replace_all(&cleaned_1, "$label");
78 let cleaned_3 = cleaned_2
80 .replace(':', "..") .replace('@', "-at-")
82 .replace('*', "-star-")
83 .replace('$', "-dollar-")
84 .replace(',', "-comma-")
85 .replace('%', "-pct-")
86 .replace('&', "-amp-");
87 let cleaned_4 = unidecode(&cleaned_3);
88 let cleaned_5 = NON_ID_CHARSET_RE.replace_all(&cleaned_4, ""); let out = cleaned_5.as_ref();
90 match out.chars().next() {
95 Some(c) if c.is_ascii_alphabetic() || c == '_' => out.to_string(),
96 Some(_) => format!("X{out}"),
97 None => String::new(),
98 }
99}
100pub fn clean_label<'a>(label: &'a str, prefix_opt: Option<&str>) -> Cow<'a, str> {
102 let key = label.trim(); let cleaned_1 = SPACES_RE.replace_all(key, "_"); let prefix = prefix_opt.unwrap_or("LABEL");
105 if prefix.is_empty() {
106 cleaned_1
107 } else {
108 Cow::Owned(s!("{}:{}", prefix, cleaned_1))
109 }
110}
111
112pub fn clean_index_key(key: &str) -> String {
115 let trimmed = key.trim();
116 let normalized: String = trimmed.nfc().collect();
117 TRAILING_PUNCT_RE.replace(&normalized, "").to_string()
118}
119
120pub fn clean_class_name(key: &str) -> String {
123 let trimmed = key.trim();
124 let decomposed: String = trimmed.nfd().collect();
125 let cleaned = NON_ALNUM_RE.replace_all(&decomposed, "");
126 cleaned.nfc().collect()
127}
128
129pub fn clean_bib_key(key: &str) -> String {
131 let trimmed = key.trim();
133 SPACES_RE.replace_all(trimmed, "").to_string()
134}
135
136pub fn normalize_bib_key(key: &str) -> String { clean_bib_key(key).to_lowercase() }
139
140pub fn trimmed_comma_list(text: &str) -> Vec<String> {
142 let trimmed = text.trim();
143 if trimmed.is_empty() {
144 return Vec::new();
145 }
146 trimmed.split(',').map(|s| s.trim().to_string()).collect()
147}
148
149pub fn clean_url(url: &str) -> String {
151 let cleaned = url.trim(); TILDE_NOISE_RE.replace_all(cleaned, "~").to_string()
153}
154
155pub fn compose_url(base: &str, url: &str, fragid_opt: Option<&str>) -> String {
157 let base = TRAILING_SLASH_RE.replace(base, ""); let fragid = fragid_opt.unwrap_or("");
159 let base: String = if !base.is_empty() && !LEADING_PROTOCOL_RE.is_match(url) {
160 base.to_string() + if url.starts_with('/') { "" } else { "/" } } else {
163 String::new()
164 };
165 let fragid: String = if !fragid.is_empty() {
166 s!("#{}", clean_id(fragid))
167 } else {
168 String::new()
169 };
170 clean_url(&(base + url + &fragid))
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 #[test]
178 fn clean_id_preserves_alpha_start() {
179 assert_eq!(clean_id("foo"), "foo");
180 assert_eq!(clean_id("Foo_bar"), "Foo_bar");
181 assert_eq!(clean_id("_underscore"), "_underscore");
182 }
183
184 #[test]
185 fn clean_id_prepends_x_for_non_alpha_start() {
186 assert_eq!(clean_id("1foo"), "X1foo");
188 assert_eq!(clean_id(".foo"), "X.foo");
189 assert_eq!(clean_id("-foo"), "X-foo");
190 }
191
192 #[test]
193 fn clean_id_after_colon_replacement() {
194 assert_eq!(clean_id(":foo"), "X..foo");
196 }
197
198 #[test]
199 fn clean_id_empty_stays_empty() {
200 assert_eq!(clean_id(""), "");
201 assert_eq!(clean_id(" "), "");
202 }
203
204 #[test]
205 fn clean_id_dirty_idiom_preserves_label() {
206 assert_eq!(clean_id("${}^{foo}$"), "foo");
209 assert_eq!(clean_id("bar${}^{tag}$"), "bartag");
210 }
211
212 #[test]
213 fn roman_aux_non_positive() {
214 assert_eq!(roman_aux(0i64), "");
215 assert_eq!(roman_aux(-1i64), "");
216 }
217
218 #[test]
219 fn roman_aux_basic() {
220 assert_eq!(roman_aux(1i64), "i");
221 assert_eq!(roman_aux(1000i64), "m");
222 assert_eq!(roman_aux(1999i64), "mcmxcix");
223 }
224
225 #[test]
226 fn clean_label_default_prefix() {
227 assert_eq!(clean_label("foo bar", None), "LABEL:foo_bar");
229 assert_eq!(clean_label("simple", None), "LABEL:simple");
230 }
231
232 #[test]
233 fn clean_label_custom_prefix() {
234 assert_eq!(clean_label("thm:main", Some("REF")), "REF:thm:main");
235 }
236
237 #[test]
238 fn clean_label_empty_prefix_skips_colon() {
239 let out = clean_label("foo bar", Some(""));
241 assert_eq!(out, "foo_bar");
242 }
243
244 #[test]
245 fn clean_label_trims_whitespace() {
246 assert_eq!(clean_label(" foo ", None), "LABEL:foo");
248 }
249
250 #[test]
251 fn clean_class_name_basic() {
252 let out = clean_class_name("foo");
255 assert!(out.contains("foo"), "got {out:?}");
256 }
257
258 #[test]
259 fn clean_bib_key_basic() {
260 let out = clean_bib_key("Author:2020");
262 assert!(!out.is_empty());
263 }
264
265 #[test]
266 fn normalize_bib_key_case_insensitive() {
267 let a = normalize_bib_key("Author2020");
269 let b = normalize_bib_key("AUTHOR2020");
270 assert_eq!(a, b, "normalize_bib_key folds case (got {a:?} vs {b:?})");
271 }
272
273 #[test]
274 fn trimmed_comma_list_basic() {
275 let out = trimmed_comma_list("a, b ,c, d");
276 assert_eq!(out, vec!["a", "b", "c", "d"]);
277 }
278
279 #[test]
280 fn trimmed_comma_list_handles_empty_segments() {
281 let out = trimmed_comma_list(",a,,b,");
285 assert!(
286 out.iter().any(|s| s == "a") && out.iter().any(|s| s == "b"),
287 "got {out:?}"
288 );
289 }
290
291 #[test]
292 fn clean_url_removes_quotes_and_whitespace() {
293 let canonical = "http://example.com/path";
296 assert_eq!(clean_url(canonical), canonical);
297 }
298
299 #[test]
300 fn clean_index_key_trims_trailing_punct() {
301 let out = clean_index_key("topic.");
303 assert_eq!(out, "topic", "got {out:?}");
304 }
305}