hyper_scripter/
script_time.rs

1use chrono::{NaiveDateTime, Utc};
2use std::cmp::{Ordering, PartialEq, PartialOrd};
3
4/// 可能帶著資料的時間。
5/// 如果有資料,代表「這些資料是新的產生,應儲存起來但還未存」
6/// 如果沒資料,就視為上次儲存的一個快照,只記得時間就好,因為我們通常不會需要上一次存下的資料
7#[derive(Debug, Clone, Deref, Copy)]
8pub struct ScriptTime<T = ()> {
9    changed: Option<T>,
10    #[deref]
11    time: NaiveDateTime,
12}
13impl<T> PartialEq for ScriptTime<T> {
14    fn eq(&self, other: &Self) -> bool {
15        self.time.eq(&other.time)
16    }
17}
18impl<T> PartialOrd for ScriptTime<T> {
19    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
20        self.time.partial_cmp(&other.time)
21    }
22}
23impl<T> Ord for ScriptTime<T> {
24    fn cmp(&self, other: &Self) -> Ordering {
25        self.partial_cmp(other).unwrap()
26    }
27}
28impl<T> Eq for ScriptTime<T> {}
29
30impl<T> ScriptTime<T> {
31    pub fn now(data: T) -> Self {
32        ScriptTime {
33            time: Utc::now().naive_utc(),
34            changed: Some(data),
35        }
36    }
37    pub fn new_or(time: Option<NaiveDateTime>, default: Self) -> Self {
38        match time {
39            Some(time) => ScriptTime {
40                time,
41                changed: None,
42            },
43            None => default,
44        }
45    }
46    pub fn new(time: NaiveDateTime) -> Self {
47        ScriptTime {
48            time,
49            changed: None,
50        }
51    }
52    pub fn data(&self) -> Option<&T> {
53        self.changed.as_ref()
54    }
55    pub fn has_changed(&self) -> bool {
56        self.changed.is_some()
57    }
58}