radix_common/time/
instant.rs

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