compact_time/
source.rs

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
use std::{sync::{atomic::{AtomicU64, Ordering, AtomicBool}, Arc}, thread::{self, JoinHandle}, time::Duration};
use super::Time;

/// Source of `Time` values which are computed asynchronously.
///
/// A `TimeSource` computes the current time in a fixed, configurable frequency, potentially
/// saving the overhead of system calls but with less resolution.
#[derive(Debug, Clone)]
pub struct TimeSource(Arc<Inner>);

#[derive(Debug)]
struct Inner {
    current: Arc<AtomicU64>,
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>
}

impl TimeSource {
    /// Create a new `TimeSource` which gets the current time at the given frequency.
    ///
    /// A thread is spawned to asynchronously getting the time.
    pub fn new(f: Duration) -> Self {
        Self(Arc::new(Inner::new(f)))
    }

    /// Get the current time.
    ///
    /// The time resolution is less than or equal to the frequency with which the
    /// time source has been created.
    pub fn get(&self) -> Time {
        self.0.get()
    }
}

impl Inner {
    fn new(f: Duration) -> Self {
        let current1 = Arc::new(AtomicU64::new(Time::now().into()));
        let current2 = current1.clone();

        let stop1 = Arc::new(AtomicBool::new(false));
        let stop2 = stop1.clone();

        let thread = thread::spawn(move || {
            while !stop2.load(Ordering::Acquire) {
                current2.fetch_max(now(), Ordering::AcqRel);
                thread::sleep(f)
            }
        });

        Self {
            current: current1,
            stop: stop1,
            thread: Some(thread)
        }
    }

    fn get(&self) -> Time {
        Time(self.current.load(Ordering::Acquire))
    }
}

#[cfg(feature = "coarse")]
fn now() -> u64 {
    Time::coarse().into()
}

#[cfg(not(feature = "coarse"))]
fn now() -> u64 {
    Time::now().into()
}

impl Drop for Inner {
    fn drop(&mut self) {
        if let Some(t) = self.thread.take() {
            self.stop.store(true, Ordering::Release);
            let _ = t.join();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;
    use super::TimeSource;

    #[test]
    fn smoke() {
        let ts = TimeSource::new(Duration::from_secs(1));
        for _ in 0 .. 10 {
            println!("{:?}", ts.get().to_utc_string());
            thread::sleep(Duration::from_millis(500))
        }
    }
}