Skip to main content

lunar_lib/
security.rs

1use std::time::{Duration, Instant};
2
3pub struct DropWaiter {
4    start: Instant,
5    min: Duration,
6}
7
8impl DropWaiter {
9    pub fn new(min: Duration) -> Self {
10        Self {
11            start: Instant::now(),
12            min,
13        }
14    }
15}
16
17impl Drop for DropWaiter {
18    fn drop(&mut self) {
19        let elapsed = self.start.elapsed();
20        if let Some(remaining) = self.min.checked_sub(elapsed) {
21            std::thread::sleep(remaining);
22        }
23    }
24}
25
26#[cfg(feature = "async-security")]
27pub struct AsyncDropWaiter {
28    start: Instant,
29    waited: bool,
30}
31
32#[cfg(feature = "async-security")]
33impl AsyncDropWaiter {
34    pub fn new(min: Duration) -> Self {
35        Self {
36            start: Instant::now() + min,
37            waited: false,
38        }
39    }
40
41    pub async fn wait(&mut self) {
42        tokio::time::sleep_until(self.start.into()).await;
43        self.waited = true;
44    }
45}
46
47#[cfg(feature = "async-security")]
48impl Drop for AsyncDropWaiter {
49    fn drop(&mut self) {
50        if !self.waited {
51            panic!("Dropped AsyncDropWaiter without waiting.")
52        }
53    }
54}