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
use std::thread::sleep;
use std::time::{Instant, Duration};

/// A type that can help with implementing the DDC specificationed delays.
#[derive(Clone, Debug)]
pub struct Delay {
    time: Option<Instant>,
    delay: Duration,
}

impl Delay {
    /// Creates a new delay starting now.
    pub fn new(delay: Duration) -> Self {
        Delay {
            time: Some(Instant::now()),
            delay: delay,
        }
    }

    /// The time remaining in this delay.
    pub fn remaining(&self) -> Duration {
        self.time.as_ref().and_then(|time| self.delay.checked_sub(time.elapsed())).unwrap_or(Duration::default())
    }

    /// Waits out the remaining time in this delay.
    pub fn sleep(&mut self) {
        if let Some(delay) = self.time.take().and_then(|time| self.delay.checked_sub(time.elapsed())) {
            sleep(delay);
        }
    }
}

impl Default for Delay {
    fn default() -> Self {
        Delay {
            time: None,
            delay: Default::default(),
        }
    }
}