cap_primitives/rustix/fs/
times.rs

1use crate::fs::SystemTimeSpec;
2use crate::time::SystemClock;
3use io_lifetimes::BorrowedFd;
4use rustix::fs::{utimensat, AtFlags, Timestamps, UTIME_NOW, UTIME_OMIT};
5use rustix::time::Timespec;
6use std::path::Path;
7use std::{fs, io};
8
9#[allow(clippy::useless_conversion)]
10pub(crate) fn to_timespec(ft: Option<SystemTimeSpec>) -> io::Result<Timespec> {
11    Ok(match ft {
12        None => Timespec {
13            tv_sec: 0,
14            tv_nsec: UTIME_OMIT.into(),
15        },
16        Some(SystemTimeSpec::SymbolicNow) => Timespec {
17            tv_sec: 0,
18            tv_nsec: UTIME_NOW.into(),
19        },
20        Some(SystemTimeSpec::Absolute(ft)) => {
21            let duration = ft.duration_since(SystemClock::UNIX_EPOCH).unwrap();
22            let nanoseconds = duration.subsec_nanos();
23            assert_ne!(i64::from(nanoseconds), i64::from(UTIME_OMIT));
24            assert_ne!(i64::from(nanoseconds), i64::from(UTIME_NOW));
25            Timespec {
26                tv_sec: duration
27                    .as_secs()
28                    .try_into()
29                    .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?,
30                tv_nsec: nanoseconds.try_into().unwrap(),
31            }
32        }
33    })
34}
35
36#[allow(dead_code)]
37pub(crate) fn set_times_nofollow_unchecked(
38    start: &fs::File,
39    path: &Path,
40    atime: Option<SystemTimeSpec>,
41    mtime: Option<SystemTimeSpec>,
42) -> io::Result<()> {
43    let times = Timestamps {
44        last_access: to_timespec(atime)?,
45        last_modification: to_timespec(mtime)?,
46    };
47    Ok(utimensat(start, path, &times, AtFlags::SYMLINK_NOFOLLOW)?)
48}
49
50#[allow(dead_code)]
51pub(crate) fn set_times_follow_unchecked(
52    start: BorrowedFd<'_>,
53    path: &Path,
54    atime: Option<SystemTimeSpec>,
55    mtime: Option<SystemTimeSpec>,
56) -> io::Result<()> {
57    let times = Timestamps {
58        last_access: to_timespec(atime)?,
59        last_modification: to_timespec(mtime)?,
60    };
61    Ok(utimensat(start, path, &times, AtFlags::empty())?)
62}