path: Reimplement PathStyle on the standard library's path implementation (#64149)

# Objective

Rust's standard library `Path` API is platform-dependent, so you get
wrong results when processing a Windows path on Unix, or vice versa. Zed
needs this functionality because we support remote development, where
cross-platform path handling is routine. Zed's `PathStyle` takes on this
responsibility.

But handling paths can be really tricky: we need to handle paths with
non-UTF-8 characters, a problem I ran into in #63075. And thanks to
Microsoft, there are 5 different kinds of valid path prefixes! Not to
mention the `/` and `\` separators, which was another problem I ran into
in #63102. So we need to make some changes to the `PathStyle` API.

## Solution

I'm not an expert on this low-level API design, or on API design in
general. But the people who maintain the Rust standard library are.
Since `PathStyle`'s API is largely a cross-platform version of the
standard library's `Path`, the most reliable and straightforward
approach I could come up with is to bring the standard library's
implementation into the Zed repo and make the necessary modifications to
make it work cross-platform.

It turns out Rust already has a great abstraction: the
platform-dependent part of `Path` is packaged under
`library/std/src/sys/path` and selected at compile time, while the
`Path` implementation just uses the abstracted constants and methods:


https://github.com/rust-lang/rust/blob/6474e999898cad2289175e2a7d253f5d0f574fa2/library/std/src/path.rs#L96

So we can add some helper methods to `PathStyle` to represent the
compile-time-determined pieces of the standard library. Then we bring in
the rest, achieving our goal of making `PathStyle`'s functionality the
same as the standard library's, but cross-platform.

Overall, the `parent()` and `file_name()` methods I introduced in #62038
have been reimplemented, and a new `starts_with()` method has been
added. Their implementations are nearly the same as the ones in the
standard library. To make these methods work, the standard library's
`Components` struct was added in a new file,
`crates/path/src/path_component.rs`, which is the core of reliable path
handling; and `crates/path/src/windows_prefix.rs` was added to handle
Windows paths. Most of the code in these two files is the same as the
standard library's; I only made some small tweaks to make it work with
`PathStyle`.

## Testing

New tests for `starts_with` have been added.

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

---

Release Notes:

- N/A
This commit is contained in:
Xin Zhao
2026-10-03 08:53:38 +00:00
committed by GitHub
parent 5eed2397a8
commit a84689073d
6 changed files with 832 additions and 179 deletions
+1 -1
View File
@@ -703,7 +703,7 @@ fn tooltip_for_server_binary(
let runtime = path_style.file_name(&server_binary.path).and_then(|name| {
["node", "python"]
.into_iter()
.find(|runtime| name.starts_with(runtime))
.find(|runtime| name.to_string_lossy().starts_with(runtime))
});
let target_path = runtime
+167 -175
View File
@@ -8,13 +8,17 @@
use std::{
borrow::Cow,
ffi::OsStr,
path::{Path, PathBuf},
};
use crate::path_component::{Component, Components, Prefix, PrefixExt, iter_after};
use crate::rel_path::RelPath;
pub mod abs_path;
mod path_component;
pub mod rel_path;
mod windows_prefix;
pub trait PathExt {
fn to_rel_path_buf(&self) -> anyhow::Result<rel_path::RelPathBuf>;
@@ -257,175 +261,30 @@ impl PathStyle {
)
}
pub fn file_name(self, path: &Path) -> Option<&str> {
if self == PathStyle::local() {
return path.file_name().and_then(|n| n.to_str());
}
let path_string = path.to_str()?;
let parent_length = self.parent(path)?.to_str()?.len();
let remainder = path_string.get(parent_length..)?;
let is_verbatim = self.is_windows() && path_string.as_bytes().starts_with(br"\\?\");
let is_body_separator = |character: char| {
if is_verbatim {
character == '\\'
} else {
self.separators_ch().contains(&character)
}
};
let component = remainder
.rsplit(is_body_separator)
.find(|component| !component.is_empty() && (is_verbatim || *component != "."))?;
if matches!(component, "." | "..") {
None
} else {
Some(component)
}
pub fn file_name<'a>(&self, path: &'a Path) -> Option<&'a OsStr> {
self.components(path).next_back().and_then(|p| match p {
Component::Normal(p) => Some(p),
_ => None,
})
}
pub fn parent(self, path: &Path) -> Option<&Path> {
if self == PathStyle::local() {
return path.parent();
}
let path = path.to_str()?;
let path_bytes = path.as_bytes();
let is_windows = self.is_windows();
const DRIVE_PREFIX_LENGTH: usize = 2;
const UNC_PREFIX_LENGTH: usize = 2;
const VERBATIM_PREFIX: &[u8] = br"\\?\";
const VERBATIM_UNC_PREFIX: &[u8] = br"\\?\UNC\";
const DEVICE_PREFIX: &[u8] = br"\\.\";
let is_separator = |byte: u8| byte == b'/' || is_windows && byte == b'\\';
let is_verbatim = is_windows && path_bytes.starts_with(VERBATIM_PREFIX);
let has_unc_prefix = path_bytes
.get(..UNC_PREFIX_LENGTH)
.is_some_and(|prefix| prefix.iter().all(|byte| is_separator(*byte)));
// Verbatim paths treat '/' as a literal character, so only '\' separates body components.
let is_body_separator = |byte: u8| {
if is_verbatim {
byte == b'\\'
} else {
is_separator(byte)
pub fn parent<'a>(&self, path: &'a Path) -> Option<&'a Path> {
let mut comps = self.components(path);
let comp = comps.next_back();
comp.and_then(|p| match p {
Component::Normal(_) | Component::CurDir | Component::ParentDir => {
Some(comps.as_path())
}
};
_ => None,
})
}
let component_end = |component_start: usize| {
path_bytes
.get(component_start..)
.and_then(|remainder| remainder.iter().position(|byte| is_body_separator(*byte)))
.map_or(path_bytes.len(), |position| component_start + position)
};
// Windows prefixes, in precedence order: \\?\UNC\, \\?\ (verbatim), \\.\ (device),
// \\ (UNC), drive letter. The device prefix must be matched before the generic UNC
// check because it also starts with two separators.
let prefix_end = {
if !is_windows {
0
} else if path_bytes.starts_with(VERBATIM_UNC_PREFIX) {
let server_end = component_end(VERBATIM_UNC_PREFIX.len());
let share_start = server_end.saturating_add(1).min(path_bytes.len());
if share_start < path_bytes.len() {
component_end(share_start)
} else {
server_end
}
} else if is_verbatim {
let drive_start = VERBATIM_PREFIX.len();
let drive_end = drive_start + DRIVE_PREFIX_LENGTH;
let has_drive_prefix = path_bytes
.get(drive_start)
.is_some_and(u8::is_ascii_alphabetic)
&& path_bytes.get(drive_start + 1) == Some(&b':');
// A drive letter only counts as a prefix when followed by a separator or end
// of path; otherwise (e.g. `\\?\C:foo`) the whole first component is the prefix.
if has_drive_prefix
&& path_bytes
.get(drive_end)
.is_none_or(|byte| is_separator(*byte))
{
drive_end
} else {
component_end(drive_start)
}
} else if path_bytes.starts_with(DEVICE_PREFIX) {
component_end(DEVICE_PREFIX.len())
} else if has_unc_prefix {
let server_end = component_end(UNC_PREFIX_LENGTH);
let share_start = server_end.saturating_add(1).min(path_bytes.len());
let share_end = component_end(share_start);
// A UNC prefix requires a share name; `\\server` without one is treated as a
// relative path, so its prefix is empty.
if server_end > UNC_PREFIX_LENGTH && share_end > share_start {
share_end
} else {
0
}
} else if path_bytes.first().is_some_and(u8::is_ascii_alphabetic)
&& path_bytes.get(1) == Some(&b':')
{
DRIVE_PREFIX_LENGTH
} else {
0
}
};
// Uses is_separator rather than is_body_separator: after a verbatim drive prefix,
// '/' still counts as the root separator (e.g. `\\?\C:/foo`) even though '/' does
// not separate body components.
let has_root = path_bytes
.get(prefix_end)
.is_some_and(|byte| is_separator(*byte));
// The leading `.`/`./` is absorbed into the body (e.g. `./a` → parent `.`).
let starts_with_current_directory = prefix_end == 0
&& !has_root
&& path_bytes.first() == Some(&b'.')
&& (path_bytes.len() == 1 || path_bytes.get(1).is_some_and(|byte| is_separator(*byte)));
let body_start =
prefix_end + usize::from(has_root) + usize::from(starts_with_current_directory);
// Loop because trimming a trailing '.' (e.g. `foo/.`) can expose a separator to trim,
// and vice versa (`foo/./`). Verbatim paths never treat '.' as a current-directory
// component, hence the !is_verbatim check below.
let trim_trailing = |mut end: usize| {
loop {
while end > body_start && is_body_separator(path_bytes[end - 1]) {
end -= 1;
}
let is_trailing_current_directory = !is_verbatim
&& end > body_start
&& path_bytes[end - 1] == b'.'
&& (end - 1 == body_start
|| end
.checked_sub(2)
.and_then(|index| path_bytes.get(index))
.is_some_and(|byte| is_body_separator(*byte)));
if is_trailing_current_directory {
end -= 1;
} else {
return end;
}
}
};
let body_end = trim_trailing(path_bytes.len());
// An empty body means the path is root- or prefix-only and has no parent; only a
// bare current-directory component (`.`/`./`) has `""` as its parent.
if body_end == body_start {
return starts_with_current_directory.then_some(Path::new(""));
}
let parent_end = path_bytes
.get(body_start..body_end)?
.iter()
.rposition(|byte| is_body_separator(*byte))
.map_or(body_start, |position| trim_trailing(body_start + position));
Some(Path::new(path.get(..parent_end)?))
pub fn starts_with<P: AsRef<Path>>(&self, path: P, prefix: P) -> bool {
iter_after(
self.components(path.as_ref()),
self.components(prefix.as_ref()),
)
.is_some()
}
pub fn strip_prefix<'a>(
@@ -468,6 +327,51 @@ impl PathStyle {
}
}
// This part contains the methods adopted from the std lib
// to make the pub api of `PathStyle` compatible with `Path`
impl PathStyle {
fn components<'a>(&self, path: &'a Path) -> Components<'a> {
Components::new(*self, path)
}
fn parse_prefix<'a>(&self, path: &'a OsStr) -> Option<Prefix<'a>> {
match self {
PathStyle::Unix => None,
PathStyle::Windows => windows_prefix::parse_prefix(path),
}
}
fn has_prefixes(&self) -> bool {
match self {
PathStyle::Unix => false,
PathStyle::Windows => true,
}
}
fn is_sep_byte(&self, b: u8) -> bool {
match self {
Self::Unix => b == b'/',
Self::Windows => b == b'\\' || b == b'/',
}
}
fn is_verbatim_sep(&self, b: u8) -> bool {
match self {
Self::Unix => self.is_sep_byte(b),
Self::Windows => b == b'\\',
}
}
fn has_physical_root(&self, s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
let path = if let Some(p) = prefix {
&s[p.len()..]
} else {
s
};
!path.is_empty() && self.is_sep_byte(path[0])
}
}
fn is_absolute(path_like: &str, path_style: PathStyle) -> bool {
path_like.starts_with('/')
|| path_style == PathStyle::Windows
@@ -691,6 +595,82 @@ mod tests {
pretty_assertions::assert_eq!(actual, expected);
}
#[test]
fn test_unix_path_style_starts_with() {
let unix_paths_and_prefixes = [
("", "", true),
("foo", "", true),
("", "foo", false),
("foo", "foo", true),
("foo/", "foo", true),
("foo//", "foo", true),
("foo///", "foo", true),
("foo/.", "foo", true),
("foo/./bar", "foo/bar", true),
("foo/.//bar", "foo/bar", true),
("foo//./bar", "foo/bar", true),
("foo/bar", "foo", true),
("foo/bar", "foobar", false),
("foo/bar/baz", "foo/bar", true),
("foo/bar", "foo/bar/baz", false),
("./foo/bar/", ".", true),
("/etc/passwd", "/etc", true),
("/etc/passwd", "/etc/", true),
("/etc/passwd", "/etc/passwd", true),
("/etc/passwd", "/etc/passwd/", true),
("/etc/passwd", "/etc/passwd///", true),
("/etc/passwd", "/e", false),
("/etc/passwd", "/etc/passwd.txt", false),
("/etc/foo.rs", "/etc/foo", false),
];
for (path, prefix, expected) in unix_paths_and_prefixes {
assert_eq!(
PathStyle::Unix.starts_with(Path::new(path), Path::new(prefix)),
expected,
"{path:?}.starts_with({prefix:?})"
);
}
}
#[test]
fn test_windows_path_style_starts_with() {
let windows_paths_and_prefixes = [
(
r"C:\src\rust\cargo-test\test\Cargo.toml",
r"c:\src\rust\cargo-test\test",
true,
),
(r"C:\foo\.\bar.txt", r"C:\foo\bar.txt", true),
(r"C:\foo\.", r"C:\foo", true),
(r"\\server\share", r"\\server", false),
(r"\\server\share\foo.txt", r"\\server", false),
(r"\\server\share\foo.txt", r"\\server\share", true),
(r"\\server\share\foo.txt", r"\\server\share\", true),
(r"\\server\share\foo.txt", r"\\server\share/", true),
(r"\\server\share\foo.txt", r"\\server\other", false),
(r"\\server\share\foo.txt", r"\\SERVER\share", false),
(r"\\?\C:\foo\.\bar.txt", r"\\?\C:\foo\bar.txt", false),
(r"\\?\C:\foo.txt", r"\\?\C:\", true),
(
r"\\?\UNC\server\share\foo.txt",
r"\\?\UNC\server\share",
true,
),
(r"\\?\UNC\server\share\foo.txt", r"\\?\UNC\server\", false),
(r"\\?\bar\foo.txt", r"\\?\bar", true),
(r"\\?\C:\foo/bar.txt", r"\\?\C:\foo", false),
];
for (path, prefix, expected) in windows_paths_and_prefixes {
assert_eq!(
PathStyle::Windows.starts_with(Path::new(path), Path::new(prefix)),
expected,
"{path:?}.starts_with({prefix:?})"
);
}
}
#[test]
fn test_unix_path_style_file_name() {
let unix_paths_and_filenames = [
@@ -708,7 +688,7 @@ mod tests {
];
for (path, filename) in unix_paths_and_filenames {
assert_eq!(PathStyle::Unix.file_name(path), filename);
assert_eq!(PathStyle::Unix.file_name(path), filename.map(OsStr::new));
}
}
@@ -731,13 +711,13 @@ mod tests {
(Path::new("//server/share/foo.txt"), Some("foo.txt")),
(Path::new(r"\\?\bar"), None),
(Path::new(r"\\?\bar\foo.txt"), Some("foo.txt")),
(Path::new(r"\\?\C:/foo/bar"), Some("foo/bar")),
(Path::new(r"\\?\C:/foo/bar"), None),
(Path::new(r"\\.\device"), None),
(Path::new(r"\\.\device\foo.txt"), Some("foo.txt")),
];
for (path, filename) in windows_paths_and_filenames {
assert_eq!(PathStyle::Windows.file_name(path), filename);
assert_eq!(PathStyle::Windows.file_name(path), filename.map(OsStr::new));
}
}
@@ -801,7 +781,7 @@ mod tests {
Some(r"\\?\UNC\server\share\"),
),
(r"\\?\C:\foo.txt", Some(r"\\?\C:\")),
(r"\\?\C:/foo/bar", Some(r"\\?\C:/")),
(r"\\?\C:/foo/bar", None),
(r"\\.\device", None),
(r"\\.\device\foo.txt", Some(r"\\.\device\")),
(".", Some("")),
@@ -823,16 +803,22 @@ mod tests {
use std::os::unix::ffi::OsStrExt;
let path = Path::new(OsStr::from_bytes(b"/home/user/\xff\xfe/repo/file.txt"));
assert_eq!(PathStyle::Unix.file_name(path), Some("file.txt"));
assert_eq!(
PathStyle::Unix.file_name(path),
Some(OsStr::new("file.txt"))
);
assert_eq!(
PathStyle::Unix.parent(path),
Some(Path::new(OsStr::from_bytes(b"/home/user/\xff\xfe/repo")))
);
let invalid_filename_path = Path::new(OsStr::from_bytes(b"/home/user/repo/\xff\xfe.txt"));
assert_eq!(PathStyle::Unix.file_name(invalid_filename_path), None);
let another_path = Path::new(OsStr::from_bytes(b"/home/user/repo/\xff\xfe.txt"));
assert_eq!(
PathStyle::Unix.parent(invalid_filename_path),
PathStyle::Unix.file_name(another_path),
Some(OsStr::from_bytes(b"\xff\xfe.txt"))
);
assert_eq!(
PathStyle::Unix.parent(another_path),
Some(Path::new("/home/user/repo"))
);
}
@@ -851,8 +837,14 @@ mod tests {
let os_str = OsString::from_wide(&wide);
let path = Path::new(&os_str);
assert_eq!(PathStyle::Windows.file_name(path), Some("file.txt"));
assert_eq!(
PathStyle::Windows.file_name(path),
Some(OsStr::new("file.txt"))
);
let parent = PathStyle::Windows.parent(path).unwrap();
assert_eq!(PathStyle::Windows.file_name(parent), Some("repo"));
assert_eq!(
PathStyle::Windows.file_name(parent),
Some(OsStr::new("repo"))
);
}
}
+449
View File
@@ -0,0 +1,449 @@
//! Path component parsing adapted from the Rust standard library
//! (`std::path::Components` in rust-lang/rust's `library/std/src/path.rs`,
//! revision 315ecf4a9).
//!
//! The code is largely a copy of upstream; the only notable changes are
//! `PathStyle`-related: the `cfg(windows)`/`cfg(unix)` branches are replaced
//! with runtime checks on [`PathStyle`], and helpers that `std` defines as
//! private inherent methods on `Prefix` live in the local [`PrefixExt`] trait.
use crate::PathStyle;
use std::ffi::OsStr;
use std::path::Path;
pub use std::path::Prefix;
pub(crate) trait PrefixExt {
fn len(&self) -> usize;
fn is_drive(&self) -> bool;
#[inline]
fn has_implicit_root(&self) -> bool {
!self.is_drive()
}
}
impl PrefixExt for Prefix<'_> {
#[inline]
fn len(&self) -> usize {
use self::Prefix::*;
fn os_str_len(s: &OsStr) -> usize {
s.as_encoded_bytes().len()
}
match *self {
Verbatim(x) => 4 + os_str_len(x),
VerbatimUNC(x, y) => {
8 + os_str_len(x)
+ if os_str_len(y) > 0 {
1 + os_str_len(y)
} else {
0
}
}
VerbatimDisk(_) => 6,
UNC(x, y) => {
2 + os_str_len(x)
+ if os_str_len(y) > 0 {
1 + os_str_len(y)
} else {
0
}
}
DeviceNS(x) => 4 + os_str_len(x),
Disk(_) => 2,
}
}
#[inline]
fn is_drive(&self) -> bool {
matches!(*self, Prefix::Disk(_))
}
}
// Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
// is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
// `iter` after having exhausted `prefix`.
pub(crate) fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
where
I: Iterator<Item = Component<'a>> + Clone,
J: Iterator<Item = Component<'b>>,
{
loop {
let mut iter_next = iter.clone();
match (iter_next.next(), prefix.next()) {
(Some(ref x), Some(ref y)) if x == y => (),
(Some(_), Some(_)) => return None,
(Some(_), None) => return Some(iter),
(None, None) => return Some(iter),
(None, Some(_)) => return None,
}
iter = iter_next;
}
}
#[derive(PartialEq, PartialOrd, Clone)]
enum State {
Prefix = 0, // c:
StartDir = 1, // / or . or nothing
Body = 2, // foo/bar/baz
Done = 3,
}
#[allow(dead_code)]
pub(crate) struct PrefixComponent<'a> {
/// The prefix as an unparsed `OsStr` slice.
raw: &'a OsStr,
/// The parsed prefix data.
parsed: Prefix<'a>,
}
impl<'a> PartialEq for PrefixComponent<'a> {
#[inline]
fn eq(&self, other: &PrefixComponent<'a>) -> bool {
self.parsed == other.parsed
}
}
#[derive(PartialEq)]
pub(crate) enum Component<'a> {
/// A Windows path prefix, e.g., `C:` or `\\server\share`.
///
/// There is a large variety of prefix types, see [`Prefix`]'s documentation
/// for more.
///
/// Does not occur on Unix.
Prefix(PrefixComponent<'a>),
/// The root directory component, appears after any prefix and before anything else.
///
/// It represents a separator that designates that a path starts from root.
RootDir,
/// A reference to the current directory, i.e., `.`.
CurDir,
/// A reference to the parent directory, i.e., `..`.
ParentDir,
/// A normal component, e.g., `a` and `b` in `a/b`.
///
/// This variant is the most common one, it represents references to files
/// or directories.
Normal(&'a OsStr),
}
#[derive(Clone)]
pub(crate) struct Components<'a> {
path_style: PathStyle,
// The path left to parse components from
path: &'a [u8],
// The prefix as it was originally parsed, if any
prefix: Option<Prefix<'a>>,
// true if path *physically* has a root separator; for most Windows
// prefixes, it may have a "logical" root separator for the purposes of
// normalization, e.g., \\server\share == \\server\share\.
has_physical_root: bool,
// The iterator is double-ended, and these two states keep track of what has
// been produced from either end
front: State,
back: State,
}
impl<'a> Components<'a> {
pub fn new(path_style: PathStyle, path: &'a Path) -> Self {
let prefix = path_style.parse_prefix(path.as_os_str());
Components {
path_style,
path: path.as_os_str().as_encoded_bytes(),
prefix,
has_physical_root: path_style
.has_physical_root(path.as_os_str().as_encoded_bytes(), prefix),
// use a platform-specific initial state to avoid one turn of
// the state-machine when the platform doesn't have a Prefix.
front: if path_style.has_prefixes() {
State::Prefix
} else {
State::StartDir
},
back: State::Body,
}
}
fn has_prefixes(&self) -> bool {
self.path_style.has_prefixes()
}
#[inline]
fn prefix_len(&self) -> usize {
if !self.has_prefixes() {
return 0;
}
self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
}
#[inline]
fn prefix_verbatim(&self) -> bool {
if !self.has_prefixes() {
return false;
}
self.prefix
.as_ref()
.map(Prefix::is_verbatim)
.unwrap_or(false)
}
#[inline]
fn prefix_remaining(&self) -> usize {
if !self.has_prefixes() {
return 0;
}
if self.front == State::Prefix {
self.prefix_len()
} else {
0
}
}
#[inline]
fn len_before_body(&self) -> usize {
let root = if self.front <= State::StartDir && self.has_physical_root {
1
} else {
0
};
let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
1
} else {
0
};
self.prefix_remaining() + root + cur_dir
}
#[inline]
fn finished(&self) -> bool {
self.front == State::Done || self.back == State::Done || self.front > self.back
}
#[inline]
fn is_sep_byte(&self, b: u8) -> bool {
if self.prefix_verbatim() {
self.path_style.is_verbatim_sep(b)
} else {
self.path_style.is_sep_byte(b)
}
}
pub fn as_path(&self) -> &'a Path {
let mut comps = self.clone();
if comps.front == State::Body {
comps.trim_left();
}
if comps.back == State::Body {
comps.trim_right();
}
unsafe { Path::new(OsStr::from_encoded_bytes_unchecked(comps.path)) }
}
fn has_root(&self) -> bool {
if self.has_physical_root {
return true;
}
if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() {
return true;
}
}
false
}
fn include_cur_dir(&self) -> bool {
if self.has_root() {
return false;
}
let slice = &self.path[self.prefix_remaining()..];
match slice {
[b'.'] => true,
[b'.', b, ..] => self.is_sep_byte(*b),
_ => false,
}
}
unsafe fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
match comp {
b"." if self.has_prefixes() && self.prefix_verbatim() => Some(Component::CurDir),
b"." => None, // . components are normalized away, except at
// the beginning of a path, which is treated
// separately via `include_cur_dir`
b".." => Some(Component::ParentDir),
b"" => None,
_ => Some(Component::Normal(unsafe {
OsStr::from_encoded_bytes_unchecked(comp)
})),
}
}
fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.front == State::Body);
let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
None => (0, self.path),
Some(i) => (1, &self.path[..i]),
};
// SAFETY: `comp` is a valid substring, since it is split on a separator.
(comp.len() + extra, unsafe {
self.parse_single_component(comp)
})
}
fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.back == State::Body);
let start = self.len_before_body();
let (extra, comp) = match self.path[start..]
.iter()
.rposition(|b| self.is_sep_byte(*b))
{
None => (0, &self.path[start..]),
Some(i) => (1, &self.path[start + i + 1..]),
};
// SAFETY: `comp` is a valid substring, since it is split on a separator.
(comp.len() + extra, unsafe {
self.parse_single_component(comp)
})
}
fn trim_left(&mut self) {
while !self.path.is_empty() {
let (size, comp) = self.parse_next_component();
if comp.is_some() {
return;
} else {
self.path = &self.path[size..];
}
}
}
fn trim_right(&mut self) {
while self.path.len() > self.len_before_body() {
let (size, comp) = self.parse_next_component_back();
if comp.is_some() {
return;
} else {
self.path = &self.path[..self.path.len() - size];
}
}
}
}
impl<'a> Iterator for Components<'a> {
type Item = Component<'a>;
fn next(&mut self) -> Option<Component<'a>> {
while !self.finished() {
match self.front {
// most likely case first
State::Body if !self.path.is_empty() => {
let (size, comp) = self.parse_next_component();
self.path = &self.path[size..];
if comp.is_some() {
return comp;
}
}
State::Body => {
self.front = State::Done;
}
State::StartDir => {
self.front = State::Body;
if self.has_physical_root {
debug_assert!(!self.path.is_empty());
self.path = &self.path[1..];
return Some(Component::RootDir);
} else if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() && !p.is_verbatim() {
return Some(Component::RootDir);
}
} else if self.include_cur_dir() {
debug_assert!(!self.path.is_empty());
self.path = &self.path[1..];
return Some(Component::CurDir);
}
}
_ if !self.has_prefixes() => unreachable!(),
State::Prefix if self.prefix_len() == 0 => {
self.front = State::StartDir;
}
State::Prefix => {
self.front = State::StartDir;
debug_assert!(self.prefix_len() <= self.path.len());
let raw = &self.path[..self.prefix_len()];
self.path = &self.path[self.prefix_len()..];
return Some(Component::Prefix(PrefixComponent {
raw: unsafe { OsStr::from_encoded_bytes_unchecked(raw) },
parsed: self.prefix.unwrap(),
}));
}
State::Done => unreachable!(),
}
}
None
}
}
impl<'a> DoubleEndedIterator for Components<'a> {
fn next_back(&mut self) -> Option<Component<'a>> {
while !self.finished() {
match self.back {
State::Body if self.path.len() > self.len_before_body() => {
let (size, comp) = self.parse_next_component_back();
self.path = &self.path[..self.path.len() - size];
if comp.is_some() {
return comp;
}
}
State::Body => {
self.back = State::StartDir;
}
State::StartDir => {
self.back = if self.has_prefixes() {
State::Prefix
} else {
State::Done
};
if self.has_physical_root {
self.path = &self.path[..self.path.len() - 1];
return Some(Component::RootDir);
} else if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() && !p.is_verbatim() {
return Some(Component::RootDir);
}
} else if self.include_cur_dir() {
self.path = &self.path[..self.path.len() - 1];
return Some(Component::CurDir);
}
}
_ if !self.has_prefixes() => unreachable!(),
State::Prefix if self.prefix_len() > 0 => {
self.back = State::Done;
return Some(Component::Prefix(PrefixComponent {
raw: unsafe { OsStr::from_encoded_bytes_unchecked(self.path) },
parsed: self.prefix.unwrap(),
}));
}
State::Prefix => {
self.back = State::Done;
return None;
}
State::Done => unreachable!(),
}
}
None
}
}
+212
View File
@@ -0,0 +1,212 @@
//! Windows prefix parsing adapted from the Rust standard library
//! (rust-lang/rust's `library/std/src/sys/path/windows_prefix.rs`, revision
//! 315ecf4a9).
//!
//! The code is a near-verbatim copy of upstream; the only notable changes are
//! `PathStyle`-related: the separator helpers delegate to [`PathStyle::Windows`].
use crate::PathStyle;
use std::ffi::OsStr;
use std::path::Prefix;
struct PrefixParser<'a, const LEN: usize> {
path: &'a OsStr,
prefix: [u8; LEN],
}
impl<'a, const LEN: usize> PrefixParser<'a, LEN> {
#[inline]
fn get_prefix(path: &OsStr) -> [u8; LEN] {
let mut prefix = [0; LEN];
// SAFETY: Only ASCII characters are modified.
for (i, &ch) in path.as_encoded_bytes().iter().take(LEN).enumerate() {
prefix[i] = if ch == b'/' { b'\\' } else { ch };
}
prefix
}
fn new(path: &'a OsStr) -> Self {
Self {
path,
prefix: Self::get_prefix(path),
}
}
fn as_slice(&self) -> PrefixParserSlice<'a, '_> {
PrefixParserSlice {
path: self.path,
prefix: &self.prefix[..LEN.min(self.path.len())],
index: 0,
}
}
}
struct PrefixParserSlice<'a, 'b> {
path: &'a OsStr,
prefix: &'b [u8],
index: usize,
}
impl<'a> PrefixParserSlice<'a, '_> {
fn strip_prefix(&self, prefix: &str) -> Option<Self> {
self.prefix[self.index..]
.starts_with(prefix.as_bytes())
.then_some(Self {
index: self.index + prefix.len(),
..*self
})
}
fn prefix_bytes(&self) -> &'a [u8] {
&self.path.as_encoded_bytes()[..self.index]
}
fn finish(self) -> &'a OsStr {
// SAFETY: The unsafety here stems from converting between &OsStr and
// &[u8] and back. This is safe to do because (1) we only look at ASCII
// contents of the encoding and (2) new &OsStr values are produced only
// from ASCII-bounded slices of existing &OsStr values.
unsafe { OsStr::from_encoded_bytes_unchecked(&self.path.as_encoded_bytes()[self.index..]) }
}
}
pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
use Prefix::{DeviceNS, Disk, UNC, Verbatim, VerbatimDisk, VerbatimUNC};
let parser = PrefixParser::<8>::new(path);
let parser = parser.as_slice();
if let Some(parser) = parser.strip_prefix(r"\\") {
// \\
// It's a POSIX path.
if cfg!(target_os = "cygwin") && !path.as_encoded_bytes().contains(&b'\\') {
return None;
}
// The meaning of verbatim paths can change when they use a different
// separator.
if let Some(parser) = parser.strip_prefix(r"?\")
// Cygwin allows `/` in verbatim paths.
&& (cfg!(target_os = "cygwin") || !parser.prefix_bytes().contains(&b'/'))
{
// \\?\
if let Some(parser) = parser.strip_prefix(r"UNC\") {
// \\?\UNC\server\share
let path = parser.finish();
let (server, path) = parse_next_component(path, true);
let (share, _) = parse_next_component(path, true);
Some(VerbatimUNC(server, share))
} else {
let path = parser.finish();
// in verbatim paths only recognize an exact drive prefix
if let Some(drive) = parse_drive_exact(path) {
// \\?\C:
Some(VerbatimDisk(drive))
} else {
// \\?\prefix
let (prefix, _) = parse_next_component(path, true);
Some(Verbatim(prefix))
}
}
} else if let Some(parser) = parser.strip_prefix(r".\") {
// \\.\COM42
let path = parser.finish();
let (prefix, _) = parse_next_component(path, false);
Some(DeviceNS(prefix))
} else {
let path = parser.finish();
let (server, path) = parse_next_component(path, false);
let (share, _) = parse_next_component(path, false);
if !server.is_empty() && !share.is_empty() {
// \\server\share
Some(UNC(server, share))
} else {
// no valid prefix beginning with "\\" recognized
None
}
}
} else {
// If it has a drive like `C:` then it's a disk.
// Otherwise there is no prefix.
Some(Disk(parse_drive(path)?))
}
}
// Parses a drive prefix, e.g. "C:" and "C:\whatever"
fn parse_drive(path: &OsStr) -> Option<u8> {
// In most DOS systems, it is not possible to have more than 26 drive letters.
// See <https://en.wikipedia.org/wiki/Drive_letter_assignment#Common_assignments>.
fn is_valid_drive_letter(drive: &u8) -> bool {
drive.is_ascii_alphabetic()
}
match path.as_encoded_bytes() {
[drive, b':', ..] if is_valid_drive_letter(drive) => Some(drive.to_ascii_uppercase()),
_ => None,
}
}
// Parses a drive prefix exactly, e.g. "C:"
fn parse_drive_exact(path: &OsStr) -> Option<u8> {
// only parse two bytes: the drive letter and the drive separator
if path
.as_encoded_bytes()
.get(2)
.map(|&x| is_verbatim_sep(x))
.unwrap_or(true)
{
parse_drive(path)
} else {
None
}
}
// Parse the next path component.
//
// Returns the next component and the rest of the path excluding the component and separator.
// Does not recognize `/` as a separator character on Windows if `verbatim` is true.
pub(crate) fn parse_next_component(path: &OsStr, verbatim: bool) -> (&OsStr, &OsStr) {
let separator = if verbatim {
is_verbatim_sep
} else {
is_sep_byte
};
match path.as_encoded_bytes().iter().position(|&x| separator(x)) {
Some(separator_start) => {
let separator_end = separator_start + 1;
let component = &path.as_encoded_bytes()[..separator_start];
// Panic safe
// The max `separator_end` is `bytes.len()` and `bytes[bytes.len()..]` is a valid index.
let path = &path.as_encoded_bytes()[separator_end..];
// SAFETY: `path` is a valid wtf8 encoded slice and each of the separators ('/', '\')
// is encoded in a single byte, therefore `bytes[separator_start]` and
// `bytes[separator_end]` must be code point boundaries and thus
// `bytes[..separator_start]` and `bytes[separator_end..]` are valid wtf8 slices.
unsafe {
(
OsStr::from_encoded_bytes_unchecked(component),
OsStr::from_encoded_bytes_unchecked(path),
)
}
}
None => (path, OsStr::new("")),
}
}
#[inline]
fn is_verbatim_sep(b: u8) -> bool {
PathStyle::Windows.is_verbatim_sep(b)
}
#[inline]
fn is_sep_byte(b: u8) -> bool {
PathStyle::Windows.is_sep_byte(b)
}
+1 -1
View File
@@ -10938,7 +10938,7 @@ async fn remove_empty_managed_worktree_ancestors(fs: &dyn Fs, child_path: &Path,
pub fn repo_identity_path(common_dir: &Path, path_style: PathStyle) -> &Path {
let is_dot_entry = path_style
.file_name(common_dir)
.is_some_and(|n| n.starts_with('.'));
.is_some_and(|n| n.to_string_lossy().starts_with('.'));
if is_dot_entry {
path_style.parent(common_dir).unwrap_or(common_dir)
} else {
+2 -2
View File
@@ -279,12 +279,12 @@ impl Render for TitleBar {
});
let display_name = if identity.extension() == Some(std::ffi::OsStr::new("git")) {
identity.file_stem().and_then(|n| n.to_str())
identity.file_stem()
} else {
repo.path_style.file_name(identity)
};
if let Some(repo_name) = display_name {
if let Some(repo_name) = display_name.and_then(|n| n.to_str()) {
let visible_worktrees_in_repo = self.visible_worktrees_in_repository(repo, cx);
let name = if visible_worktrees_in_repo == 1 {
if let Ok(relative) =