Skip to main content

tuwunel_core/utils/
time.rs

1//! Wall-clock conversion, parsing, and duration-formatting utilities.
2//!
3//! The helpers convert between `SystemTime` and the Unix epoch, parse
4//! human-readable durations, and choose display units. These clocks are not
5//! monotonic and can be affected by system-time changes.
6
7mod elapsed;
8pub mod exponential_backoff;
9
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12pub use elapsed::Elapsed;
13
14use crate::{Result, err};
15
16/// Returns the current wall-clock time as whole milliseconds since the Unix
17/// epoch.
18///
19/// The submillisecond remainder is discarded, and counts above `u64::MAX`
20/// retain only their low 64 bits. The function panics if the current system
21/// clock is earlier than the epoch.
22#[inline]
23#[must_use]
24#[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
25pub fn now_millis() -> u64 { now().as_millis() as u64 }
26
27/// Returns the current wall-clock time as whole seconds since the Unix epoch.
28///
29/// The subsecond remainder is discarded. The function panics if the current
30/// system clock is earlier than the epoch.
31#[inline]
32#[must_use]
33pub fn now_secs() -> u64 { now().as_secs() }
34
35/// Returns the current wall-clock duration since the Unix epoch.
36///
37/// The value comes from `SystemTime` and is not monotonic. The function panics
38/// if the current system clock is earlier than the epoch.
39#[inline]
40#[must_use]
41pub fn now() -> Duration {
42	UNIX_EPOCH
43		.elapsed()
44		.expect("positive duration after epoch")
45}
46
47/// Converts a system time into a nonnegative duration since the Unix epoch.
48///
49/// Times before the epoch saturate to [`Duration::ZERO`]. Times at or after the
50/// epoch preserve their full representable duration.
51#[inline]
52#[must_use]
53pub fn duration_since_epoch(timepoint: SystemTime) -> Duration {
54	timepoint
55		.duration_since(UNIX_EPOCH)
56		.unwrap_or(Duration::ZERO)
57}
58
59/// Converts a duration to whole milliseconds when they fit in a `u64`.
60///
61/// The submillisecond remainder is discarded; a count past `u64::MAX` gives
62/// `None` rather than truncating.
63#[inline]
64#[must_use]
65pub fn millis(duration: Duration) -> Option<u64> { duration.as_millis().try_into().ok() }
66
67/// Adds a duration to the Unix epoch using checked arithmetic.
68///
69/// The resulting system time is returned when representable. An arithmetic
70/// error is returned when the duration exceeds the platform's `SystemTime`
71/// range.
72#[inline]
73pub fn timepoint_from_epoch(duration: Duration) -> Result<SystemTime> {
74	UNIX_EPOCH
75		.checked_add(duration)
76		.ok_or_else(|| err!(Arithmetic("Duration {duration:?} from epoch is too large")))
77}
78
79/// Adds a duration to the current wall-clock time using checked arithmetic.
80///
81/// The current time is sampled once for the calculation. An arithmetic error is
82/// returned when the result exceeds the platform's `SystemTime` range.
83#[inline]
84pub fn timepoint_from_now(duration: Duration) -> Result<SystemTime> {
85	SystemTime::now()
86		.checked_add(duration)
87		.ok_or_else(|| err!(Arithmetic("Duration {duration:?} from now is too large")))
88}
89
90/// Subtracts a duration from the current wall-clock time using checked
91/// arithmetic.
92///
93/// The current time is sampled once for the calculation. An arithmetic error is
94/// returned when the result precedes the platform's `SystemTime` range.
95#[inline]
96pub fn timepoint_ago(duration: Duration) -> Result<SystemTime> {
97	SystemTime::now()
98		.checked_sub(duration)
99		.ok_or_else(|| err!(Arithmetic("Duration {duration:?} ago is too large")))
100}
101
102/// Parses a duration and returns the wall-clock time that far in the past.
103///
104/// Input syntax is delegated to [`parse_duration`]. Parsing and
105/// checked-subtraction errors are propagated.
106#[inline]
107pub fn parse_timepoint_ago(ago: &str) -> Result<SystemTime> {
108	timepoint_ago(parse_duration(ago)?)
109}
110
111/// Parses a human-readable duration with the `cyborgtime` parser.
112///
113/// Successful input is returned as a standard [`Duration`]. Parser failures are
114/// wrapped with the original input for context.
115#[inline]
116pub fn parse_duration(duration: &str) -> Result<Duration> {
117	cyborgtime::parse_duration(duration)
118		.map_err(|error| err!("'{duration:?}' is not a valid duration string: {error:?}"))
119}
120
121/// Checks whether an optional deadline has passed.
122///
123/// An absent deadline never passes.
124#[inline]
125#[must_use]
126pub fn deadline_has_passed(deadline: Option<SystemTime>) -> bool {
127	deadline.is_some_and(timepoint_has_passed)
128}
129
130/// Checks whether a system time is at or before the current wall-clock time.
131///
132/// Equality is considered passed. A time later than the sampled current time
133/// returns `false`.
134#[inline]
135#[must_use]
136pub fn timepoint_has_passed(timepoint: SystemTime) -> bool {
137	SystemTime::now()
138		.duration_since(timepoint)
139		.is_ok()
140}
141
142/// Formats a signed Unix timestamp as RFC 2822 text in UTC.
143///
144/// Timestamps outside Chrono's supported range use its default UTC date and
145/// time before formatting.
146#[must_use]
147pub fn rfc2822_from_seconds(epoch: i64) -> String {
148	use chrono::{DateTime, Utc};
149
150	DateTime::<Utc>::from_timestamp(epoch, 0)
151		.unwrap_or_default()
152		.to_rfc2822()
153}
154
155/// Formats a system time in UTC with a Chrono format string.
156///
157/// The pattern is passed to Chrono without modification. The rendered value is
158/// returned as an owned string.
159#[must_use]
160pub fn format(ts: SystemTime, str: &str) -> String {
161	use chrono::{DateTime, Utc};
162
163	let dt: DateTime<Utc> = ts.into();
164	dt.format(str).to_string()
165}
166
167/// Formats a duration with one plural human-readable unit.
168///
169/// The unit and scale component come from [`whole_and_frac`]. Output has the
170/// form `{whole}.{scaled} {unit}`, where `scaled` is the component multiplied
171/// by 100, truncated to an integer, and zero-padded to two digits.
172#[must_use]
173#[expect(
174	clippy::as_conversions,
175	clippy::cast_possible_truncation,
176	clippy::cast_sign_loss
177)]
178pub fn pretty(d: Duration) -> String {
179	use Unit::*;
180
181	let fmt = |w, f, u| format!("{w}.{f:02} {u}");
182	let gen64 = |w, f, u| fmt(w, (f * 100.0) as u32, u);
183	let gen128 = |w, f, u| gen64(u64::try_from(w).expect("u128 to u64"), f, u);
184	match whole_and_frac(d) {
185		| (Days(whole), frac) => gen64(whole, frac, "days"),
186		| (Hours(whole), frac) => gen64(whole, frac, "hours"),
187		| (Mins(whole), frac) => gen64(whole, frac, "minutes"),
188		| (Secs(whole), frac) => gen64(whole, frac, "seconds"),
189		| (Millis(whole), frac) => gen128(whole, frac, "milliseconds"),
190		| (Micros(whole), frac) => gen128(whole, frac, "microseconds"),
191		| (Nanos(whole), frac) => gen128(whole, frac, "nanoseconds"),
192	}
193}
194
195/// Pairs a duration's selected whole unit with its fraction in `[0, 1)`.
196///
197/// For days through minutes, the second value is a whole-second remainder
198/// divided by the selected unit, so subsecond data is discarded. Seconds use
199/// milliseconds within the current second, discarding submillisecond data;
200/// milliseconds use microseconds, discarding nanoseconds; microseconds use
201/// nanoseconds; nanoseconds return `0.0`.
202#[must_use]
203#[expect(clippy::as_conversions, clippy::cast_precision_loss)]
204pub fn whole_and_frac(d: Duration) -> (Unit, f64) {
205	use Unit::*;
206
207	let whole = whole_unit(d);
208	(whole, match whole {
209		| Days(_) => (d.as_secs() % 86_400) as f64 / 86_400.0,
210		| Hours(_) => (d.as_secs() % 3_600) as f64 / 3_600.0,
211		| Mins(_) => (d.as_secs() % 60) as f64 / 60.0,
212		| Secs(_) => f64::from(d.subsec_millis()) / 1000.0,
213		| Millis(_) => f64::from(d.subsec_micros() % 1000) / 1000.0,
214		| Micros(_) => f64::from(d.subsec_nanos() % 1000) / 1000.0,
215		| Nanos(_) => 0.0,
216	})
217}
218
219/// Selects the largest integral unit represented by a duration.
220///
221/// The stored value is rounded down to a whole unit. A zero duration is
222/// represented as `Unit::Nanos(0)`.
223#[must_use]
224pub fn whole_unit(d: Duration) -> Unit {
225	use Unit::*;
226
227	match d.as_secs() {
228		| 86_400.. => Days(d.as_secs() / 86_400),
229		| 3_600..=86_399 => Hours(d.as_secs() / 3_600),
230		| 60..=3_599 => Mins(d.as_secs() / 60),
231		| _ => match d.as_micros() {
232			| 1_000_000.. => Secs(d.as_secs()),
233			| 1_000..=999_999 => Millis(d.subsec_millis().into()),
234			| _ => match d.as_nanos() {
235				| 1_000.. => Micros(d.subsec_micros().into()),
236				| _ => Nanos(d.subsec_nanos().into()),
237			},
238		},
239	}
240}
241
242/// Represents an integral duration in one selected unit.
243///
244/// Each variant stores the whole count for its named unit. [`whole_unit`]
245/// selects the largest unit with a nonzero count, except that zero is
246/// represented in nanoseconds.
247#[derive(Eq, PartialEq, Clone, Copy, Debug)]
248pub enum Unit {
249	/// A duration measured in whole 86,400-second days.
250	///
251	/// [`whole_unit`] selects this variant for durations of at least one day.
252	Days(u64),
253
254	/// A duration measured in whole hours.
255	///
256	/// [`whole_unit`] selects this variant below one day and at or above one
257	/// hour.
258	Hours(u64),
259
260	/// A duration measured in whole minutes.
261	///
262	/// [`whole_unit`] selects this variant below one hour and at or above one
263	/// minute.
264	Mins(u64),
265
266	/// A duration measured in whole seconds.
267	///
268	/// [`whole_unit`] selects this variant below one minute and at or above one
269	/// second.
270	Secs(u64),
271
272	/// A duration measured in whole milliseconds.
273	///
274	/// [`whole_unit`] selects this variant below one second and at or above one
275	/// millisecond.
276	Millis(u128),
277
278	/// A duration measured in whole microseconds.
279	///
280	/// [`whole_unit`] selects this variant below one millisecond and at or
281	/// above one microsecond.
282	Micros(u128),
283
284	/// A duration measured in whole nanoseconds.
285	///
286	/// [`whole_unit`] selects this variant below one microsecond, including for
287	/// zero.
288	Nanos(u128),
289}