blob: 8460f209332cfb35ac1046977d74374e30329596 (
plain)
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
|
use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
pub fn now() -> String {
match pinned() {
Some(pinned) => pinned,
None => fmt(Utc::now()),
}
}
fn base() -> DateTime<Utc> {
match pinned().and_then(|p| parse(&p)) {
Some(t) => t,
None => Utc::now(),
}
}
fn fmt(t: DateTime<Utc>) -> String {
t.to_rfc3339_opts(SecondsFormat::Secs, true)
}
fn pinned() -> Option<String> {
CLOCK.with(|c| c.borrow().clone())
}
thread_local! {
static CLOCK: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
pub fn pin(ts: &str) -> Option<String> {
CLOCK.with(|c| {
let mut slot = c.borrow_mut();
(*slot).replace(ts.to_string())
})
}
pub fn unpin() {
CLOCK.with(|c| *c.borrow_mut() = None);
}
pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
DateTime::parse_from_rfc3339(ts)
.ok()
.map(|d| d.with_timezone(&Utc))
.or_else(|| {
chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S")
.ok()
.map(|n| Utc.from_utc_datetime(&n))
})
}
pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
}
pub fn secs_ago(secs: i64) -> String {
fmt(base() - chrono::Duration::seconds(secs))
}
pub fn secs_ahead(secs: i64) -> String {
fmt(base() + chrono::Duration::seconds(secs))
}
|