Skip to main content

fontoxide_misc/
filenames.rs

1//! Port of `fontTools.misc.filenames`: converting a "user name" (something a
2//! user can choose arbitrarily inside a font editor, such as a glyph name) to a
3//! file name that is safe on a wide range of operating systems and file
4//! systems.
5//!
6//! This is the older copy of the algorithm that `fontTools.ttLib` uses (for
7//! example, for the glyph files of `ttx -s`). `fontTools.ufoLib.filenames`
8//! (`fontoxide_ufolib::filenames`) has the same algorithm with different
9//! tables of illegal characters and reserved names.
10
11use std::collections::{BTreeSet, HashSet};
12
13/// The errors of the module.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15pub enum FilenamesError {
16	/// `IndexError`: an empty user name without a prefix.
17	#[error("{0}")]
18	Index(String),
19	/// `ValueError`: the prefix and suffix leave no room for a counter.
20	#[error("{0}")]
21	Value(String),
22	/// `NameTranslationError`: no unique name could be found.
23	#[error("{0}")]
24	NameTranslation(String),
25}
26
27/// The result type of the module.
28pub type Result<T> = std::result::Result<T, FilenamesError>;
29
30/// `illegalCharacters`: `* + / : < > ? [ \ ] |`, U+0001 to U+001F and U+007F.
31///
32/// UPSTREAM-BUG(B66): the list is split from the raw string
33/// `r"\" * + / : < > ? [ \ ] | \0"`, so its first and last items are the
34/// two-character strings `\"` and `\0`, which never match a character: the
35/// double quote and NUL are not replaced.
36pub fn is_illegal_character(c: char) -> bool {
37	matches!(
38		c,
39		'*' | '+' | '/' | ':' | '<' | '>' | '?' | '[' | '\\' | ']' | '|' | '\x01'..='\x1f' | '\x7f'
40	)
41}
42
43/// `reservedFileNames`. (`a:-z:` can never match, since `:` is replaced first.)
44pub const RESERVED_FILE_NAMES: [&str; 13] = [
45	"con", "prn", "aux", "clock$", "nul", "a:-z:", "com1", "lpt1", "lpt2", "lpt3", "com2", "com3",
46	"com4",
47];
48
49/// `maxFileNameLength`.
50pub const MAX_FILE_NAME_LENGTH: i64 = 255;
51
52/// The existing (lowercase) file names, as the `existing` arguments take:
53/// anything that supports `in`.
54pub trait ExistingNames {
55	/// `name in existing`.
56	fn contains_name(&self, name: &str) -> bool;
57}
58
59impl ExistingNames for HashSet<String> {
60	fn contains_name(&self, name: &str) -> bool {
61		self.contains(name)
62	}
63}
64
65impl ExistingNames for BTreeSet<String> {
66	fn contains_name(&self, name: &str) -> bool {
67		self.contains(name)
68	}
69}
70
71impl ExistingNames for [String] {
72	fn contains_name(&self, name: &str) -> bool {
73		self.iter().any(|n| n == name)
74	}
75}
76
77impl ExistingNames for Vec<String> {
78	fn contains_name(&self, name: &str) -> bool {
79		self.iter().any(|n| n == name)
80	}
81}
82
83impl ExistingNames for [&str] {
84	fn contains_name(&self, name: &str) -> bool {
85		self.contains(&name)
86	}
87}
88
89impl<const N: usize> ExistingNames for [&str; N] {
90	fn contains_name(&self, name: &str) -> bool {
91		self.contains(&name)
92	}
93}
94
95/// `str.lower()`.
96fn lower(s: &str) -> String {
97	s.chars().flat_map(char::to_lowercase).collect()
98}
99
100/// `s[:n]` on code points, with Python's negative indices.
101fn slice_to(s: &str, n: i64) -> String {
102	let len = s.chars().count() as i64;
103	let end = if n < 0 { (len + n).max(0) } else { n.min(len) };
104	s.chars().take(end as usize).collect()
105}
106
107/// Converts a user name to a file name, avoiding illegal characters, reserved
108/// file names, ambiguity between upper- and lower-case characters, and clashes
109/// with the (lowercase) `existing` names (`userNameToFileName`).
110///
111/// ```
112/// use fontoxide_misc::filenames::user_name_to_file_name;
113/// let none: [&str; 0] = [];
114/// assert_eq!(user_name_to_file_name("A.alt", &none, "", "").unwrap(), "A_.alt");
115/// assert_eq!(user_name_to_file_name(".notdef", &none, "", "").unwrap(), "_notdef");
116/// assert_eq!(user_name_to_file_name("con.alt", &none, "", "").unwrap(), "_con.alt");
117/// ```
118pub fn user_name_to_file_name<E: ExistingNames + ?Sized>(
119	user_name: &str,
120	existing: &E,
121	prefix: &str,
122	suffix: &str,
123) -> Result<String> {
124	let prefix_length = prefix.chars().count() as i64;
125	let suffix_length = suffix.chars().count() as i64;
126	let mut user_name = user_name.to_owned();
127	// replace an initial period with an _ if no prefix is to be added
128	if prefix.is_empty() {
129		match user_name.chars().next() {
130			// `userName[0]` of an empty name.
131			None => return Err(FilenamesError::Index("string index out of range".into())),
132			Some('.') => user_name = format!("_{}", &user_name[1..]),
133			Some(_) => {}
134		}
135	}
136	// filter the user name
137	let mut filtered = String::with_capacity(user_name.len());
138	for c in user_name.chars() {
139		if is_illegal_character(c) {
140			// replace illegal characters with _
141			filtered.push('_');
142		} else {
143			// add _ to all non-lower characters
144			filtered.push(c);
145			if c.to_lowercase().ne(std::iter::once(c)) {
146				filtered.push('_');
147			}
148		}
149	}
150	// clip to 255
151	let slice_length = MAX_FILE_NAME_LENGTH - prefix_length - suffix_length;
152	let user_name = slice_to(&filtered, slice_length);
153	// test for illegal files names
154	let user_name = user_name
155		.split('.')
156		.map(|part| {
157			if RESERVED_FILE_NAMES.contains(&lower(part).as_str()) {
158				format!("_{part}")
159			} else {
160				part.to_owned()
161			}
162		})
163		.collect::<Vec<_>>()
164		.join(".");
165	// test for clash
166	let full_name = format!("{prefix}{user_name}{suffix}");
167	if existing.contains_name(&lower(&full_name)) {
168		return handle_clash1(&user_name, existing, prefix, suffix);
169	}
170	Ok(full_name)
171}
172
173/// Resolves a clash by appending a 15-digit counter to the user name
174/// (`handleClash1`); `existing` holds lowercase names.
175pub fn handle_clash1<E: ExistingNames + ?Sized>(
176	user_name: &str,
177	existing: &E,
178	prefix: &str,
179	suffix: &str,
180) -> Result<String> {
181	// if the prefix length + user name length + suffix length + 15 is at or
182	// past the maximum length, slice 15 characters off of the user name
183	let prefix_length = prefix.chars().count() as i64;
184	let suffix_length = suffix.chars().count() as i64;
185	let name_length = user_name.chars().count() as i64;
186	let mut user_name = user_name.to_owned();
187	if prefix_length + name_length + suffix_length + 15 > MAX_FILE_NAME_LENGTH {
188		let l = prefix_length + name_length + suffix_length + 15;
189		let slice_length = MAX_FILE_NAME_LENGTH - l;
190		user_name = slice_to(&user_name, slice_length);
191	}
192	// try to add numbers to create a unique name
193	let mut counter: u64 = 1;
194	loop {
195		let full_name = format!("{prefix}{user_name}{counter:015}{suffix}");
196		if !existing.contains_name(&lower(&full_name)) {
197			return Ok(full_name);
198		}
199		counter += 1;
200		if counter >= 999_999_999_999_999 {
201			break;
202		}
203	}
204	// if there is a clash, go to the next fallback
205	handle_clash2(existing, prefix, suffix)
206}
207
208/// The fallback of [`handle_clash1`]: a plain counter between the prefix and
209/// the suffix (`handleClash2`).
210pub fn handle_clash2<E: ExistingNames + ?Sized>(
211	existing: &E,
212	prefix: &str,
213	suffix: &str,
214) -> Result<String> {
215	// calculate the longest possible string
216	let max_length =
217		MAX_FILE_NAME_LENGTH - prefix.chars().count() as i64 - suffix.chars().count() as i64;
218	// `int("9" * maxLength)`
219	if max_length <= 0 {
220		return Err(FilenamesError::Value(
221			"invalid literal for int() with base 10: ''".into(),
222		));
223	}
224	let max_value: Option<u128> = (max_length < 39).then(|| 10u128.pow(max_length as u32) - 1);
225	// try to find a number
226	let mut counter: u128 = 1;
227	loop {
228		let full_name = format!("{prefix}{counter}{suffix}");
229		if !existing.contains_name(&lower(&full_name)) {
230			return Ok(full_name);
231		}
232		counter += 1;
233		if max_value.is_some_and(|m| counter >= m) {
234			break;
235		}
236	}
237	// raise an error if nothing has been found
238	Err(FilenamesError::NameTranslation(
239		"No unique name could be found.".into(),
240	))
241}