Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement masking in FileType comparison on Unix #104901

Merged
merged 4 commits into from
Dec 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions library/std/src/fs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1551,3 +1551,19 @@ fn hiberfil_sys() {
fs::metadata(hiberfil).unwrap();
assert_eq!(true, hiberfil.exists());
}

/// Test that two different ways of obtaining the FileType give the same result.
/// Cf. https://github.com/rust-lang/rust/issues/104900
#[test]
fn test_eq_direntry_metadata() {
let tmpdir = tmpdir();
let file_path = tmpdir.join("file");
File::create(file_path).unwrap();
for e in fs::read_dir(tmpdir.path()).unwrap() {
let e = e.unwrap();
let p = e.path();
let ft1 = e.file_type().unwrap();
let ft2 = p.metadata().unwrap().file_type();
assert_eq!(ft1, ft2);
}
}
20 changes: 18 additions & 2 deletions library/std/src/sys/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,11 +332,23 @@ pub struct FileTimes {
modified: Option<SystemTime>,
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[derive(Copy, Clone, Eq, Debug)]
pub struct FileType {
mode: mode_t,
}

impl PartialEq for FileType {
fn eq(&self, other: &Self) -> bool {
self.masked() == other.masked()
}
}

impl core::hash::Hash for FileType {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.masked().hash(state);
}
}

#[derive(Debug)]
pub struct DirBuilder {
mode: mode_t,
Expand Down Expand Up @@ -548,7 +560,11 @@ impl FileType {
}

pub fn is(&self, mode: mode_t) -> bool {
self.mode & libc::S_IFMT == mode
self.masked() == mode
}

fn masked(&self) -> mode_t {
self.mode & libc::S_IFMT
}
}

Expand Down