Skip to content

Commit f68f260

Browse files
authored
Optimize metadata calls on Linux. (#367)
Optimize `metadata` calls on Linux in the case where there's exactly one path component (and it isn't `..`) and symlinks are not being followed. In that case, we can just call `stat_unchecked` instead of doing an `openat2` followed by an `fstat`.
1 parent 76f3449 commit f68f260

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

cap-primitives/src/rustix/linux/fs/stat_impl.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,20 @@ pub(crate) fn stat_impl(
1515
path: &Path,
1616
follow: FollowSymlinks,
1717
) -> io::Result<Metadata> {
18-
use crate::fs::OpenOptionsExt;
18+
use crate::fs::{stat_unchecked, OpenOptionsExt};
19+
use std::path::Component;
20+
21+
// Optimization: if path has exactly one component and it's not ".." and
22+
// we're not following symlinks we can go straight to `stat_unchecked`,
23+
// which is faster than doing an open with a separate fstat.
24+
if follow == FollowSymlinks::No {
25+
let mut components = path.components();
26+
if let Some(component) = components.next() {
27+
if components.next().is_none() && component != Component::ParentDir {
28+
return stat_unchecked(start, component.as_ref(), FollowSymlinks::No);
29+
}
30+
}
31+
}
1932

2033
// Open the path with `O_PATH`. Use `read(true)` even though we don't need
2134
// `read` permissions, because Rust's libstd requires an access mode, and

0 commit comments

Comments
 (0)