use std::path::PathBuf;
use crate::PlatformError;
#[cfg(target_os = "linux")]
use crate::linux::user_dirs as system_dirs;
#[cfg(target_os = "macos")]
use crate::macos::user_dirs as system_dirs;
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
use crate::unsupported::user_dirs as system_dirs;
#[cfg(target_os = "windows")]
use crate::windows::user_dirs as system_dirs;
const MAX_NAME_BYTES: usize = 255;
const FORBIDDEN: [char; 9] = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserDirs {
pub config: PathBuf,
pub data: PathBuf,
pub logs: PathBuf,
}
pub fn user_dirs(studio: &str, game: &str) -> Result<UserDirs, PlatformError> {
check_name(studio)?;
check_name(game)?;
system_dirs(studio, game)
}
fn check_name(name: &str) -> Result<(), PlatformError> {
let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ');
let valid = !name.is_empty()
&& name.len() <= MAX_NAME_BYTES
&& !name
.chars()
.any(|c| c.is_control() || FORBIDDEN.contains(&c))
&& !name.starts_with(' ')
&& !name.ends_with([' ', '.'])
&& !is_device_name(stem);
if valid {
Ok(())
} else {
Err(PlatformError::InvalidName {
name: name.to_string(),
})
}
}
fn is_device_name(stem: &str) -> bool {
let upper = stem.to_ascii_uppercase();
if matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL") {
return true;
}
let Some(number) = upper
.strip_prefix("COM")
.or_else(|| upper.strip_prefix("LPT"))
else {
return false;
};
let mut chars = number.chars();
matches!(
(chars.next(), chars.next()),
(Some('0'..='9' | '¹' | '²' | '³'), None)
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordinary_names_are_accepted() {
for name in [
"Sandbox",
"My Game",
"Nadir Studio",
"Café",
"ゲーム",
"game-2",
"v1.0",
".hidden",
"CONSOLE",
"Contra",
"COM10",
"LPT",
"NULL",
] {
assert_eq!(check_name(name), Ok(()), "{name:?}");
}
assert_eq!(check_name(&"x".repeat(MAX_NAME_BYTES)), Ok(()));
}
#[test]
fn names_that_some_system_refuses_are_rejected() {
let long = "x".repeat(MAX_NAME_BYTES + 1);
for name in [
"",
".",
"..",
"a/b",
"/abs",
"a\\b",
"C:",
"what?",
"star*",
"<x>",
"\"quoted\"",
"a|b",
"tab\there",
"line\nbreak",
"nul\0",
" leading",
"trailing ",
"trailing.",
"CON",
"con",
"Con.txt",
"NUL",
"aux.tar.gz",
"AUX .log",
"prn",
"COM1",
"com0",
"LPT9",
"COM¹",
"lpt³",
&long,
] {
assert_eq!(
check_name(name),
Err(PlatformError::InvalidName {
name: name.to_string()
}),
"{name:?}"
);
}
}
#[test]
fn both_names_are_checked() {
let invalid = |name: &str| {
Err(PlatformError::InvalidName {
name: name.to_string(),
})
};
assert_eq!(user_dirs("a/b", "Game"), invalid("a/b"));
assert_eq!(user_dirs("Studio", ".."), invalid(".."));
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
#[test]
fn other_systems_have_no_paths_yet() {
assert_eq!(user_dirs("Studio", "Game"), Err(PlatformError::Unsupported));
}
}