Skip to content

Commit

Permalink
Add a wrapper for utimes(2)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmmv committed Sep 24, 2018
1 parent d302e8d commit 63b6851
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/sys/time.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use {NixPath, Result};
use errno::Errno;
use std::{cmp, fmt, ops};
use libc::{c_long, time_t, suseconds_t, timespec, timeval};
use libc::{self, c_long, time_t, suseconds_t, timespec, timeval};

pub trait TimeValLike: Sized {
#[inline]
Expand Down Expand Up @@ -494,6 +496,19 @@ fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
(this / other, this % other)
}

/// Change the times of the file at `path` to have the access and modification times set to
/// `atime` and `mtime` respectively (see
/// [utimes(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/utimes.html)).
#[inline]
pub fn utimes<P: ?Sized + NixPath>(path: &P, atime: &TimeVal, mtime: &TimeVal) -> Result<()> {
let times: [timeval; 2] = [*atime.as_ref(), *mtime.as_ref()];
let res = try!(path.with_nix_path(|cstr| {
unsafe { libc::utimes(cstr.as_ptr(), &times[0]) }
}));

Errno::result(res).map(drop)
}

#[cfg(test)]
mod test {
use super::{TimeSpec, TimeVal, TimeValLike};
Expand Down
1 change: 1 addition & 0 deletions test/sys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod test_select;
mod test_sysinfo;
mod test_termios;
mod test_ioctl;
mod test_time;
mod test_wait;
mod test_uio;

Expand Down
23 changes: 23 additions & 0 deletions test/sys/test_time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use nix::sys::time::*;
use std::fs::{self, File};
use std::time::{Duration, SystemTime};
use tempfile;

#[test]
fn test_utimes() {
let tempdir = tempfile::tempdir().unwrap();
let file = tempdir.path().join("file");
drop(File::create(&file).unwrap());

let atime = TimeVal::seconds(12345);
let mtime = TimeVal::seconds(678);
utimes(&file, &atime, &mtime).unwrap();

let attr = fs::symlink_metadata(&file).unwrap();
assert_eq!(
Duration::new(12345, 0),
attr.accessed().unwrap().duration_since(SystemTime::UNIX_EPOCH).unwrap());
assert_eq!(
Duration::new(678, 0),
attr.modified().unwrap().duration_since(SystemTime::UNIX_EPOCH).unwrap());
}

0 comments on commit 63b6851

Please sign in to comment.