disk-core 0.2.1

Shared base for the rusty-backup filesystem, partition-table and disk-image crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Make a filename legal on a destination filesystem, whatever its rules.
//!
//! Every editable driver already states its naming rules through
//! [`Filesystem::validate_name`](crate::filesystem::Filesystem::validate_name)
//! (length, charset, encoding, reserved names, 8.3 shape, ...). Rather than
//! restate those rules in a second table that would drift, [`legalize_name`]
//! treats `validate_name` as an oracle and searches for the smallest repair it
//! accepts:
//!
//! 1. Per-character: each character is probed alone (`A<c>A`). One the
//!    destination refuses is replaced by its uppercase form, then an ASCII
//!    transliteration (`e` for `é`, `TM` for `™`), then `_`, `-` or `.`,
//!    and is dropped only when none of those are accepted.
//! 2. Structural: trailing spaces / dots are trimmed, extra dots collapsed,
//!    reserved names (`CON`, `..`) suffixed, a leading letter added for
//!    filesystems that need one (ProDOS, Atari DOS).
//! 3. Length: the stem is shortened first so the extension survives, then the
//!    extension, then the whole name.
//!
//! [`unique_name`] then appends `_1`, `_2`, ... (shortening the stem to make
//! room) when the legal name is already taken in the same folder.
//!
//! The small validators at the bottom ([`validate_posix_name`],
//! [`validate_amiga_name`], [`is_dos_device_name`]) are shared by drivers that
//! had no name check of their own.

use std::collections::HashMap;

use crate::filesystem::FilesystemError;

/// A name check: `Ok` when the destination accepts the name as-is.
pub type NameValidator<'a> = dyn Fn(&str) -> Result<(), FilesystemError> + 'a;

/// Return `name` unchanged when `validate` accepts it, else the closest legal
/// name; `Err` (the destination's own reason) when no repair is accepted.
pub fn legalize_name(validate: &NameValidator<'_>, name: &str) -> Result<String, FilesystemError> {
    let original_err = match validate(name) {
        Ok(()) => return Ok(name.to_string()),
        Err(e) => e,
    };
    let mut probe = CharProbe::new(validate);
    let mapped = probe.map_chars(name);
    let candidates = structural_candidates(&mapped, &mut probe);
    if let Some(ok) = candidates.iter().find(|c| validate(c).is_ok()) {
        return Ok(ok.clone());
    }
    candidates
        .iter()
        .find_map(|c| shorten_to_fit(validate, c))
        .ok_or(original_err)
}

/// `name` if it is free, else `stem_N.ext` for the first free legal N.
pub fn unique_name(
    validate: &NameValidator<'_>,
    name: &str,
    is_taken: &dyn Fn(&str) -> bool,
) -> Option<String> {
    if !is_taken(name) {
        return Some(name.to_string());
    }
    let (stem, ext) = split_ext(name);
    let stem: Vec<char> = stem.chars().collect();
    for n in 1..10_000u32 {
        let suffix = format!("_{n}");
        for keep in (0..=stem.len()).rev() {
            let head: String = stem[..keep].iter().collect();
            let candidate = format!("{head}{suffix}{ext}");
            if validate(&candidate).is_ok() {
                if !is_taken(&candidate) {
                    return Some(candidate);
                }
                break;
            }
        }
    }
    None
}

/// Per-character acceptance, memoised: a long copy probes the same few characters.
struct CharProbe<'a, 'b> {
    validate: &'a NameValidator<'b>,
    cache: HashMap<String, bool>,
}

impl<'a, 'b> CharProbe<'a, 'b> {
    fn new(validate: &'a NameValidator<'b>) -> Self {
        Self {
            validate,
            cache: HashMap::new(),
        }
    }

    fn accepts(&mut self, piece: &str) -> bool {
        if let Some(&ok) = self.cache.get(piece) {
            return ok;
        }
        // Surrounding letters keep leading-letter and empty-name rules out of the probe.
        let ok = (self.validate)(&format!("A{piece}A")).is_ok()
            || (self.validate)(&format!("A{piece}")).is_ok();
        self.cache.insert(piece.to_string(), ok);
        ok
    }

    /// The first replacement the destination accepts, or "" to drop the char.
    fn replacement(&mut self) -> String {
        for r in ["_", "-", "."] {
            if self.accepts(r) {
                return r.to_string();
            }
        }
        String::new()
    }

    fn map_chars(&mut self, name: &str) -> String {
        let mut out = String::with_capacity(name.len());
        for c in name.chars() {
            let s = c.to_string();
            if self.accepts(&s) {
                out.push(c);
                continue;
            }
            let upper: String = c.to_uppercase().collect();
            if upper != s && self.accepts(&upper) {
                out.push_str(&upper);
                continue;
            }
            if let Some(ascii) = ascii_fold(c) {
                let folded: String = ascii
                    .chars()
                    .map(|a| {
                        if self.accepts(&a.to_string()) {
                            a.to_string()
                        } else if self.accepts(&a.to_ascii_uppercase().to_string()) {
                            a.to_ascii_uppercase().to_string()
                        } else {
                            String::new()
                        }
                    })
                    .collect();
                if !folded.is_empty() {
                    out.push_str(&folded);
                    continue;
                }
            }
            out.push_str(&self.replacement());
        }
        out
    }
}

/// Whole-name repairs to try in order, each on top of the character mapping.
fn structural_candidates(mapped: &str, probe: &mut CharProbe<'_, '_>) -> Vec<String> {
    let mut out = vec![mapped.to_string()];
    let trimmed = mapped
        .trim_start_matches(' ')
        .trim_end_matches([' ', '.'])
        .to_string();
    let base = if trimmed.is_empty() {
        let r = probe.replacement();
        if r.is_empty() {
            "X".to_string()
        } else {
            r
        }
    } else {
        trimmed
    };
    out.push(base.clone());
    // Filesystems that split on the first '.' refuse a second one (Atari DOS, RS-DOS).
    if let Some(last) = base.rfind('.') {
        let (head, tail) = base.split_at(last);
        if head.contains('.') {
            let r = probe.replacement();
            let r = if r == "." { String::new() } else { r };
            out.push(format!("{}{tail}", head.replace('.', &r)));
        }
        out.push(format!("{}{tail}", head.replace('.', "")));
    }
    // Reserved names (CON, NUL, '..') and names that must start with a letter.
    let with_suffix: Vec<String> = out.iter().map(|c| format!("{c}_")).collect();
    let with_prefix: Vec<String> = out.iter().map(|c| format!("X{c}")).collect();
    out.extend(with_suffix);
    out.extend(with_prefix);
    out.dedup();
    out
}

/// Shorten `name` until `validate` accepts it: stem first, then extension, then the whole.
fn shorten_to_fit(validate: &NameValidator<'_>, name: &str) -> Option<String> {
    let (stem, ext) = split_ext(name);
    let stem: Vec<char> = stem.chars().collect();
    let ext: Vec<char> = ext.chars().collect();
    // Full extension first; then shorter extensions (".html" on an 8.3 volume).
    for ext_keep in (2..=ext.len()).rev() {
        let tail: String = ext[..ext_keep].iter().collect();
        for keep in (1..=stem.len()).rev() {
            let head: String = stem[..keep].iter().collect();
            let candidate = format!("{}{tail}", head.trim_end_matches([' ', '.']));
            if validate(&candidate).is_ok() {
                return Some(candidate);
            }
        }
    }
    let all: Vec<char> = name.chars().collect();
    for keep in (1..all.len()).rev() {
        let candidate: String = all[..keep].iter().collect();
        let candidate = candidate.trim_end_matches([' ', '.']).to_string();
        if !candidate.is_empty() && validate(&candidate).is_ok() {
            return Some(candidate);
        }
    }
    None
}

/// Split at the last '.', keeping the dot with the extension; a leading dot is not an extension.
fn split_ext(name: &str) -> (&str, &str) {
    match name.rfind('.') {
        Some(i) if i > 0 && name.len() - i <= 6 => name.split_at(i),
        _ => (name, ""),
    }
}

/// Closest plain-ASCII spelling for the non-ASCII characters vintage names carry.
pub fn ascii_fold(c: char) -> Option<&'static str> {
    Some(match c {
        'À' | 'Á' | 'Â' | 'Ã' | 'Ä' | 'Å' => "A",
        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ª' => "a",
        'Ç' => "C",
        'ç' | '¢' => "c",
        'È' | 'É' | 'Ê' | 'Ë' => "E",
        'è' | 'é' | 'ê' | 'ë' => "e",
        'Ì' | 'Í' | 'Î' | 'Ï' => "I",
        'ì' | 'í' | 'î' | 'ï' | 'ı' => "i",
        'Ñ' => "N",
        'ñ' => "n",
        'Ò' | 'Ó' | 'Ô' | 'Õ' | 'Ö' | 'Ø' => "O",
        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'º' => "o",
        'Ù' | 'Ú' | 'Û' | 'Ü' => "U",
        'ù' | 'ú' | 'û' | 'ü' | 'µ' => "u",
        'Ÿ' => "Y",
        'ÿ' | '¥' => "y",
        'ß' => "ss",
        'Æ' => "AE",
        'æ' => "ae",
        'Œ' => "OE",
        'œ' => "oe",
        'ƒ' => "f",
        'fi' => "fi",
        'fl' => "fl",
        'π' => "pi",
        'Ω' => "Omega",
        '™' => "TM",
        '©' => "(c)",
        '®' => "(R)",
        '£' => "L",
        '€' => "EUR",
        '§' => "S",
        '' => "P",
        '°' | '˚' => "o",
        '±' => "+-",
        '≠' => "!=",
        '≤' => "<=",
        '≥' => ">=",
        '≈' | '˜' => "~",
        '÷' | '⁄' => "-",
        '•' | '·' | '–' | '—' | '†' | '‡' => "-",
        '…' => "...",
        '“' | '”' | '„' | '«' | '»' => "\"",
        '‘' | '’' | '‚' | '‹' | '›' | '´' | '`' => "'",
        '\u{A0}' => " ",
        '\u{F8FF}' => "Apple",
        '∞' => "inf",
        '√' => "v",
        '¬' => "-",
        '¿' => "?",
        '¡' => "!",
        _ => return None,
    })
}

/// DOS / Windows device names, refused as a base name on FAT-family volumes.
pub fn is_dos_device_name(name: &str) -> bool {
    let base = name.split('.').next().unwrap_or("").trim_end();
    let upper = base.to_ascii_uppercase();
    matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$")
        || (upper.len() == 4
            && (upper.starts_with("COM") || upper.starts_with("LPT"))
            && matches!(upper.as_bytes()[3], b'1'..=b'9'))
}

/// Host folder names: the portable set everywhere, plus Win32's extra rules on Windows.
pub fn validate_host_name(name: &str) -> Result<(), FilesystemError> {
    validate_host_name_for(name, cfg!(windows))
}

fn validate_host_name_for(name: &str, windows: bool) -> Result<(), FilesystemError> {
    validate_posix_name(name, 255, "the host")?;
    if let Some(c) = name.chars().find(|c| r#"<>:"\|?*"#.contains(*c)) {
        return Err(FilesystemError::InvalidData(format!(
            "'{c}' is not allowed in a host filename"
        )));
    }
    if windows {
        // `Icon\r` is a real Finder file on macOS, so control codes only fail on Windows.
        if name.chars().any(|c| (c as u32) < 0x20) {
            return Err(FilesystemError::InvalidData(
                "Windows filenames cannot hold control characters".into(),
            ));
        }
        if name.ends_with([' ', '.']) || is_dos_device_name(name) {
            return Err(FilesystemError::InvalidData(format!(
                "'{name}' is not a usable Windows filename"
            )));
        }
    }
    Ok(())
}

/// Unix-style names: 1..=`max_bytes` UTF-8 bytes, no `/` or NUL, not `.` / `..`.
pub fn validate_posix_name(name: &str, max_bytes: usize, fs: &str) -> Result<(), FilesystemError> {
    if name.is_empty() {
        return Err(FilesystemError::InvalidData("name cannot be empty".into()));
    }
    if name == "." || name == ".." {
        return Err(FilesystemError::InvalidData(format!(
            "'.' and '..' are reserved on {fs}"
        )));
    }
    if name.contains('/') || name.contains('\0') {
        return Err(FilesystemError::InvalidData(format!(
            "{fs} names cannot contain '/' or NUL"
        )));
    }
    if name.len() > max_bytes {
        return Err(FilesystemError::InvalidData(format!(
            "name is too long ({} bytes); {fs} allows up to {max_bytes}",
            name.len()
        )));
    }
    Ok(())
}

/// Amiga-style names: 1..=`max_bytes` bytes, no `/`, `:` or NUL (the AmigaDOS path syntax).
pub fn validate_amiga_name(name: &str, max_bytes: usize, fs: &str) -> Result<(), FilesystemError> {
    if name.is_empty() {
        return Err(FilesystemError::InvalidData("name cannot be empty".into()));
    }
    if name.contains(['/', ':', '\0']) {
        return Err(FilesystemError::InvalidData(format!(
            "{fs} names cannot contain '/', ':' or NUL"
        )));
    }
    if name.len() > max_bytes {
        return Err(FilesystemError::InvalidData(format!(
            "name is too long ({} bytes); {fs} allows up to {max_bytes}",
            name.len()
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn legal(v: &NameValidator<'_>, name: &str) -> String {
        let out = legalize_name(v, name).unwrap();
        assert!(v(&out).is_ok(), "{name:?} -> {out:?} still invalid");
        out
    }

    #[test]
    fn a_legal_name_is_untouched() {
        let v = |n: &str| validate_posix_name(n, 255, "ext");
        assert_eq!(legal(&v, "plain.txt"), "plain.txt");
        assert_eq!(legal(&v, "Icon\r"), "Icon\r");
    }

    #[test]
    fn slash_and_colon_become_underscores() {
        let v = |n: &str| validate_amiga_name(n, 30, "SFS");
        assert_eq!(legal(&v, "Schwarz/Weiss"), "Schwarz_Weiss");
        assert_eq!(legal(&v, "a:b"), "a_b");
    }

    #[test]
    fn long_names_keep_their_extension() {
        let v = |n: &str| validate_amiga_name(n, 12, "SFS");
        assert_eq!(legal(&v, "Anti-Aliased PICT.rsrc"), "Anti-Al.rsrc");
    }

    #[test]
    fn dos_device_names_are_detected() {
        assert!(is_dos_device_name("con"));
        assert!(is_dos_device_name("LPT1.txt"));
        assert!(!is_dos_device_name("CONFIG.SYS"));
        assert!(!is_dos_device_name("COM0"));
    }

    #[test]
    fn unique_name_suffixes_before_the_extension() {
        let v = |n: &str| validate_posix_name(n, 255, "ext");
        let taken = |n: &str| n == "a_b.txt" || n == "a_b_1.txt";
        assert_eq!(unique_name(&v, "a_b.txt", &taken).unwrap(), "a_b_2.txt");
        let short = |n: &str| validate_posix_name(n, 8, "ext");
        let taken = |n: &str| n == "abcdefgh";
        assert_eq!(unique_name(&short, "abcdefgh", &taken).unwrap(), "abcdef_1");
    }

    #[test]
    fn nothing_legal_reports_the_destination_reason() {
        let v = |_: &str| Err(FilesystemError::InvalidData("read-only".into()));
        assert!(legalize_name(&v, "x").is_err());
    }

    #[test]
    fn host_rules_are_stricter_on_windows() {
        assert!(validate_host_name_for("Icon\r", false).is_ok());
        assert!(validate_host_name_for("Icon\r", true).is_err());
        assert!(validate_host_name_for("Read Me.", true).is_err());
        assert!(validate_host_name_for("aux.c", true).is_err());
        assert!(validate_host_name_for("a:b", false).is_err());
    }
}