use std::path::Path;
#[must_use]
pub fn of(payload_name: &str) -> Option<&str> {
if payload_name.is_empty() || payload_name.contains(['/', '\\']) {
return None;
}
match Path::new(payload_name).extension()?.to_str()? {
"" => None,
e => Some(e),
}
}
#[must_use]
pub fn policy_key(payload_name: &str) -> Option<String> {
let e = of(payload_name)?;
e.chars()
.all(|c| c.is_ascii_alphanumeric())
.then(|| e.to_ascii_lowercase())
}
#[cfg(test)]
mod tests {
use super::{of, policy_key};
#[test]
fn takes_the_last_extension_and_not_the_whole_tail() {
assert_eq!(of("archive.tar.gz"), Some("gz"));
}
#[test]
fn a_name_that_is_all_name_has_no_extension() {
assert_eq!(of("README"), None);
}
#[test]
fn a_leading_dot_makes_a_hidden_file_rather_than_an_extension() {
assert_eq!(of(".bashrc"), None);
}
#[test]
fn a_trailing_dot_is_not_an_extension() {
assert_eq!(of("report."), None);
}
#[test]
fn a_name_carrying_a_separator_is_refused_rather_than_split() {
assert_eq!(of("etc/passwd.pdf"), None);
assert_eq!(of("..\\windows\\system32\\x.dll"), None);
}
#[test]
fn the_policy_key_folds_ascii_case() {
assert_eq!(policy_key("REPORT.PDF").as_deref(), Some("pdf"));
assert_eq!(policy_key("report.PdF").as_deref(), Some("pdf"));
}
#[test]
fn an_extension_that_is_not_ascii_alphanumeric_is_not_comparable() {
assert_eq!(policy_key("report.pdf\u{212a}"), None);
assert_eq!(policy_key("notes.tëxt"), None);
}
#[test]
fn digits_are_comparable_because_real_extensions_carry_them() {
assert_eq!(policy_key("clip.mp3").as_deref(), Some("mp3"));
assert_eq!(policy_key("page.7z").as_deref(), Some("7z"));
}
#[test]
fn the_display_form_keeps_the_case_the_container_spelled() {
assert_eq!(of("REPORT.PDF"), Some("PDF"));
}
}