Skip to main content

tokio/fs/
file_times.rs

1use std::time::SystemTime;
2
3#[cfg(target_vendor = "apple")]
4use std::os::darwin::fs::FileTimesExt;
5#[cfg(windows)]
6use std::os::windows::fs::FileTimesExt;
7
8/// Timestamps for a file.
9///
10/// This is a specialized version of [`std::fs::FileTimes`] for usage with
11/// [`File::set_times`](crate::fs::File::set_times). Unlike the standard library version,
12/// this type records the timestamps itself, so a future `io-uring` file
13/// implementation can consume them without converting through the standard
14/// library type.
15///
16/// # Examples
17///
18/// ```no_run
19/// use tokio::fs::FileTimes;
20///
21/// # async fn dox() -> std::io::Result<()> {
22/// let times = FileTimes::new()
23///     .set_accessed(std::time::SystemTime::now())
24///     .set_modified(std::time::SystemTime::now());
25/// # Ok(())
26/// # }
27/// ```
28#[derive(Debug, Clone, Default)]
29#[must_use = "must be applied to a file via `File::set_times` to have any effect"]
30pub struct FileTimes {
31    accessed: Option<SystemTime>,
32    modified: Option<SystemTime>,
33    #[cfg(any(windows, target_vendor = "apple"))]
34    created: Option<SystemTime>,
35}
36
37impl FileTimes {
38    /// Creates a new empty [`FileTimes`].
39    ///
40    /// Unset timestamps are left unchanged.
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// Sets the last access time.
46    pub fn set_accessed(mut self, t: SystemTime) -> Self {
47        self.accessed = Some(t);
48        self
49    }
50
51    /// Sets the last modification time.
52    pub fn set_modified(mut self, t: SystemTime) -> Self {
53        self.modified = Some(t);
54        self
55    }
56
57    /// Sets the creation time.
58    #[cfg(any(all(doc, docsrs), windows, target_vendor = "apple"))]
59    #[cfg_attr(docsrs, doc(cfg(any(windows, target_vendor = "apple"))))]
60    pub fn set_created(mut self, t: SystemTime) -> Self {
61        self.created = Some(t);
62        self
63    }
64
65    pub(crate) fn into_std(self) -> std::fs::FileTimes {
66        let mut std_times = std::fs::FileTimes::new();
67        if let Some(accessed) = self.accessed {
68            std_times = std_times.set_accessed(accessed);
69        }
70        if let Some(modified) = self.modified {
71            std_times = std_times.set_modified(modified);
72        }
73        #[cfg(any(windows, target_vendor = "apple"))]
74        if let Some(created) = self.created {
75            std_times = std_times.set_created(created);
76        }
77        std_times
78    }
79}