Skip to content

Commit 3ea37e4

Browse files
committed
Parse a Windows file name without normalization
1 parent a84d1b2 commit 3ea37e4

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

library/std/src/sys/windows/path.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,24 @@ pub fn is_verbatim_sep(b: u8) -> bool {
2828
b == b'\\'
2929
}
3030

31+
/// Gets the final component of a path. Unlike the public `Path::file_name`,
32+
/// this will not perform any normalization.
33+
///
34+
/// If `path` ends with a separator then it will return an empty string.
35+
/// If `path` is empty then it will return `None`.
36+
pub(crate) fn parse_filename(path: &OsStr) -> Option<&OsStr> {
37+
if path.is_empty() {
38+
None
39+
} else {
40+
let is_verbatim = path.bytes().starts_with(br"\\?\");
41+
let is_separator = if is_verbatim { is_verbatim_sep } else { is_sep_byte };
42+
let filename = path.bytes().rsplit(|&b| is_separator(b)).next().unwrap_or(&[]);
43+
// SAFETY: We are only splitting the string on ASCII characters so it
44+
// will remain valid WTF-8.
45+
Some(unsafe { bytes_as_os_str(filename) })
46+
}
47+
}
48+
3149
pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
3250
use Prefix::{DeviceNS, Disk, Verbatim, VerbatimDisk, VerbatimUNC, UNC};
3351

0 commit comments

Comments
 (0)