Skip to content

Commit

Permalink
impl Clone for UnixClock
Browse files Browse the repository at this point in the history
  • Loading branch information
folkertdev committed Oct 4, 2023
1 parent fb717fa commit 470047c
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,21 @@ impl Drop for UnixClock {
}
}

impl Clone for UnixClock {
fn clone(&self) -> Self {
match self.fd {
Some(fd) => {
let new_fd = unsafe { libc::dup(fd) };
Self::safe_from_raw_fd(new_fd)
}
None => {
let clock = self.clock;
Self { clock, fd: None }
}
}
}
}

impl FromRawFd for UnixClock {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
Self::safe_from_raw_fd(fd)
Expand Down Expand Up @@ -870,4 +885,38 @@ mod tests {

assert_ne!(resolution, Timestamp::default());
}

#[cfg(target_os = "linux")]
fn is_valid_fd(fd: RawFd) -> bool {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };

// fd is valid if its flags are not -1
flags != -1
}

#[test]
#[cfg(target_os = "linux")]
fn test_clone_and_drop() {
use std::fs::File;

// make some fd that we can open
let path = std::env::temp_dir().join("clock-steering-test-clock");
File::create(&path).unwrap();

let clock = UnixClock::open(&path).unwrap();
let original_fd = clock.fd.unwrap();

let new_clock = clock.clone();
let new_fd = new_clock.fd.unwrap();

assert_ne!(original_fd, new_fd);

assert!(is_valid_fd(original_fd));
drop(clock);
assert!(!is_valid_fd(original_fd));

assert!(is_valid_fd(new_fd));
drop(new_clock);
assert!(!is_valid_fd(new_fd));
}
}

0 comments on commit 470047c

Please sign in to comment.