defuse_core/
deadline.rs

1use core::{
2    ops::{Add, AddAssign},
3    time::Duration,
4};
5
6use chrono::{DateTime, Utc};
7use near_sdk::near;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10#[near(serializers=[json])]
11pub struct Deadline(DateTime<Utc>);
12
13impl Deadline {
14    pub const MAX: Self = Self(DateTime::<Utc>::MAX_UTC);
15
16    #[cfg(target_arch = "wasm32")]
17    #[must_use]
18    pub fn now() -> Self {
19        Self(defuse_near_utils::time::now())
20    }
21
22    #[cfg(not(target_arch = "wasm32"))]
23    #[must_use]
24    #[inline]
25    pub fn now() -> Self {
26        Self(Utc::now())
27    }
28
29    #[must_use]
30    #[inline]
31    pub fn timeout(timeout: Duration) -> Self {
32        Self::now() + timeout
33    }
34
35    #[must_use]
36    #[inline]
37    pub fn has_expired(self) -> bool {
38        Self::now() > self
39    }
40
41    #[must_use]
42    #[inline]
43    pub const fn into_timestamp(self) -> DateTime<Utc> {
44        self.0
45    }
46}
47
48impl Add<Duration> for Deadline {
49    type Output = Self;
50
51    #[inline]
52    fn add(self, rhs: Duration) -> Self::Output {
53        Self(self.0 + rhs)
54    }
55}
56
57impl AddAssign<Duration> for Deadline {
58    #[inline]
59    fn add_assign(&mut self, rhs: Duration) {
60        self.0 += rhs;
61    }
62}