1use std::fs::File;
8use std::io;
9
10#[cfg(windows)]
11mod windows;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub struct FileId {
18 kind: Kind,
19 volume: u64,
20 file: u128,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24enum Kind {
25 #[cfg(unix)]
26 Unix,
27 #[cfg(windows)]
28 FileIdInfo,
29 #[cfg(windows)]
30 FileIndex,
31}
32
33impl FileId {
34 pub fn of(file: &File) -> io::Result<Self> {
37 read(file)
38 }
39}
40
41#[cfg(unix)]
42fn read(file: &File) -> io::Result<FileId> {
43 use std::os::unix::fs::MetadataExt as _;
44 let metadata = file.metadata()?;
45 Ok(FileId {
46 kind: Kind::Unix,
47 volume: metadata.dev(),
48 file: u128::from(metadata.ino()),
49 })
50}
51
52#[cfg(windows)]
53fn read(file: &File) -> io::Result<FileId> {
54 windows::file_id(file)
55}
56
57#[cfg(not(any(unix, windows)))]
58fn read(_file: &File) -> io::Result<FileId> {
59 Err(io::Error::new(
60 io::ErrorKind::Unsupported,
61 "file identity is unsupported",
62 ))
63}
64
65#[cfg(test)]
66mod tests {
67 use super::FileId;
68 use std::fs::File;
69 use std::path::Path;
70
71 fn id(path: &Path) -> FileId {
72 FileId::of(&File::open(path).expect("open")).expect("file id")
73 }
74
75 #[test]
76 fn same_path_read_twice_has_the_same_id() {
77 let dir = tempfile::tempdir().expect("tempdir");
78 let path = dir.path().join("source");
79 std::fs::write(&path, b"bytes").expect("write");
80 assert_eq!(id(&path), id(&path));
81 }
82
83 #[test]
84 fn in_place_rewrite_keeps_the_id() {
85 let dir = tempfile::tempdir().expect("tempdir");
86 let path = dir.path().join("source");
87 std::fs::write(&path, b"bytes").expect("write");
88 let before = id(&path);
89 std::fs::write(&path, b"other bytes").expect("rewrite");
90 assert_eq!(before, id(&path));
91 }
92
93 #[test]
94 fn rename_over_with_identical_bytes_changes_the_id() {
95 let dir = tempfile::tempdir().expect("tempdir");
96 let path = dir.path().join("source");
97 let sibling = dir.path().join("replacement");
98 std::fs::write(&path, b"bytes").expect("write");
99 let before = id(&path);
100 std::fs::write(&sibling, b"bytes").expect("write sibling");
101 std::fs::rename(&sibling, &path).expect("rename");
102 assert_ne!(before, id(&path));
103 }
104
105 #[test]
106 fn different_files_have_different_ids() {
107 let dir = tempfile::tempdir().expect("tempdir");
108 let first = dir.path().join("first");
109 let second = dir.path().join("second");
110 std::fs::write(&first, b"bytes").expect("write");
111 std::fs::write(&second, b"bytes").expect("write");
112 assert_ne!(id(&first), id(&second));
113 }
114}