1use std::path::{Path, PathBuf};
8
9pub fn normalize_windows_path(path: &Path) -> PathBuf {
15 let raw = path.to_string_lossy().replace('/', "\\");
16 let mut normalized = non_verbatim_path_text(&raw).unwrap_or(raw);
17 if normalized.as_bytes().get(1) == Some(&b':') {
18 let drive = normalized.as_bytes()[0];
19 if drive.is_ascii_lowercase() {
20 normalized.replace_range(0..1, &(drive as char).to_ascii_uppercase().to_string());
21 }
22 }
23 PathBuf::from(normalized)
24}
25
26pub fn non_verbatim_path_text(path: &str) -> Option<String> {
29 for prefix in [r"\\?\UNC\", r"\\??\UNC\", r"\??\UNC\"] {
30 if let Some(tail) = strip_ascii_prefix(path, prefix) {
31 if is_safe_unc_tail(tail) {
32 return Some(format!(r"\\{tail}"));
33 }
34 return None;
35 }
36 }
37
38 for prefix in [r"\\?\", r"\\??\", r"\??\"] {
39 if let Some(tail) = strip_ascii_prefix(path, prefix) {
40 let bytes = tail.as_bytes();
41 if bytes.len() >= 3
42 && bytes[0].is_ascii_alphabetic()
43 && bytes[1] == b':'
44 && matches!(bytes[2], b'\\' | b'/')
45 && !has_dot_component(tail)
46 {
47 return Some(tail.to_string());
48 }
49 return None;
50 }
51 }
52
53 None
54}
55
56pub const PLAIN_WIN32_PATH_LIMIT: usize = 248;
61
62pub fn extended_length_path_text(absolute: &str) -> Option<String> {
68 let text = absolute.replace('/', "\\");
69 if text.encode_utf16().count() < PLAIN_WIN32_PATH_LIMIT {
70 return None;
71 }
72 if [r"\\?\", r"\\.\", r"\??\"]
73 .iter()
74 .any(|prefix| strip_ascii_prefix(&text, prefix).is_some())
75 || has_dot_component(&text)
76 {
77 return None;
78 }
79 if let Some(tail) = text.strip_prefix(r"\\") {
80 return is_safe_unc_tail(tail).then(|| format!(r"\\?\UNC\{tail}"));
81 }
82 let bytes = text.as_bytes();
83 (bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\')
84 .then(|| format!(r"\\?\{text}"))
85}
86
87#[cfg(windows)]
92pub(crate) fn win32_call_path(path: &Path) -> std::borrow::Cow<'_, Path> {
93 use std::os::windows::ffi::OsStrExt;
94 if path.as_os_str().encode_wide().count() < PLAIN_WIN32_PATH_LIMIT {
95 return std::borrow::Cow::Borrowed(path);
96 }
97 std::path::absolute(path)
98 .ok()
99 .and_then(|absolute| absolute.to_str().and_then(extended_length_path_text))
100 .map_or(std::borrow::Cow::Borrowed(path), |text| {
101 std::borrow::Cow::Owned(PathBuf::from(text))
102 })
103}
104
105fn is_safe_unc_tail(tail: &str) -> bool {
106 let mut components = tail.split(['\\', '/']);
107 components.next().is_some_and(|server| !server.is_empty())
108 && components.next().is_some_and(|share| !share.is_empty())
109 && !has_dot_component(tail)
110}
111
112fn has_dot_component(path: &str) -> bool {
113 path.split(['\\', '/'])
114 .any(|component| matches!(component, "." | ".."))
115}
116
117fn strip_ascii_prefix<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
118 let head = value.get(..prefix.len())?;
119 if head.eq_ignore_ascii_case(prefix) {
120 value.get(prefix.len()..)
121 } else {
122 None
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::{non_verbatim_path_text, normalize_windows_path};
129 use std::path::{Path, PathBuf};
130
131 #[test]
132 fn converts_only_valid_dos_and_unc_verbatim_paths() {
133 assert_eq!(
134 non_verbatim_path_text(r"\\?\C:\cache\server.cmd"),
135 Some(r"C:\cache\server.cmd".to_string())
136 );
137 assert_eq!(
138 non_verbatim_path_text(r"\\?\unc\host\share\server.cmd"),
139 Some(r"\\host\share\server.cmd".to_string())
140 );
141 assert_eq!(
142 normalize_windows_path(Path::new(r"\\??\d:\repo")),
143 PathBuf::from(r"D:\repo")
144 );
145 }
146
147 #[test]
148 fn long_paths_get_the_extended_length_form_for_win32_calls() {
149 use super::{extended_length_path_text, PLAIN_WIN32_PATH_LIMIT};
150 let deep = "a".repeat(PLAIN_WIN32_PATH_LIMIT);
151 assert_eq!(
152 extended_length_path_text(&format!(r"C:\storage\{deep}")),
153 Some(format!(r"\\?\C:\storage\{deep}"))
154 );
155 assert_eq!(
156 extended_length_path_text(&format!("C:/storage/{deep}")),
157 Some(format!(r"\\?\C:\storage\{deep}"))
158 );
159 assert_eq!(
160 extended_length_path_text(&format!(r"\\host\share\{deep}")),
161 Some(format!(r"\\?\UNC\host\share\{deep}"))
162 );
163 for unchanged in [
164 r"C:\storage\short".to_string(),
165 format!(r"\\?\C:\storage\{deep}"),
166 format!(r"\\.\pipe\{deep}"),
167 format!(r"C:\storage\..\{deep}"),
168 format!(r"storage\{deep}"),
169 format!(r"\\{deep}"),
170 ] {
171 assert_eq!(extended_length_path_text(&unchanged), None, "{unchanged}");
172 }
173 }
174
175 #[test]
176 fn preserves_unsupported_or_malformed_verbatim_namespaces() {
177 for path in [
178 r"\\?\Volume{1234}\server.cmd",
179 r"\\?\UNC\host",
180 r"\\?\UNC\\host\share",
181 r"\\??\UNC\\host\share",
182 r"\\?\UNC\host\share\..\file",
183 r"\\?\C:\repo\..\other",
184 r"\\?\C:relative",
185 r"\\?\relative",
186 r"C:\ordinary\path",
187 ] {
188 assert_eq!(non_verbatim_path_text(path), None, "{path}");
189 }
190 }
191}