Skip to content

Commit e88a6cf

Browse files
bors[bot]danieldulaneyasomers
authored
Merge #1465
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 <[email protected]> Co-authored-by: Alan Somers <[email protected]>
2 parents 7033d47 + 7fd7f27 commit e88a6cf

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).
66
## [Unreleased] - ReleaseDate
77
### Added
88

9+
- Added `TimeSpec::from_duration` and `TimeSpec::from_timespec`
10+
(#[1465](https://github.com/nix-rust/nix/pull/1465))
11+
912
- Added `IPV6_V6ONLY` sockopt.
1013
(#[1470](https://github.com/nix-rust/nix/pull/1470))
1114

src/sys/time.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,7 @@ impl From<timespec> for TimeSpec {
7777

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

@@ -198,6 +194,18 @@ impl TimeSpec {
198194
pub fn tv_nsec(&self) -> timespec_tv_nsec_t {
199195
self.0.tv_nsec
200196
}
197+
198+
pub const fn from_duration(duration: Duration) -> Self {
199+
#[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
200+
TimeSpec(timespec {
201+
tv_sec: duration.as_secs() as time_t,
202+
tv_nsec: duration.subsec_nanos() as timespec_tv_nsec_t
203+
})
204+
}
205+
206+
pub const fn from_timespec(timespec: timespec) -> Self {
207+
Self(timespec)
208+
}
201209
}
202210

203211
impl ops::Neg for TimeSpec {

0 commit comments

Comments
 (0)