1//! `Timespec` and related types, which are used by multiple public API
2//! modules.
34#[cfg(not(fix_y2038))]
5use crate::backend::c;
67/// `struct timespec`
8#[cfg(not(fix_y2038))]
9pub type Timespec = c::timespec;
1011/// `struct timespec`
12#[cfg(fix_y2038)]
13#[derive(Debug, Clone, Copy)]
14#[repr(C)]
15pub struct Timespec {
16/// Seconds.
17pub tv_sec: Secs,
1819/// Nanoseconds. Must be less than 1_000_000_000.
20pub tv_nsec: Nsecs,
21}
2223/// A type for the `tv_sec` field of [`Timespec`].
24#[cfg(not(fix_y2038))]
25#[allow(deprecated)]
26pub type Secs = c::time_t;
2728/// A type for the `tv_sec` field of [`Timespec`].
29#[cfg(fix_y2038)]
30pub type Secs = i64;
3132/// A type for the `tv_sec` field of [`Timespec`].
33#[cfg(any(
34 fix_y2038,
35 linux_raw,
36 all(libc, target_arch = "x86_64", target_pointer_width = "32")
37))]
38pub type Nsecs = i64;
3940/// A type for the `tv_nsec` field of [`Timespec`].
41#[cfg(all(
42 not(fix_y2038),
43 libc,
44 not(all(target_arch = "x86_64", target_pointer_width = "32"))
45))]
46pub type Nsecs = c::c_long;
4748/// On 32-bit glibc platforms, `timespec` has anonymous padding fields, which
49/// Rust doesn't support yet (see `unnamed_fields`), so we define our own
50/// struct with explicit padding, with bidirectional `From` impls.
51#[cfg(fix_y2038)]
52#[repr(C)]
53#[derive(Debug, Clone)]
54pub(crate) struct LibcTimespec {
55pub(crate) tv_sec: Secs,
5657#[cfg(target_endian = "big")]
58padding: core::mem::MaybeUninit<u32>,
5960pub(crate) tv_nsec: i32,
6162#[cfg(target_endian = "little")]
63padding: core::mem::MaybeUninit<u32>,
64}
6566#[cfg(fix_y2038)]
67impl From<LibcTimespec> for Timespec {
68#[inline]
69fn from(t: LibcTimespec) -> Self {
70Self {
71 tv_sec: t.tv_sec,
72 tv_nsec: t.tv_nsec as _,
73 }
74 }
75}
7677#[cfg(fix_y2038)]
78impl From<Timespec> for LibcTimespec {
79#[inline]
80fn from(t: Timespec) -> Self {
81Self {
82 tv_sec: t.tv_sec,
83 tv_nsec: t.tv_nsec as _,
84 padding: core::mem::MaybeUninit::uninit(),
85 }
86 }
87}
8889#[test]
90fn test_sizes() {
91assert_eq_size!(Secs, u64);
92const_assert!(core::mem::size_of::<Timespec>() >= core::mem::size_of::<(u64, u32)>());
93const_assert!(core::mem::size_of::<Nsecs>() >= 4);
9495let mut t = Timespec {
96 tv_sec: 0,
97 tv_nsec: 0,
98 };
99100// `tv_nsec` needs to be able to hold nanoseconds up to a second.
101t.tv_nsec = 999_999_999_u32 as _;
102assert_eq!(t.tv_nsec as u64, 999_999_999_u64);
103104// `tv_sec` needs to be able to hold more than 32-bits of seconds.
105t.tv_sec = 0x1_0000_0000_u64 as _;
106assert_eq!(t.tv_sec as u64, 0x1_0000_0000_u64);
107}
108109// Test that our workarounds are needed.
110#[cfg(fix_y2038)]
111#[test]
112#[allow(deprecated)]
113fn test_fix_y2038() {
114assert_eq_size!(libc::time_t, u32);
115}