Skip to content

Commit

Permalink
Optimize metadata calls on Linux. (#367)
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
sunfishcode authored Sep 24, 2024
1 parent 76f3449 commit f68f260
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cap-primitives/src/rustix/linux/fs/stat_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,20 @@ pub(crate) fn stat_impl(
path: &Path,
follow: FollowSymlinks,
) -> io::Result<Metadata> {
use crate::fs::OpenOptionsExt;
use crate::fs::{stat_unchecked, OpenOptionsExt};
use std::path::Component;

// Optimization: if path has exactly one component and it's not ".." and
// we're not following symlinks we can go straight to `stat_unchecked`,
// which is faster than doing an open with a separate fstat.
if follow == FollowSymlinks::No {
let mut components = path.components();
if let Some(component) = components.next() {
if components.next().is_none() && component != Component::ParentDir {
return stat_unchecked(start, component.as_ref(), FollowSymlinks::No);
}
}
}

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

0 comments on commit f68f260

Please sign in to comment.