Skip to main content

nym_ecash_time/
lib.rs

1// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use time::{Duration, PrimitiveDateTime, Time};
5
6pub use time::{Date, OffsetDateTime};
7
8pub trait EcashTime {
9    fn ecash_unix_timestamp(&self) -> u32 {
10        let ts = self.ecash_datetime().unix_timestamp();
11
12        // just panic on pre-1970 timestamps...
13        assert!(ts > 0);
14
15        // and on anything in 22nd century...
16        assert!(ts <= u32::MAX as i64);
17
18        ts as u32
19    }
20
21    fn ecash_date(&self) -> Date {
22        self.ecash_datetime().date()
23    }
24
25    fn ecash_datetime(&self) -> OffsetDateTime;
26}
27
28impl EcashTime for OffsetDateTime {
29    fn ecash_datetime(&self) -> OffsetDateTime {
30        self.replace_time(Time::MIDNIGHT)
31    }
32}
33
34impl EcashTime for PrimitiveDateTime {
35    fn ecash_datetime(&self) -> OffsetDateTime {
36        self.assume_utc().ecash_datetime()
37    }
38}
39
40impl EcashTime for Date {
41    fn ecash_datetime(&self) -> OffsetDateTime {
42        OffsetDateTime::new_utc(*self, Time::MIDNIGHT)
43    }
44}
45
46pub fn ecash_today() -> OffsetDateTime {
47    OffsetDateTime::now_utc().ecash_datetime()
48}
49
50pub fn ecash_today_date() -> Date {
51    ecash_today().ecash_date()
52}
53
54// no point in supporting more than i8 variance
55pub fn ecash_date_offset(offset: i8) -> OffsetDateTime {
56    let today = ecash_today();
57
58    let day = today + Duration::days(offset as i64);
59
60    // make sure to correct the time in case of DST
61    day.replace_time(Time::MIDNIGHT)
62}
63
64#[cfg(feature = "expiration")]
65pub fn cred_exp_date() -> OffsetDateTime {
66    //count today as well
67    ecash_date_offset(nym_compact_ecash::constants::CRED_VALIDITY_PERIOD_DAYS as i8 - 1)
68    // ecash_today() + Duration::days(constants::CRED_VALIDITY_PERIOD_DAYS as i64 - 1)
69}
70
71#[cfg(feature = "expiration")]
72pub fn ecash_default_expiration_date() -> Date {
73    cred_exp_date().ecash_date()
74}