Skip to content

Commit 6542a6c

Browse files
committed
Enable creating a const TimeSpec
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 a std::time::Duration
1 parent e493f83 commit 6542a6c

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

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)