Skip to main content

file_id/
lib.rs

1//! Utility for reading inode numbers (Linux, macOS) and file ids (Windows) that uniquely identify a file on a single computer.
2//!
3//! Modern file systems assign a unique ID to each file. On Linux and macOS it is called an `inode number`,
4//! on Windows it is called a `file id` or `file index`.
5//! Together with the `device id` (Linux, macOS) or the `volume serial number` (Windows),
6//! a file or directory can be uniquely identified on a single computer at a given time.
7//!
8//! Keep in mind though, that IDs may be re-used at some point.
9//!
10//! ## Example
11//!
12//! ```
13//! let file = tempfile::NamedTempFile::new().unwrap();
14//!
15//! let file_id = file_id::get_file_id(file.path()).unwrap();
16//! println!("{file_id:?}");
17//! ```
18//!
19//! ## Example (Windows Only)
20//!
21//! ```ignore
22//! let file = tempfile::NamedTempFile::new().unwrap();
23//!
24//! let file_id = file_id::get_low_res_file_id(file.path()).unwrap();
25//! println!("{file_id:?}");
26//!
27//! let file_id = file_id::get_high_res_file_id(file.path()).unwrap();
28//! println!("{file_id:?}");
29//! ```
30//!
31//! ## Example (Not Following Symlinks/Reparse Points)
32//!
33//! ```
34//! let file = tempfile::NamedTempFile::new().unwrap();
35//!
36//! // Get file ID without following symlinks
37//! let file_id = file_id::get_file_id_no_follow(file.path()).unwrap();
38//! println!("{file_id:?}");
39//! ```
40use std::{fs, io, path::Path};
41
42#[cfg(feature = "serde")]
43use serde::{Deserialize, Serialize};
44
45/// Unique identifier of a file
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
47#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
48pub enum FileId {
49    /// Inode number, available on Linux and macOS.
50    #[cfg_attr(feature = "serde", serde(rename = "inode"))]
51    Inode {
52        /// Device ID
53        #[cfg_attr(feature = "serde", serde(rename = "device"))]
54        device_id: u64,
55
56        /// Inode number
57        #[cfg_attr(feature = "serde", serde(rename = "inode"))]
58        inode_number: u64,
59    },
60
61    /// Low resolution file ID, available on Windows XP and above.
62    ///
63    /// Compared to the high resolution variant, only the lower parts of the IDs are stored.
64    ///
65    /// On Windows, the low resolution variant can be requested explicitly with the `get_low_res_file_id` function.
66    ///
67    /// Details: <https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle>.
68    #[cfg_attr(feature = "serde", serde(rename = "lowres"))]
69    LowRes {
70        /// Volume serial number
71        #[cfg_attr(feature = "serde", serde(rename = "volume"))]
72        volume_serial_number: u32,
73
74        /// File index
75        #[cfg_attr(feature = "serde", serde(rename = "index"))]
76        file_index: u64,
77    },
78
79    /// High resolution file ID, available on Windows Vista and above.
80    ///
81    /// On Windows, the high resolution variant can be requested explicitly with the `get_high_res_file_id` function.
82    ///
83    /// Details: <https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfileinformationbyhandleex>.
84    #[cfg_attr(feature = "serde", serde(rename = "highres"))]
85    HighRes {
86        /// Volume serial number
87        #[cfg_attr(feature = "serde", serde(rename = "volume"))]
88        volume_serial_number: u64,
89
90        /// File ID
91        #[cfg_attr(feature = "serde", serde(rename = "file"))]
92        file_id: u128,
93    },
94}
95
96impl FileId {
97    #[must_use]
98    pub fn new_inode(device_id: u64, inode_number: u64) -> Self {
99        FileId::Inode {
100            device_id,
101            inode_number,
102        }
103    }
104
105    #[must_use]
106    pub fn new_low_res(volume_serial_number: u32, file_index: u64) -> Self {
107        FileId::LowRes {
108            volume_serial_number,
109            file_index,
110        }
111    }
112
113    #[must_use]
114    pub fn new_high_res(volume_serial_number: u64, file_id: u128) -> Self {
115        FileId::HighRes {
116            volume_serial_number,
117            file_id,
118        }
119    }
120}
121
122impl AsRef<FileId> for FileId {
123    fn as_ref(&self) -> &FileId {
124        self
125    }
126}
127
128/// Get the `FileId` for the file or directory at `path`
129#[cfg(target_family = "unix")]
130pub fn get_file_id(path: impl AsRef<Path>) -> io::Result<FileId> {
131    use std::os::unix::fs::MetadataExt;
132
133    let metadata = fs::metadata(path.as_ref())?;
134
135    Ok(FileId::new_inode(metadata.dev(), metadata.ino()))
136}
137
138/// Get the `FileId` for the file or directory at `path` without following symlinks
139#[cfg(target_family = "unix")]
140pub fn get_file_id_no_follow(path: impl AsRef<Path>) -> io::Result<FileId> {
141    use std::os::unix::fs::MetadataExt;
142
143    let metadata = fs::symlink_metadata(path.as_ref())?;
144
145    Ok(FileId::new_inode(metadata.dev(), metadata.ino()))
146}
147
148/// Get the `FileId` for the file or directory at `path`
149#[cfg(target_family = "windows")]
150pub fn get_file_id(path: impl AsRef<Path>) -> io::Result<FileId> {
151    let file = open_file(path)?;
152
153    get_file_info_ex(&file).or_else(|_| get_file_info(&file))
154}
155
156/// Get the `FileId` for the file or directory at `path` without following symlinks/reparse points
157#[cfg(target_family = "windows")]
158pub fn get_file_id_no_follow(path: impl AsRef<Path>) -> io::Result<FileId> {
159    let file = open_file_no_follow(path)?;
160
161    get_file_info_ex(&file).or_else(|_| get_file_info(&file))
162}
163
164/// Get the `FileId` with the low resolution variant for the file or directory at `path`
165#[cfg(target_family = "windows")]
166pub fn get_low_res_file_id(path: impl AsRef<Path>) -> io::Result<FileId> {
167    let file = open_file(path)?;
168
169    get_file_info(&file)
170}
171
172/// Get the `FileId` with the low resolution variant for the file or directory at `path` without following symlinks/reparse points
173#[cfg(target_family = "windows")]
174pub fn get_low_res_file_id_no_follow(path: impl AsRef<Path>) -> io::Result<FileId> {
175    let file = open_file_no_follow(path)?;
176
177    get_file_info(&file)
178}
179
180/// Get the `FileId` with the high resolution variant for the file or directory at `path`
181#[cfg(target_family = "windows")]
182pub fn get_high_res_file_id(path: impl AsRef<Path>) -> io::Result<FileId> {
183    let file = open_file(path)?;
184
185    get_file_info_ex(&file)
186}
187
188/// Get the `FileId` with the high resolution variant for the file or directory at `path` without following symlinks/reparse points
189#[cfg(target_family = "windows")]
190pub fn get_high_res_file_id_no_follow(path: impl AsRef<Path>) -> io::Result<FileId> {
191    let file = open_file_no_follow(path)?;
192
193    get_file_info_ex(&file)
194}
195
196#[cfg(target_family = "windows")]
197fn get_file_info_ex(file: &fs::File) -> Result<FileId, io::Error> {
198    use std::{
199        mem::{self, MaybeUninit},
200        os::windows::prelude::*,
201    };
202    use windows_sys::Win32::Storage::FileSystem::{
203        FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx,
204    };
205
206    let mut info = MaybeUninit::<FILE_ID_INFO>::zeroed();
207    // SAFETY: the arguments are valid
208    // - hfile: must be a handle to a file
209    // - fileinformationclass: must be a value of `FILE_INFO_BY_HANDLE_CLASS` enum
210    // - lpfileinformation: must be a valid pointer to a struct corresponding to the `fileinformationclass`
211    // - dwbufferlength: must be the size of the struct passed to `lpfileinformation`
212    let ret = unsafe {
213        GetFileInformationByHandleEx(
214            file.as_raw_handle(),
215            FileIdInfo,
216            info.as_mut_ptr().cast(),
217            #[expect(clippy::cast_possible_truncation)]
218            {
219                mem::size_of::<FILE_ID_INFO>() as u32
220            },
221        )
222    };
223    if ret == 0 {
224        return Err(io::Error::last_os_error());
225    }
226
227    // SAFETY: `info` is initialized by `GetFileInformationByHandleEx`.
228    let info = unsafe { info.assume_init() };
229    Ok(FileId::new_high_res(
230        info.VolumeSerialNumber,
231        u128::from_le_bytes(info.FileId.Identifier),
232    ))
233}
234
235#[cfg(target_family = "windows")]
236fn get_file_info(file: &fs::File) -> Result<FileId, io::Error> {
237    use std::{mem::MaybeUninit, os::windows::prelude::*};
238    use windows_sys::Win32::Storage::FileSystem::{
239        BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
240    };
241
242    let mut info = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::zeroed();
243    // SAFETY: the arguments are valid
244    // - hfile: must be a handle to a file
245    // - lpfileinformation: must be a valid pointer to a `BY_HANDLE_FILE_INFORMATION
246    let ret = unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) };
247    if ret == 0 {
248        return Err(io::Error::last_os_error());
249    }
250
251    // SAFETY: `info` is initialized by `GetFileInformationByHandle`.
252    let info = unsafe { info.assume_init() };
253    Ok(FileId::new_low_res(
254        info.dwVolumeSerialNumber,
255        (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
256    ))
257}
258
259#[cfg(target_family = "windows")]
260fn open_file<P: AsRef<Path>>(path: P) -> io::Result<fs::File> {
261    use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt};
262    use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
263
264    OpenOptions::new()
265        .access_mode(0)
266        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
267        .open(path)
268}
269
270#[cfg(target_family = "windows")]
271fn open_file_no_follow<P: AsRef<Path>>(path: P) -> io::Result<fs::File> {
272    use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt};
273    use windows_sys::Win32::Storage::FileSystem::{
274        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
275    };
276
277    OpenOptions::new()
278        .access_mode(0)
279        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
280        .open(path)
281}