radix_common/time/
instant.rs

1use crate::internal_prelude::*;
2use crate::time::constants::*;
3
4use sbor::*;
5
6/// Represents a Unix timestamp, capturing the seconds since the unix epoch.
7///
8/// See also the [`UtcDateTime`](super::UtcDateTime) type which supports conversion to/from `Instant`.
9#[cfg_attr(feature = "fuzzing", derive(::arbitrary::Arbitrary))]
10#[derive(
11    Copy,
12    Clone,
13    Debug,
14    Eq,
15    PartialEq,
16    Categorize,
17    Encode,
18    Decode,
19    BasicDescribe,
20    PartialOrd,
21    Ord,
22    Hash,
23)]
24#[sbor(transparent)]
25pub struct Instant {
26    pub seconds_since_unix_epoch: i64,
27}
28
29impl Describe<ScryptoCustomTypeKind> for Instant {
30    const TYPE_ID: RustTypeId =
31        RustTypeId::WellKnown(well_known_scrypto_custom_types::INSTANT_TYPE);
32
33    fn type_data() -> ScryptoTypeData<RustTypeId> {
34        well_known_scrypto_custom_types::instant_type_data()
35    }
36}
37
38impl Instant {
39    pub fn new(seconds_since_unix_epoch: i64) -> Instant {
40        Instant {
41            seconds_since_unix_epoch,
42        }
43    }
44
45    pub fn compare(&self, other: Instant, operator: TimeComparisonOperator) -> bool {
46        let self_seconds = self.seconds_since_unix_epoch;
47        let other_seconds = other.seconds_since_unix_epoch;
48        match operator {
49            TimeComparisonOperator::Eq => self_seconds == other_seconds,
50            TimeComparisonOperator::Lt => self_seconds < other_seconds,
51            TimeComparisonOperator::Lte => self_seconds <= other_seconds,
52            TimeComparisonOperator::Gt => self_seconds > other_seconds,
53            TimeComparisonOperator::Gte => self_seconds >= other_seconds,
54        }
55    }
56
57    pub fn add_days(&self, days_to_add: i64) -> Option<Instant> {
58        days_to_add
59            .checked_mul(SECONDS_IN_A_DAY)
60            .and_then(|to_add| self.seconds_since_unix_epoch.checked_add(to_add))
61            .map(Instant::new)
62    }
63
64    pub fn add_hours(&self, hours_to_add: i64) -> Option<Instant> {
65        hours_to_add
66            .checked_mul(SECONDS_IN_AN_HOUR)
67            .and_then(|to_add| self.seconds_since_unix_epoch.checked_add(to_add))
68            .map(Instant::new)
69    }
70
71    pub fn add_minutes(&self, minutes_to_add: i64) -> Option<Instant> {
72        minutes_to_add
73            .checked_mul(SECONDS_IN_A_MINUTE)
74            .and_then(|to_add| self.seconds_since_unix_epoch.checked_add(to_add))
75            .map(Instant::new)
76    }
77
78    pub fn add_seconds(&self, seconds_to_add: i64) -> Option<Instant> {
79        self.seconds_since_unix_epoch
80            .checked_add(seconds_to_add)
81            .map(Instant::new)
82    }
83}
84
85#[derive(Sbor, Copy, Clone, Debug, Eq, PartialEq)]
86pub enum TimeComparisonOperator {
87    Eq,
88    Lt,
89    Lte,
90    Gt,
91    Gte,
92}