use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug)]
pub(crate) struct Busy {
state: Mutex<State>,
}
#[derive(Debug)]
struct State {
open: usize,
since: u64,
}
impl Busy {
pub(crate) fn new() -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(State {
open: 0,
since: now(),
}),
})
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn open(this: &Arc<Self>) -> BusyGuard {
{
let mut state = this.lock();
if state.open == 0 {
state.since = now();
}
state.open += 1;
}
BusyGuard {
busy: Arc::clone(this),
}
}
pub(crate) fn status(&self) -> (bool, u64) {
let state = self.lock();
(state.open > 0, state.since)
}
}
#[must_use = "dropping the guard at once ends the busy status immediately"]
#[derive(Debug)]
pub struct BusyGuard {
busy: Arc<Busy>,
}
impl Drop for BusyGuard {
fn drop(&mut self) {
let mut state = self.busy.lock();
state.open = state.open.saturating_sub(1);
if state.open == 0 {
state.since = now();
}
}
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs())
}