Debian Codegraph @

debian/rust-vendor/nix/src/time.rs

raw
1 //! Sleep, query system clocks, and set system clock
2 use crate::sys::time::TimeSpec;
3 #[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))]
4 #[cfg(feature = "process")]
5 use crate::unistd::Pid;
6 use crate::{Errno, Result};
7 use libc::{self, clockid_t};
8 use std::mem::MaybeUninit;
9
10 /// Clock identifier
11 ///
12 /// Newtype pattern around [`libc::clockid_t`].
13 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
14 pub struct ClockId(clockid_t);
15
16 impl ClockId {
17 /// Creates `ClockId` from raw `clockid_t`
18 pub const fn from_raw(clk_id: clockid_t) -> Self {
19 ClockId(clk_id)
20 }
21
22 feature! {
23 #![feature = "process"]
24 /// Returns `ClockId` of a `pid` CPU-time clock
25 #[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))]
26 pub fn pid_cpu_clock_id(pid: Pid) -> Result<Self> {
27 clock_getcpuclockid(pid)
28 }
29 }
30
31 /// Returns resolution of the clock id
32 #[cfg(not(target_os = "redox"))]
33 pub fn res(self) -> Result<TimeSpec> {
34 clock_getres(self)
35 }
36
37 /// Returns the current time on the clock id
38 pub fn now(self) -> Result<TimeSpec> {
39 clock_gettime(self)
40 }
41
42 /// Sets time to `timespec` on the clock id
43 #[cfg(not(any(
44 target_os = "ios",
45 target_os = "tvos",
46 target_os = "watchos",
47 target_os = "redox",
48 target_os = "hermit"
49 )))]
50 pub fn set_time(self, timespec: TimeSpec) -> Result<()> {
51 clock_settime(self, timespec)
52 }
53
54 /// Gets the raw `clockid_t` wrapped by `self`
55 pub const fn as_raw(self) -> clockid_t {
56 self.0
57 }
58
59 #[cfg(any(
60 linux_android,
61 target_os = "emscripten",
62 target_os = "freebsd",
63 target_os = "fuchsia",
64 target_os = "openbsd",
65 ))]
66 /// Starts at zero when the kernel boots and increments monotonically in SI seconds while the
67 /// machine is running.
68 pub const CLOCK_BOOTTIME: ClockId = ClockId(libc::CLOCK_BOOTTIME);
69 /// Like [`CLOCK_BOOTTIME`](ClockId::CLOCK_BOOTTIME), but will wake the system if it is
70 /// suspended..
71 #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))]
72 pub const CLOCK_BOOTTIME_ALARM: ClockId =
73 ClockId(libc::CLOCK_BOOTTIME_ALARM);
74 /// Increments in SI seconds.
75 pub const CLOCK_MONOTONIC: ClockId = ClockId(libc::CLOCK_MONOTONIC);
76 /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for execution time at the expense of accuracy.
77 #[cfg(any(
78 linux_android,
79 target_os = "emscripten",
80 target_os = "freebsd",
81 target_os = "fuchsia"
82 ))]
83 pub const CLOCK_MONOTONIC_COARSE: ClockId =
84 ClockId(libc::CLOCK_MONOTONIC_COARSE);
85 #[cfg(freebsdlike)]
86 /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for execution time at the expense of accuracy.
87 pub const CLOCK_MONOTONIC_FAST: ClockId =
88 ClockId(libc::CLOCK_MONOTONIC_FAST);
89 #[cfg(freebsdlike)]
90 /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for accuracy at the expense of execution time.
91 pub const CLOCK_MONOTONIC_PRECISE: ClockId =
92 ClockId(libc::CLOCK_MONOTONIC_PRECISE);
93 /// Similar to [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but provides access to a raw
94 /// hardware-based time that is not subject to NTP adjustments.
95 #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))]
96 pub const CLOCK_MONOTONIC_RAW: ClockId = ClockId(libc::CLOCK_MONOTONIC_RAW);
97 #[cfg(any(
98 linux_android,
99 apple_targets,
100 freebsdlike,
101 netbsdlike,
102 target_os = "emscripten",
103 target_os = "fuchsia",
104 target_os = "redox",
105 ))]
106 /// Returns the execution time of the calling process.
107 pub const CLOCK_PROCESS_CPUTIME_ID: ClockId =
108 ClockId(libc::CLOCK_PROCESS_CPUTIME_ID);
109 #[cfg(freebsdlike)]
110 /// Increments when the CPU is running in user or kernel mode
111 pub const CLOCK_PROF: ClockId = ClockId(libc::CLOCK_PROF);
112 /// Increments as a wall clock should.
113 pub const CLOCK_REALTIME: ClockId = ClockId(libc::CLOCK_REALTIME);
114 /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but not settable.
115 #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))]
116 pub const CLOCK_REALTIME_ALARM: ClockId =
117 ClockId(libc::CLOCK_REALTIME_ALARM);
118 /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for execution time at the expense of accuracy.
119 #[cfg(any(
120 linux_android,
121 target_os = "emscripten",
122 target_os = "freebsd",
123 target_os = "fuchsia"
124 ))]
125 pub const CLOCK_REALTIME_COARSE: ClockId =
126 ClockId(libc::CLOCK_REALTIME_COARSE);
127 #[cfg(freebsdlike)]
128 /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for execution time at the expense of accuracy.
129 pub const CLOCK_REALTIME_FAST: ClockId = ClockId(libc::CLOCK_REALTIME_FAST);
130 #[cfg(freebsdlike)]
131 /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for accuracy at the expense of execution time.
132 pub const CLOCK_REALTIME_PRECISE: ClockId =
133 ClockId(libc::CLOCK_REALTIME_PRECISE);
134 #[cfg(freebsdlike)]
135 /// Returns the current second without performing a full time counter query, using an in-kernel
136 /// cached value of the current second.
137 pub const CLOCK_SECOND: ClockId = ClockId(libc::CLOCK_SECOND);
138 #[allow(missing_docs)] // Undocumented on Linux!
139 #[cfg(any(
140 target_os = "emscripten",
141 target_os = "fuchsia",
142 all(
143 target_os = "linux",
144 any(target_env = "musl", target_env = "ohos")
145 )
146 ))]
147 pub const CLOCK_SGI_CYCLE: ClockId = ClockId(libc::CLOCK_SGI_CYCLE);
148 /// International Atomic Time.
149 ///
150 /// A nonsettable system-wide clock derived from wall-clock time but ignoring leap seconds.
151 #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))]
152 pub const CLOCK_TAI: ClockId = ClockId(libc::CLOCK_TAI);
153 #[cfg(any(
154 linux_android,
155 apple_targets,
156 freebsdlike,
157 netbsdlike,
158 target_os = "emscripten",
159 target_os = "fuchsia",
160 ))]
161 /// Returns the execution time of the calling thread.
162 pub const CLOCK_THREAD_CPUTIME_ID: ClockId =
163 ClockId(libc::CLOCK_THREAD_CPUTIME_ID);
164 #[cfg(any(freebsdlike, target_os = "openbsd"))]
165 /// Starts at zero when the kernel boots and increments monotonically in SI seconds while the
166 /// machine is running.
167 pub const CLOCK_UPTIME: ClockId = ClockId(libc::CLOCK_UPTIME);
168 #[cfg(freebsdlike)]
169 /// Like [`CLOCK_UPTIME`](ClockId::CLOCK_UPTIME), but optimized for execution time at the expense of accuracy.
170 pub const CLOCK_UPTIME_FAST: ClockId = ClockId(libc::CLOCK_UPTIME_FAST);
171 #[cfg(freebsdlike)]
172 /// Like [`CLOCK_UPTIME`](ClockId::CLOCK_UPTIME), but optimized for accuracy at the expense of execution time.
173 pub const CLOCK_UPTIME_PRECISE: ClockId =
174 ClockId(libc::CLOCK_UPTIME_PRECISE);
175 #[cfg(freebsdlike)]
176 /// Increments only when the CPU is running in user mode on behalf of the calling process.
177 pub const CLOCK_VIRTUAL: ClockId = ClockId(libc::CLOCK_VIRTUAL);
178 }
179
180 impl From<ClockId> for clockid_t {
181 fn from(clock_id: ClockId) -> Self {
182 clock_id.as_raw()
183 }
184 }
185
186 impl From<clockid_t> for ClockId {
187 fn from(clk_id: clockid_t) -> Self {
188 ClockId::from_raw(clk_id)
189 }
190 }
191
192 impl std::fmt::Display for ClockId {
193 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
194 std::fmt::Display::fmt(&self.0, f)
195 }
196 }
197
198 /// Get the resolution of the specified clock, (see
199 /// [clock_getres(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_getres.html)).
200 #[cfg(not(target_os = "redox"))]
201 pub fn clock_getres(clock_id: ClockId) -> Result<TimeSpec> {
202 let mut c_time: MaybeUninit<libc::timespec> = MaybeUninit::uninit();
203 let ret =
204 unsafe { libc::clock_getres(clock_id.as_raw(), c_time.as_mut_ptr()) };
205 Errno::result(ret)?;
206 let res = unsafe { c_time.assume_init() };
207 Ok(TimeSpec::from(res))
208 }
209
210 /// Get the time of the specified clock, (see
211 /// [clock_gettime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_gettime.html)).
212 pub fn clock_gettime(clock_id: ClockId) -> Result<TimeSpec> {
213 let mut c_time: MaybeUninit<libc::timespec> = MaybeUninit::uninit();
214 let ret =
215 unsafe { libc::clock_gettime(clock_id.as_raw(), c_time.as_mut_ptr()) };
216 Errno::result(ret)?;
217 let res = unsafe { c_time.assume_init() };
218 Ok(TimeSpec::from(res))
219 }
220
221 /// Set the time of the specified clock, (see
222 /// [clock_settime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_settime.html)).
223 #[cfg(not(any(
224 target_os = "ios",
225 target_os = "tvos",
226 target_os = "watchos",
227 target_os = "redox",
228 target_os = "hermit"
229 )))]
230 pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> {
231 let ret =
232 unsafe { libc::clock_settime(clock_id.as_raw(), timespec.as_ref()) };
233 Errno::result(ret).map(drop)
234 }
235
236 /// Get the clock id of the specified process id, (see
237 /// [clock_getcpuclockid(3)](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_getcpuclockid.html)).
238 #[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))]
239 #[cfg(feature = "process")]
240 #[cfg_attr(docsrs, doc(cfg(feature = "process")))]
241 pub fn clock_getcpuclockid(pid: Pid) -> Result<ClockId> {
242 let mut clk_id: MaybeUninit<libc::clockid_t> = MaybeUninit::uninit();
243 let ret =
244 unsafe { libc::clock_getcpuclockid(pid.into(), clk_id.as_mut_ptr()) };
245 if ret == 0 {
246 let res = unsafe { clk_id.assume_init() };
247 Ok(ClockId::from(res))
248 } else {
249 Err(Errno::from_raw(ret))
250 }
251 }
252
253 #[cfg(any(
254 linux_android,
255 solarish,
256 freebsdlike,
257 target_os = "netbsd",
258 target_os = "hurd",
259 target_os = "aix"
260 ))]
261 libc_bitflags! {
262 /// Flags that are used for arming the timer.
263 pub struct ClockNanosleepFlags: libc::c_int {
264 /// Indicates that a requested time value should be treated as absolute instead of
265 /// relative.
266 TIMER_ABSTIME;
267 }
268 }
269
270 /// Suspend execution of this thread for the amount of time specified by `request`
271 /// and measured against the clock speficied by `clock_id`.
272 ///
273 /// If `flags` is [`TIMER_ABSTIME`](ClockNanosleepFlags::TIMER_ABSTIME), this function will suspend
274 /// execution until the time value of clock_id reaches the absolute time specified by `request`. If
275 /// a signal is caught by a signal-catching function, or a signal causes the process to terminate,
276 /// this sleep is interrrupted.
277 ///
278 /// see also [man 3 clock_nanosleep](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_nanosleep.html)
279 #[cfg(any(
280 linux_android,
281 solarish,
282 freebsdlike,
283 target_os = "netbsd",
284 target_os = "hurd",
285 target_os = "aix"
286 ))]
287 pub fn clock_nanosleep(
288 clock_id: ClockId,
289 flags: ClockNanosleepFlags,
290 request: &TimeSpec,
291 ) -> Result<TimeSpec> {
292 let mut remain = TimeSpec::new(0, 0);
293 let ret = unsafe {
294 libc::clock_nanosleep(
295 clock_id.as_raw(),
296 flags.bits(),
297 request.as_ref() as *const _,
298 remain.as_mut() as *mut _,
299 )
300 };
301 if ret == 0 {
302 Ok(remain)
303 } else {
304 Err(Errno::from_raw(ret))
305 }
306 }