use std::fmt;
use std::str::FromStr;
use super::error::{NsError, NsErrorKind};
pub const MAX_NAME_BYTES: usize = 255;
pub const MAX_PATH_BYTES: usize = 4096;
pub const TEMP_PREFIX: &str = ".skns-tmp-";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PathReason {
NotAbsolute,
EmptyComponent,
DotComponent,
DotDotComponent,
ControlCharacter,
FormatCharacter,
ForbiddenCharacter,
NotNfc,
TrailingDotOrSpace,
ReservedName,
ReservedPrefix,
NameTooLong,
PathTooLong,
}
impl PathReason {
pub(crate) fn describe(self) -> &'static str {
match self {
PathReason::NotAbsolute => {
"a namespace path starts with '/' (a host path or a relative path is not one)"
}
PathReason::EmptyComponent => "an empty component ('//' or a trailing '/')",
PathReason::DotComponent => "a '.' component",
PathReason::DotDotComponent => {
"a '..' component (there is no parent traversal; give the parent's path)"
}
PathReason::ControlCharacter => "a control character in a name",
PathReason::FormatCharacter => {
"an invisible or direction-changing format character in a name (bidi control, zero-width space, soft hyphen, BOM)"
}
PathReason::ForbiddenCharacter => {
"a character that is not portable in a name (one of \\ : < > \" | ? *)"
}
PathReason::NotNfc => "a name that is not Unicode NFC (normalise it first)",
PathReason::TrailingDotOrSpace => "a name ending in '.' or a space",
PathReason::ReservedName => "a Windows reserved device name (CON, NUL, COM1, ...)",
PathReason::ReservedPrefix => "a name starting with the reserved temporary prefix",
PathReason::NameTooLong => "a name longer than 255 bytes",
PathReason::PathTooLong => "a path longer than 4096 bytes",
}
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct NsPath(String);
impl NsPath {
pub fn root() -> Self {
NsPath("/".to_string())
}
pub fn parse(input: &str) -> Result<Self, NsError> {
let invalid = |r| NsError::new(NsErrorKind::InvalidPath(r));
if input.len() > MAX_PATH_BYTES {
return Err(invalid(PathReason::PathTooLong));
}
let Some(rest) = input.strip_prefix('/') else {
return Err(invalid(PathReason::NotAbsolute));
};
if rest.is_empty() {
return Ok(Self::root());
}
for name in rest.split('/') {
validate_name(name).map_err(invalid)?;
}
Ok(NsPath(input.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_root(&self) -> bool {
self.0 == "/"
}
pub fn depth(&self) -> usize {
self.components().count()
}
pub fn join(&self, relative: &str) -> Result<NsPath, NsError> {
let invalid = |r| NsError::new(NsErrorKind::InvalidPath(r));
if relative.is_empty() {
return Err(invalid(PathReason::EmptyComponent));
}
for name in relative.split('/') {
validate_name(name).map_err(invalid)?;
}
let mut s = if self.is_root() {
String::new()
} else {
self.0.clone()
};
s.push('/');
s.push_str(relative);
if s.len() > MAX_PATH_BYTES {
return Err(invalid(PathReason::PathTooLong));
}
Ok(NsPath(s))
}
pub(crate) fn child(&self, name: &str) -> Option<NsPath> {
debug_assert!(validate_name(name).is_ok());
let mut s = if self.is_root() {
String::new()
} else {
self.0.clone()
};
s.push('/');
s.push_str(name);
(s.len() <= MAX_PATH_BYTES).then_some(NsPath(s))
}
pub fn parent(&self) -> Option<NsPath> {
if self.is_root() {
return None;
}
let idx = self.0.rfind('/')?;
Some(if idx == 0 {
Self::root()
} else {
NsPath(self.0[..idx].to_string())
})
}
pub fn file_name(&self) -> Option<&str> {
if self.is_root() {
None
} else {
self.0.rsplit('/').next()
}
}
pub fn components(&self) -> impl DoubleEndedIterator<Item = &str> + Clone {
self.0.split('/').filter(|c| !c.is_empty())
}
pub fn starts_with(&self, base: &NsPath) -> bool {
if base.is_root() || self == base {
return true;
}
self.0
.strip_prefix(base.0.as_str())
.is_some_and(|rest| rest.starts_with('/'))
}
pub fn strip_prefix(&self, base: &NsPath) -> Option<NsPath> {
if !self.starts_with(base) {
return None;
}
if base.is_root() {
return Some(self.clone());
}
let rest = &self.0[base.0.len()..];
Some(if rest.is_empty() {
Self::root()
} else {
NsPath(rest.to_string())
})
}
pub(crate) fn fold_components(&self) -> Vec<String> {
self.components().map(case_fold_key).collect()
}
pub(crate) fn tail_after(&self, skip: usize) -> NsPath {
let mut out = String::new();
for c in self.components().skip(skip) {
out.push('/');
out.push_str(c);
}
if out.is_empty() {
NsPath::root()
} else {
NsPath(out)
}
}
pub fn rebase(&self, base: &NsPath) -> Result<NsPath, NsError> {
if base.is_root() {
return Ok(self.clone());
}
if self.is_root() {
return Ok(base.clone());
}
let s = format!("{}{}", base.0, self.0);
if s.len() > MAX_PATH_BYTES {
return Err(NsError::new(NsErrorKind::InvalidPath(
PathReason::PathTooLong,
)));
}
Ok(NsPath(s))
}
}
impl PartialOrd for NsPath {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NsPath {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.components().cmp(other.components())
}
}
impl fmt::Display for NsPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for NsPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "NsPath({:?})", self.0)
}
}
impl FromStr for NsPath {
type Err = NsError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
NsPath::parse(s)
}
}
const FORBIDDEN: &[char] = &['\\', ':', '<', '>', '"', '|', '?', '*'];
pub fn validate_name(name: &str) -> Result<(), PathReason> {
if name.is_empty() {
return Err(PathReason::EmptyComponent);
}
if name == "." {
return Err(PathReason::DotComponent);
}
if name == ".." {
return Err(PathReason::DotDotComponent);
}
if name.len() > MAX_NAME_BYTES {
return Err(PathReason::NameTooLong);
}
for c in name.chars() {
if c.is_control() {
return Err(PathReason::ControlCharacter);
}
if is_format_character(c) {
return Err(PathReason::FormatCharacter);
}
if FORBIDDEN.contains(&c) {
return Err(PathReason::ForbiddenCharacter);
}
}
if !unicode_normalization::is_nfc(name) {
return Err(PathReason::NotNfc);
}
if name.ends_with('.') || name.ends_with(' ') {
return Err(PathReason::TrailingDotOrSpace);
}
if is_reserved_device_name(name) {
return Err(PathReason::ReservedName);
}
if case_fold_key(name).starts_with(TEMP_PREFIX) {
return Err(PathReason::ReservedPrefix);
}
Ok(())
}
pub fn is_format_character(c: char) -> bool {
matches!(
c,
'\u{00AD}'
| '\u{061C}'
| '\u{180E}'
| '\u{200B}'
| '\u{200E}'..='\u{200F}'
| '\u{202A}'..='\u{202E}'
| '\u{2060}'..='\u{2064}'
| '\u{2066}'..='\u{2069}'
| '\u{FEFF}'
)
}
fn is_reserved_device_name(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ');
let up = stem.to_uppercase();
match up.as_str() {
"CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true,
_ => {
let digit = |rest: &str| {
matches!(
rest,
"1" | "2"
| "3"
| "4"
| "5"
| "6"
| "7"
| "8"
| "9"
| "\u{b9}"
| "\u{b2}"
| "\u{b3}"
)
};
up.strip_prefix("COM")
.or_else(|| up.strip_prefix("LPT"))
.is_some_and(digit)
}
}
}
pub fn case_fold_key(name: &str) -> String {
use unicode_normalization::UnicodeNormalization;
let composed: String = name.nfc().collect();
composed.to_uppercase().to_lowercase().nfc().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn root_and_basics() {
let r = NsPath::root();
assert!(r.is_root());
assert_eq!(r.parent(), None);
assert_eq!(r.file_name(), None);
assert_eq!(r.depth(), 0);
let p = NsPath::parse("/a/b/c").unwrap();
assert_eq!(p.file_name(), Some("c"));
assert_eq!(p.parent().unwrap().as_str(), "/a/b");
assert_eq!(NsPath::parse("/a").unwrap().parent().unwrap(), r);
assert_eq!(p.components().collect::<Vec<_>>(), ["a", "b", "c"]);
}
#[test]
fn prefix_ops_use_whole_components() {
let a = NsPath::parse("/a").unwrap();
let ab = NsPath::parse("/ab").unwrap();
let a_b = NsPath::parse("/a/b").unwrap();
assert!(a_b.starts_with(&a));
assert!(!ab.starts_with(&a));
assert!(a.starts_with(&a));
assert!(a.starts_with(&NsPath::root()));
assert_eq!(a_b.strip_prefix(&a).unwrap().as_str(), "/b");
assert!(a.strip_prefix(&a).unwrap().is_root());
assert_eq!(ab.strip_prefix(&a), None);
assert_eq!(a_b.strip_prefix(&NsPath::root()).unwrap(), a_b);
let b = NsPath::parse("/b").unwrap();
assert_eq!(b.rebase(&a).unwrap().as_str(), "/a/b");
assert_eq!(NsPath::root().rebase(&a).unwrap(), a);
}
#[test]
fn order_is_by_component() {
let mut v = [
NsPath::parse("/a-b").unwrap(),
NsPath::parse("/a/b").unwrap(),
NsPath::parse("/a").unwrap(),
];
v.sort();
let s: Vec<_> = v.iter().map(NsPath::as_str).collect();
assert_eq!(s, ["/a", "/a/b", "/a-b"]);
}
#[test]
fn join_validates_each_component() {
let a = NsPath::parse("/a").unwrap();
assert_eq!(a.join("b/c").unwrap().as_str(), "/a/b/c");
assert_eq!(NsPath::root().join("x").unwrap().as_str(), "/x");
assert!(a.join("/b").is_err());
assert!(a.join("b/../c").is_err());
assert!(a.join("").is_err());
}
}