pub use crate::exfat::ondisk::MAX_NAME_UNITS;
use crate::exfat::ondisk::{NAME_UNITS_PER_ENTRY, UpcaseTable, name_hash};
use crate::path::is_reserved_name_char;
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NameError {
#[error("the name is not valid UTF-8, so it has no UTF-16 form a name entry holds")]
NotUtf8,
#[error("the name is empty")]
Empty,
#[error("a name of {units} UTF-16 code units exceeds the {limit} the format holds")]
#[non_exhaustive]
TooLong {
units: usize,
limit: usize,
},
#[error("{ch:?} is not a character an exFAT name may contain")]
#[non_exhaustive]
ForbiddenCharacter {
ch: char,
},
#[error("a name ending in a dot or a space is not one a driver reads back unchanged")]
TrailingDotOrSpace,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct PlacedName {
pub units: Vec<u16>,
pub hash: u16,
}
impl PlacedName {
pub(crate) fn slots(&self) -> u32 {
2 + self.units.len().div_ceil(NAME_UNITS_PER_ENTRY) as u32
}
pub(crate) fn secondary_count(&self) -> u8 {
(self.slots() - 1) as u8
}
}
pub(crate) fn place(
name: &[u8],
upcase: &UpcaseTable,
) -> Result<(PlacedName, Vec<u16>), NameError> {
let text = core::str::from_utf8(name).map_err(|_| NameError::NotUtf8)?;
if text.is_empty() {
return Err(NameError::Empty);
}
for ch in text.chars() {
if is_reserved_name_char(ch) {
return Err(NameError::ForbiddenCharacter { ch });
}
}
if text.ends_with('.') || text.ends_with(' ') {
return Err(NameError::TrailingDotOrSpace);
}
let units: Vec<u16> = text.encode_utf16().collect();
if units.len() > MAX_NAME_UNITS {
return Err(NameError::TooLong {
units: units.len(),
limit: MAX_NAME_UNITS,
});
}
let folded = upcase.fold(&units);
let hash = name_hash(&folded);
Ok((PlacedName { units, hash }, folded))
}
#[cfg(test)]
mod tests {
use super::*;
fn placed(name: &str) -> Result<(PlacedName, Vec<u16>), NameError> {
place(name.as_bytes(), &UpcaseTable::recommended())
}
#[test]
fn a_name_is_stored_as_the_units_it_was_given() {
let (name, _) = placed("A Long Name.txt").expect("a name the format holds");
assert_eq!(
name.units,
"A Long Name.txt".encode_utf16().collect::<Vec<_>>()
);
let (unicode, _) = placed("Ünïcode — 名前").expect("a name the format holds");
assert_eq!(
String::from_utf16(&unicode.units).expect("well-formed"),
"Ünïcode — 名前"
);
}
#[test]
fn a_set_is_the_two_leading_entries_and_one_per_fifteen_units() {
for (units, slots, secondary) in [
(1, 3, 2),
(15, 3, 2),
(16, 4, 3),
(30, 4, 3),
(31, 5, 4),
(255, 19, 18),
] {
let (name, _) = placed(&"a".repeat(units)).expect("a name the format holds");
assert_eq!(name.slots(), slots, "{units} units");
assert_eq!(name.secondary_count(), secondary, "{units} units");
}
}
#[test]
fn the_hash_is_taken_over_the_folded_name_so_two_spellings_hash_alike() {
let (upper, _) = placed("README.TXT").expect("a name");
let (lower, _) = placed("readme.txt").expect("a name");
let (mixed, _) = placed("ReadMe.Txt").expect("a name");
assert_eq!(upper.hash, lower.hash);
assert_eq!(upper.hash, mixed.hash);
assert_ne!(upper.units, lower.units, "the stored names still differ");
let (other, _) = placed("README.TX").expect("a name");
assert_ne!(upper.hash, other.hash);
}
#[test]
fn the_key_is_the_volumes_folding_rather_than_the_hosts_idea_of_case() {
let key = |name: &str| placed(name).expect("a name").1;
assert_eq!(key("README"), key("readme"));
assert_eq!(key("Ünïcode"), key("ÜNÏCODE"));
assert_ne!(key("README"), key("READ_ME"));
assert_ne!(key("stra\u{00DF}e"), key("STRASSE"));
assert_ne!(key("\u{0131}"), key("I"));
}
#[test]
fn a_name_the_format_cannot_hold_is_refused_by_name() {
for (name, expected) in [
(&b""[..], NameError::Empty),
(b"a/b", NameError::ForbiddenCharacter { ch: '/' }),
(b"a:b", NameError::ForbiddenCharacter { ch: ':' }),
(b"a*b", NameError::ForbiddenCharacter { ch: '*' }),
(b"a?b", NameError::ForbiddenCharacter { ch: '?' }),
(b"a\\b", NameError::ForbiddenCharacter { ch: '\\' }),
(b"a|b", NameError::ForbiddenCharacter { ch: '|' }),
(b"a\"b", NameError::ForbiddenCharacter { ch: '"' }),
(b"a<b", NameError::ForbiddenCharacter { ch: '<' }),
(b"a>b", NameError::ForbiddenCharacter { ch: '>' }),
(b"a\tb", NameError::ForbiddenCharacter { ch: '\t' }),
(b"trailing.", NameError::TrailingDotOrSpace),
(b"trailing ", NameError::TrailingDotOrSpace),
(b"\xFF\xFE", NameError::NotUtf8),
] {
assert_eq!(
place(name, &UpcaseTable::recommended()).unwrap_err(),
expected,
"{}",
crate::escape::printable(name)
);
}
}
#[test]
fn a_name_is_bounded_by_the_field_and_not_by_its_characters() {
assert!(placed(&"a".repeat(MAX_NAME_UNITS)).is_ok());
assert!(matches!(
placed(&"a".repeat(MAX_NAME_UNITS + 1)),
Err(NameError::TooLong { limit: 255, .. })
));
assert!(placed(&"\u{1F600}".repeat(127)).is_ok());
assert!(matches!(
placed(&"\u{1F600}".repeat(128)),
Err(NameError::TooLong { units: 256, .. })
));
}
}