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