Skip to content

Commit eb1159c

Browse files
authored
Rollup merge of #104901 - krtab:filetype_compare, r=the8472
Implement masking in FileType comparison on Unix Fixes: #104900
2 parents 1ce18d2 + 24cd863 commit eb1159c

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

library/std/src/fs/tests.rs

+16
Original file line numberDiff line numberDiff line change
@@ -1551,3 +1551,19 @@ fn hiberfil_sys() {
15511551
fs::metadata(hiberfil).unwrap();
15521552
assert_eq!(true, hiberfil.exists());
15531553
}
1554+
1555+
/// Test that two different ways of obtaining the FileType give the same result.
1556+
/// Cf. https://github.com/rust-lang/rust/issues/104900
1557+
#[test]
1558+
fn test_eq_direntry_metadata() {
1559+
let tmpdir = tmpdir();
1560+
let file_path = tmpdir.join("file");
1561+
File::create(file_path).unwrap();
1562+
for e in fs::read_dir(tmpdir.path()).unwrap() {
1563+
let e = e.unwrap();
1564+
let p = e.path();
1565+
let ft1 = e.file_type().unwrap();
1566+
let ft2 = p.metadata().unwrap().file_type();
1567+
assert_eq!(ft1, ft2);
1568+
}
1569+
}

library/std/src/sys/unix/fs.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,23 @@ pub struct FileTimes {
332332
modified: Option<SystemTime>,
333333
}
334334

335-
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
335+
#[derive(Copy, Clone, Eq, Debug)]
336336
pub struct FileType {
337337
mode: mode_t,
338338
}
339339

340+
impl PartialEq for FileType {
341+
fn eq(&self, other: &Self) -> bool {
342+
self.masked() == other.masked()
343+
}
344+
}
345+
346+
impl core::hash::Hash for FileType {
347+
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
348+
self.masked().hash(state);
349+
}
350+
}
351+
340352
#[derive(Debug)]
341353
pub struct DirBuilder {
342354
mode: mode_t,
@@ -548,7 +560,11 @@ impl FileType {
548560
}
549561

550562
pub fn is(&self, mode: mode_t) -> bool {
551-
self.mode & libc::S_IFMT == mode
563+
self.masked() == mode
564+
}
565+
566+
fn masked(&self) -> mode_t {
567+
self.mode & libc::S_IFMT
552568
}
553569
}
554570

0 commit comments

Comments
 (0)