forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

time.rs127 lines, 4.3 KiBHistoryRawDownload
1//! UTC timestamps as stored in the database.
2//!
3//! The format is RFC 3339 with 9 fractional digits and a `Z` suffix. It has a fixed width, so
4//! comparing two stamps as text gives the same order as comparing the times.
5
6use std::time::Duration;
7
8use time::{
9 OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
10};
11
12const FORMAT: &[FormatItem<'static>] =
13 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
14
15fn format_stamp(at: OffsetDateTime) -> String {
16 // The format description only uses fields that always format, so this cannot fail.
17 at.format(FORMAT).unwrap_or_default()
18}
19
20/// Converts a `std` duration to the signed form `time` uses, saturating on overflow.
21fn signed(d: Duration) -> SignedDuration {
22 SignedDuration::try_from(d).unwrap_or(SignedDuration::MAX)
23}
24
25/// The current time as a stamp.
26pub fn now_stamp() -> String {
27 format_stamp(OffsetDateTime::now_utc())
28}
29
30/// The stamp for `now + after`. Saturates at the maximum representable time instead of panicking.
31pub fn stamp_after(after: Duration) -> String {
32 format_stamp(OffsetDateTime::now_utc().saturating_add(signed(after)))
33}
34
35/// The stamp for `now - before`. Saturates at the minimum representable time instead of panicking.
36pub fn stamp_before(before: Duration) -> String {
37 format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before)))
38}
39
40/// Parses a stored stamp back into a time. `None` for anything that is not a stamp.
41fn parse_stamp(stamp: &str) -> Option<OffsetDateTime> {
42 OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339).ok()
43}
44
45/// The Unix time, in whole seconds, of a stored stamp. `None` when it is not a stamp.
46pub fn unix_seconds(stamp: &str) -> Option<i64> {
47 parse_stamp(stamp).map(OffsetDateTime::unix_timestamp)
48}
49
50/// The stamp `after` later than `stamp`, saturating at the largest time. `None` when `stamp` is not a
51/// stamp.
52pub fn stamp_plus(stamp: &str, after: Duration) -> Option<String> {
53 Some(format_stamp(
54 parse_stamp(stamp)?.saturating_add(signed(after)),
55 ))
56}
57
58/// The stamp `before` earlier than `stamp`, saturating at the smallest time. `None` when `stamp` is not
59/// a stamp.
60pub fn stamp_minus(stamp: &str, before: Duration) -> Option<String> {
61 Some(format_stamp(
62 parse_stamp(stamp)?.saturating_sub(signed(before)),
63 ))
64}
65
66/// The current Unix time in whole seconds.
67pub fn unix_now() -> i64 {
68 OffsetDateTime::now_utc().unix_timestamp()
69}
70
71/// The stamp of a Unix time in whole seconds. `None` when the time is out of range.
72pub fn stamp_of_unix(seconds: i64) -> Option<String> {
73 OffsetDateTime::from_unix_timestamp(seconds)
74 .ok()
75 .map(format_stamp)
76}
77
78/// The IANA time zone names of the database compiled into this build, sorted. The bundled database
79/// is used on purpose, so every install offers the same list whatever the host has installed.
80pub fn zone_names() -> Vec<String> {
81 let mut names: Vec<String> = jiff::tz::db()
82 .available()
83 .map(|name| name.as_str().to_owned())
84 .collect();
85 names.sort();
86 names
87}
88
89/// True only for an exact IANA name from [`zone_names`]. Matching is case-sensitive and nothing is
90/// trimmed, so the stored value is always the canonical name.
91pub fn is_zone(name: &str) -> bool {
92 jiff::tz::db()
93 .available()
94 .any(|known| known.as_str() == name)
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn zones_are_checked_against_the_bundled_list() {
103 assert!(is_zone("Europe/Istanbul"));
104 assert!(is_zone("UTC"));
105 for bad in [
106 "",
107 "europe/istanbul",
108 " Europe/Istanbul",
109 "../../etc/passwd",
110 "Mars/Olympus",
111 ] {
112 assert!(!is_zone(bad), "accepted {bad:?}");
113 }
114 assert!(zone_names().len() > 300);
115 }
116
117 #[test]
118 fn stamps_have_fixed_width_and_sort_in_time_order() {
119 let now = now_stamp();
120 let later = stamp_after(Duration::from_secs(3600));
121 let much_later = stamp_after(Duration::from_secs(7200));
122 assert_eq!(now.len(), 30, "bad stamp: {now}");
123 assert!(now.ends_with('Z'));
124 assert!(now < later && later < much_later);
125 assert!(stamp_before(Duration::from_secs(3600)) < now);
126 }
127}