1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
mod date;
mod month;
mod parsing;
mod period;

use chrono::{Local, TimeZone};
#[cfg(debug_assertions)] use lazy_static::lazy_static;

pub use chrono::DateTime as TzDateTime;
pub use crate::types::{Date, Time, DateTime};

pub use date::*;
pub use month::*;
pub use parsing::*;
pub use period::*;

pub fn today() -> Date {
    tz_now().naive_local().date()
}

pub fn now() -> DateTime {
    tz_now().naive_local()
}

pub fn utc_now() -> DateTime {
    tz_now().naive_utc()
}

fn tz_now() -> TzDateTime<Local> {
    #[cfg(debug_assertions)]
    {
        use std::process;

        lazy_static! {
            static ref FAKE_NOW: Option<TzDateTime<Local>> = parsing::parse_fake_now().unwrap_or_else(|e| {
                eprintln!("{}.", e);
                process::exit(1);
            });
        }

        if let Some(&now) = FAKE_NOW.as_ref() {
            return now;
        }
    }

    Local::now()
}

pub trait TimeProvider: Sync + Send {
    fn now(&self) -> TzDateTime<Local>;
}

pub struct SystemTime();

impl TimeProvider for SystemTime {
    fn now(&self) -> TzDateTime<Local> {
        tz_now()
    }
}

pub struct FakeTime(i64);

impl FakeTime {
    pub fn new<T: TimeZone>(time: TzDateTime<T>) -> FakeTime {
        FakeTime(time.timestamp())
    }
}

impl TimeProvider for FakeTime {
    fn now(&self) -> TzDateTime<Local> {
        Local.from_utc_datetime(&chrono::NaiveDateTime::from_timestamp_opt(self.0, 0).unwrap())
    }
}