1use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7#[derive(Debug)]
9pub(crate) struct Busy {
10 state: Mutex<State>,
11}
12
13#[derive(Debug)]
14struct State {
15 open: usize,
16 since: u64,
19}
20
21impl Busy {
22 pub(crate) fn new() -> Arc<Self> {
23 Arc::new(Self {
24 state: Mutex::new(State {
25 open: 0,
26 since: now(),
27 }),
28 })
29 }
30
31 fn lock(&self) -> MutexGuard<'_, State> {
32 self.state.lock().unwrap_or_else(PoisonError::into_inner)
33 }
34
35 pub(crate) fn open(this: &Arc<Self>) -> BusyGuard {
37 {
38 let mut state = this.lock();
39 if state.open == 0 {
40 state.since = now();
41 }
42 state.open += 1;
43 }
44 BusyGuard {
45 busy: Arc::clone(this),
46 }
47 }
48
49 pub(crate) fn status(&self) -> (bool, u64) {
51 let state = self.lock();
52 (state.open > 0, state.since)
53 }
54}
55
56#[must_use = "dropping the guard at once ends the busy status immediately"]
61#[derive(Debug)]
62pub struct BusyGuard {
63 busy: Arc<Busy>,
64}
65
66impl Drop for BusyGuard {
67 fn drop(&mut self) {
68 let mut state = self.busy.lock();
69 state.open = state.open.saturating_sub(1);
70 if state.open == 0 {
71 state.since = now();
72 }
73 }
74}
75
76fn now() -> u64 {
77 SystemTime::now()
78 .duration_since(UNIX_EPOCH)
79 .map_or(0, |elapsed| elapsed.as_secs())
80}