// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz use crate::error::ParseError; use crate::limits::MAX_PATH; use serde::{Deserialize, Serialize}; use std::fmt; use std::str::FromStr; const BAD: ParseError = ParseError::BadPath("path"); const SEPARATORS: [char; 2] = ['\\', '/']; /// `X:\` const ROOT_LEN: usize = 3; /// Device names Windows opens instead of a file, whatever the folder or extension. const DEVICES: [&str; 32] = [ "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³", ]; /// An absolute Windows path with a drive letter, checked and normalised. /// /// Refused: anything not starting with `X:\` (so UNC `\\server\share`, `\\?\` and `\\.\` too), `.` and `..` /// components, NUL and other control characters, `<>:"|?*` (a `:` only after the drive letter), device names /// (`CON`, `NUL`, `COM1`, ...) as any component, components ending in a dot or a space, and paths over /// [`crate::limits::MAX_PATH`] UTF-16 units. Normalised: `/` becomes `\`, repeated separators collapse, the drive /// letter is uppercase and a trailing separator is dropped (except on the drive root `X:\`). /// /// Equality is exact on the normalised text; [`WinPath::eq_ignore_case`] compares the way Windows does. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(try_from = "String", into = "String")] pub struct WinPath(String); impl WinPath { /// Checks and normalises `s`. pub fn parse(s: &str) -> Result { // Cheap bound first: no valid path has more than 4 bytes per UTF-16 unit. if s.len() > 4 * MAX_PATH { return Err(BAD); } let mut chars = s.chars(); let drive = chars.next().filter(char::is_ascii_alphabetic).ok_or(BAD)?; if chars.next() != Some(':') { return Err(BAD); } let rest = chars.as_str(); if !rest.starts_with(SEPARATORS) { return Err(BAD); } let mut out = String::with_capacity(s.len()); out.push(drive.to_ascii_uppercase()); out.push_str(":\\"); let mut first = true; for comp in rest.split(SEPARATORS).filter(|c| !c.is_empty()) { check_component(comp)?; if !first { out.push('\\'); } first = false; out.push_str(comp); } if out.encode_utf16().count() > MAX_PATH { return Err(BAD); } Ok(WinPath(out)) } pub fn as_str(&self) -> &str { &self.0 } /// Appends a relative path (`a\b` or `a/b`); the same component rules apply and it may not climb out. pub fn join(&self, relative: &str) -> Result { if relative.is_empty() || relative.starts_with(SEPARATORS) { return Err(BAD); } let mut joined = String::with_capacity(self.0.len() + 1 + relative.len()); joined.push_str(&self.0); if !joined.ends_with('\\') { joined.push('\\'); } joined.push_str(relative); WinPath::parse(&joined) } /// The containing folder, or `None` for a drive root. pub fn parent(&self) -> Option { self.file_name()?; let cut = self.0.rfind('\\')?; let head = if cut < ROOT_LEN { self.0.get(..ROOT_LEN)? } else { self.0.get(..cut)? }; Some(WinPath(head.to_owned())) } /// The last component, or `None` for a drive root. pub fn file_name(&self) -> Option<&str> { self.components().last() } /// The components after the drive root. pub fn components(&self) -> impl Iterator { self.0.get(ROOT_LEN..).unwrap_or_default().split('\\').filter(|c| !c.is_empty()) } /// The case-folded form Windows treats as the same place, for comparing and deduping. pub fn key(&self) -> String { self.0.to_lowercase() } /// True when both name the same place, ignoring case. pub fn eq_ignore_case(&self, other: &WinPath) -> bool { self.key() == other.key() } /// True when `self` is `base` or lies inside it (component-wise, ignoring case). pub fn starts_with(&self, base: &WinPath) -> bool { let same_drive = self.0.get(..1).zip(base.0.get(..1)).is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)); if !same_drive { return false; } let mut mine = self.components(); base.components().all(|b| mine.next().is_some_and(|m| m.to_lowercase() == b.to_lowercase())) } } /// One path component, between separators. fn check_component(c: &str) -> Result<(), ParseError> { if c == "." || c == ".." || c.ends_with('.') || c.ends_with(' ') { return Err(BAD); } if c.chars().any(|ch| ch.is_control() || matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*')) { return Err(BAD); } let stem = c.split('.').next().unwrap_or(c).trim_end_matches(' '); if DEVICES.iter().any(|d| d.eq_ignore_ascii_case(stem)) { return Err(BAD); } Ok(()) } impl fmt::Display for WinPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) } } impl FromStr for WinPath { type Err = ParseError; fn from_str(s: &str) -> Result { WinPath::parse(s) } } impl TryFrom for WinPath { type Error = ParseError; fn try_from(s: String) -> Result { WinPath::parse(&s) } } impl From for String { fn from(p: WinPath) -> String { p.0 } } impl AsRef for WinPath { fn as_ref(&self) -> &str { &self.0 } }