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
use std::prelude::v1::*;



#[cfg(feature = "moment")]
use core::fmt;
#[cfg(feature = "moment")]
use core::fmt::Formatter;

use std::sync::Arc;


#[cfg(feature = "moment")]
#[derive(Clone)]
pub struct Moment {
    generator: Arc<fn() -> chrono::DateTime<chrono::Utc>>
}

#[cfg(feature = "moment")]
impl Moment {
    pub fn new(func: Option<fn() -> chrono::DateTime<chrono::Utc>>) -> Self {
        let time_func = {
            #[cfg(feature = "default")] {
                match func {
                    Some(f) => f,
                    None => chrono::Utc::now
                }
            }
            #[cfg(not(feature = "default"))] {
                match func {
                    Some(f) => f,
                    None => panic!("No time function supplied")
                }
            }
        };

        Self {
            generator: Arc::new(time_func)
        }
    }

    pub fn now(&self) -> chrono::DateTime<chrono::Utc> {
        (self.generator)()
    }

    pub fn get_function(&self) -> fn() -> chrono::DateTime<chrono::Utc> {
        *self.generator.clone()
    }
}

#[cfg(all(feature = "moment", feature = "default"))]
impl Default for Moment {
    fn default() -> Self {
        Self {
            generator: Arc::new(chrono::Utc::now)
        }
    }
}

#[cfg(feature = "moment")]
impl core::fmt::Debug for Moment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}