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
62
63
64
65
66
67
68
69
use chrono::{Local, NaiveDateTime, TimeZone, Utc};
use std::cmp::{Ordering, PartialEq, PartialOrd};
use std::fmt::Debug;
#[derive(Debug, Clone, Deref)]
pub struct ScriptTime<T = ()> {
changed: Option<T>,
#[deref]
time: NaiveDateTime,
}
impl<T> PartialEq for ScriptTime<T> {
fn eq(&self, other: &Self) -> bool {
self.time.eq(&other.time)
}
}
impl<T> PartialOrd for ScriptTime<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.time.partial_cmp(&other.time)
}
}
impl<T> Ord for ScriptTime<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl<T> Eq for ScriptTime<T> {}
impl<T> ScriptTime<T> {
pub fn now(data: T) -> Self {
ScriptTime {
time: Utc::now().naive_utc(),
changed: Some(data),
}
}
pub fn new_or_else<F: FnOnce() -> Self>(time: Option<NaiveDateTime>, default: F) -> Self {
match time {
Some(time) => ScriptTime {
time,
changed: None,
},
None => default(),
}
}
pub fn new_or(time: Option<NaiveDateTime>, default: Self) -> Self {
ScriptTime::new_or_else(time, || default)
}
pub fn new(time: NaiveDateTime) -> Self {
ScriptTime {
time,
changed: None,
}
}
pub fn data(&self) -> Option<&T> {
self.changed.as_ref()
}
pub fn has_changed(&self) -> bool {
self.changed.is_some()
}
}
impl<T> std::fmt::Display for ScriptTime<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let local_time = Local.from_utc_datetime(&self.time);
write!(f, "{}", local_time.format("%Y-%m-%d %H:%M"))
}
}