1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#![deny(warnings)]
extern crate libc;
use std::ptr;
use std::time::Duration;
pub fn sleep(duration: Duration) -> Option<Duration> {
let ts = duration_to_timespec(duration);
let mut remain = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
#[cfg(target_os = "linux")] clock_nanosleep(libc::CLOCK_MONOTONIC, 0, &ts, Some(&mut remain));
#[cfg(target_os = "macos")] nanosleep(&ts, Some(&mut remain));
if remain.tv_nsec == 0 && remain.tv_sec == 0 {
return None;
}
Some(timespec_to_duration(remain))
}
fn duration_to_timespec(duration: Duration) -> libc::timespec {
libc::timespec {
tv_sec: duration.as_secs() as libc::time_t,
tv_nsec: duration.subsec_nanos() as libc::c_long,
}
}
fn timespec_to_duration(timespec: libc::timespec) -> Duration {
Duration::new(timespec.tv_sec as u64, timespec.tv_nsec as u32)
}
#[cfg(target_os = "linux")]
fn clock_nanosleep(
clk_id: libc::clockid_t,
flags: libc::c_int,
req: &libc::timespec,
remain: Option<&mut libc::timespec>,
) -> i32 {
match remain {
Some(p) => unsafe { libc::clock_nanosleep(clk_id, flags, req as *const _, p as *mut _) },
_ => unsafe { libc::clock_nanosleep(clk_id, flags, req as *const _, ptr::null_mut()) },
}
}
#[cfg(target_os = "macos")]
fn nanosleep(req: &libc::timespec, remain: Option<&mut libc::timespec>) -> i32 {
match remain {
Some(p) => unsafe { libc::nanosleep(req as *const _, p as *mut _) },
_ => unsafe { libc::nanosleep(req as *const _, ptr::null_mut()) },
}
}