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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use std::{
    fmt::Debug,
    ops::{Deref, DerefMut},
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::{SystemTime, UNIX_EPOCH},
};

pub trait Clock {
    fn now(&self) -> u64;
}

#[derive(Debug)]
pub struct SystemClock {}

impl Clock for SystemClock {
    fn now(&self) -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64
    }
}

#[derive(Debug)]
pub struct DebugClock {
    time: AtomicU64,
}

impl DebugClock {
    pub fn new(time: u64) -> DebugClock {
        DebugClock {
            time: AtomicU64::new(time),
        }
    }

    pub fn set(&self, time: u64) {
        self.time.store(time, Ordering::Release);
    }
}

impl Clock for DebugClock {
    fn now(&self) -> u64 {
        self.time.load(Ordering::Acquire)
    }
}

#[derive(Debug)]
pub enum ClockImpl {
    System(SystemClock),
    Debug(Arc<DebugClock>),
}

impl Clock for ClockImpl {
    fn now(&self) -> u64 {
        match self {
            ClockImpl::System(c) => c.now(),
            ClockImpl::Debug(c) => c.now(),
        }
    }
}

#[derive(Debug)]
pub struct BitcaskClock {
    pub clock: ClockImpl,
}

impl Clock for BitcaskClock {
    fn now(&self) -> u64 {
        self.clock.now()
    }
}

impl Deref for BitcaskClock {
    type Target = ClockImpl;

    fn deref(&self) -> &Self::Target {
        &self.clock
    }
}

impl DerefMut for BitcaskClock {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.clock
    }
}

impl Default for BitcaskClock {
    fn default() -> Self {
        Self {
            clock: ClockImpl::System(SystemClock {}),
        }
    }
}