coven_foundation/files/relative_path.rs
1//! A path an app names below a folder the person picked, as names, and the
2//! name coven writes for each: one rule, the same on every platform, that
3//! makes a name valid on any volume a copy can land on (§17.3).
4
5use std::fmt;
6use std::path::PathBuf;
7use windows_reserved_names::windows_device;
8
9/// A path below a folder, as the names the app gives, outermost first: an
10/// album's name, then a track's. Each name is one name on every platform,
11/// whatever it holds, `/` and `\` included. Coven writes each through one
12/// rule that makes it valid on any volume (§17.3), so joined to the folder
13/// the path stays inside it.
14#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
15pub struct RelativePath(Vec<String>);
16
17/// Why names can't be a `RelativePath`.
18#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
19pub enum RelativePathError {
20 /// The path has no names, or a name is empty.
21 #[error("the path or one of its names is empty")]
22 Empty,
23}
24
25impl RelativePath {
26 /// The path of `names`, outermost first. Each must be non-empty.
27 pub fn new<S: Into<String>>(
28 names: impl IntoIterator<Item = S>,
29 ) -> Result<Self, RelativePathError> {
30 let names: Vec<String> = names.into_iter().map(Into::into).collect();
31 if names.is_empty() || names.iter().any(String::is_empty) {
32 return Err(RelativePathError::Empty);
33 }
34 Ok(Self(names))
35 }
36
37 /// Its names as the app gave them, outermost first.
38 pub fn names(&self) -> impl Iterator<Item = &str> {
39 self.0.iter().map(String::as_str)
40 }
41
42 /// The path coven writes for it below a folder: each name as the one
43 /// rule for every platform makes it (§17.3), joined by this platform's
44 /// separator. An app writing a file of its own under a name it stores
45 /// writes it here, so its names land as coven's copies do.
46 pub fn local_path(&self) -> PathBuf {
47 self.names().map(local_name).collect()
48 }
49
50 /// The path of its first `count` names.
51 pub(super) fn first(&self, count: usize) -> Self {
52 Self(self.0[..count].to_vec())
53 }
54}
55
56/// The names joined by `/`, for showing only: a name may hold `/` itself.
57impl fmt::Display for RelativePath {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(&self.0.join("/"))
60 }
61}
62
63/// The longest name coven writes: 255 bytes of UTF-8, the limit of ext4,
64/// f2fs and Android's shared storage, which also covers the 255 UTF-16
65/// units of NTFS, exFAT, FAT and APFS, since no character takes more UTF-16
66/// units than UTF-8 bytes. HFS+ counts 255 UTF-16 units of the name
67/// decomposed, where `Ǖ`, two bytes of UTF-8, takes three, so that counts
68/// too.
69pub(super) const NAME_LIMIT: usize = 255;
70
71/// The name coven writes for `name`, the same on every platform, since what
72/// a name may hold is the volume's rule, not the platform's (§17.3):
73///
74/// 1. `" * : < > ? \ | /`, which Windows, Android's shared storage and FAT
75/// volumes refuse, become their full-width lookalikes; control characters
76/// and DEL become their pictures, `␀`–`␟` and `␡`.
77/// 2. A last `.` becomes `.` and a last space `␠`, since Windows and FAT
78/// drop them. So `.` and `..` are ordinary names, `.` and `..`.
79/// 3. A Windows device name, `CON.flac` among them, has its letters in full
80/// width: `CON.flac`.
81/// 4. A name past `NAME_LIMIT` keeps its extension and loses whole
82/// characters, as a person reads them, from the end of the part before
83/// it, with `…` where it was cut.
84///
85/// The result is never empty, `.` or `..`, and holds no separator, so it is
86/// one name inside the folder on every platform.
87pub(super) fn local_name(name: &str) -> String {
88 let mut local: String = name.chars().map(lookalike).collect();
89 if let Some(last) = local.pop() {
90 local.push(match last {
91 '.' => '.',
92 ' ' => '␠',
93 last => last,
94 });
95 }
96 let device = local[..local.find('.').unwrap_or(local.len())].trim_end_matches(' ');
97 if windows_device(device) {
98 let wide: String = device.chars().map(full_width).collect();
99 let end = device.len();
100 local.replace_range(..end, &wide);
101 }
102 fit(local)
103}
104
105/// A character no volume of the four platforms refuses in a name.
106fn lookalike(character: char) -> char {
107 match character {
108 '"' | '*' | ':' | '<' | '>' | '?' | '\\' | '|' | '/' => full_width(character),
109 '\0'..='\x1f' => char::from_u32(0x2400 + u32::from(character))
110 .expect("Control Pictures has a picture for each control character"),
111 '\x7f' => '␡',
112 _ => character,
113 }
114}
115
116/// An ASCII character's full-width form; anything else as it is.
117fn full_width(character: char) -> char {
118 match character {
119 '!'..='~' => char::from_u32(u32::from(character) + 0xFEE0)
120 .expect("Halfwidth and Fullwidth Forms has each printable ASCII character"),
121 _ => character,
122 }
123}
124
125/// `name`, cut to `NAME_LIMIT` if it is longer. The extension, from the
126/// last `.`, stays when at least one character before it fits too;
127/// otherwise the name is cut from its own end. A cut falls between
128/// characters as a person reads them (grapheme clusters), so an accent is
129/// never cut from its letter, except within one such character too long
130/// for a name by itself. The ending `…` is neither dot nor space, so a cut
131/// name stays valid.
132fn fit(name: String) -> String {
133 if fits(&name) {
134 return name;
135 }
136 let (stem, extension) = match name.rfind('.') {
137 Some(dot) if dot > 0 => name.split_at(dot),
138 _ => (name.as_str(), ""),
139 };
140 let graphemes = |text: &str| -> Vec<usize> {
141 icu_segmenter::GraphemeClusterSegmenter::new().segment_str(text).collect()
142 };
143 let characters = |text: &str| -> Vec<usize> {
144 text.char_indices().map(|(index, _)| index).chain([text.len()]).collect()
145 };
146 cut(stem, extension, &graphemes(stem))
147 .or_else(|| cut(&name, "", &graphemes(&name)))
148 .or_else(|| cut(&name, "", &characters(&name)))
149 .expect("one character, `…` and nothing else fit in a name")
150}
151
152/// The longest of `text` up to one of `ends`, then `…` and `extension`,
153/// that fits; none when no end past the start does.
154fn cut(text: &str, extension: &str, ends: &[usize]) -> Option<String> {
155 let room = NAME_LIMIT.checked_sub('…'.len_utf8() + extension.len())?;
156 ends.iter()
157 .rev()
158 .filter(|&&end| end > 0 && end <= room)
159 .map(|&end| format!("{}…{extension}", &text[..end]))
160 .find(|candidate| fits(candidate))
161}
162
163/// Whether `name` is within `NAME_LIMIT` in UTF-8 bytes and, decomposed,
164/// in UTF-16 units.
165fn fits(name: &str) -> bool {
166 name.len() <= NAME_LIMIT
167 && icu_normalizer::DecomposingNormalizerBorrowed::new_nfd()
168 .normalize(name)
169 .encode_utf16()
170 .count()
171 <= NAME_LIMIT
172}
173
174#[cfg(test)]
175#[path = "relative_path_tests.rs"]
176mod tests;