Skip to content

Commit

Permalink
Merge #1465
Browse files Browse the repository at this point in the history
1465: Enable creating a const TimeSpec r=asomers a=danieldulaney

Previously, there was no way to create a `TimeSpec` in a `const` context because all creation was through traits. This adds two utility functions to create a `const TimeSpec` from a `libc::timespec` or an `std::time::Duration`.

An alternative approach would be to make the inner `timespec` field `pub`, which would not require any additional functions but would expose some (potentially unwanted) implementation details.

Co-authored-by: Daniel Dulaney <dulaney.daniel@gmail.com>
Co-authored-by: Alan Somers <asomers@gmail.com>
  • Loading branch information
3 people authored Jul 24, 2021
2 parents 7033d47 + 7fd7f27 commit e88a6cf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased] - ReleaseDate
### Added

- Added `TimeSpec::from_duration` and `TimeSpec::from_timespec`
(#[1465](https://github.com/nix-rust/nix/pull/1465))

- Added `IPV6_V6ONLY` sockopt.
(#[1470](https://github.com/nix-rust/nix/pull/1470))

Expand Down
18 changes: 13 additions & 5 deletions src/sys/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,7 @@ impl From<timespec> for TimeSpec {

impl From<Duration> for TimeSpec {
fn from(duration: Duration) -> Self {
#[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
TimeSpec(timespec {
tv_sec: duration.as_secs() as time_t,
tv_nsec: duration.subsec_nanos() as timespec_tv_nsec_t
})
Self::from_duration(duration)
}
}

Expand Down Expand Up @@ -198,6 +194,18 @@ impl TimeSpec {
pub fn tv_nsec(&self) -> timespec_tv_nsec_t {
self.0.tv_nsec
}

pub const fn from_duration(duration: Duration) -> Self {
#[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
TimeSpec(timespec {
tv_sec: duration.as_secs() as time_t,
tv_nsec: duration.subsec_nanos() as timespec_tv_nsec_t
})
}

pub const fn from_timespec(timespec: timespec) -> Self {
Self(timespec)
}
}

impl ops::Neg for TimeSpec {
Expand Down

0 comments on commit e88a6cf

Please sign in to comment.