use super::{Guard, OwnedChild, State};
pub(super) struct HolderGuard<'a> {
sc: &'a OwnedChild,
token: u64,
lock: Option<Guard<'a>>,
done: bool,
}
impl<'a> HolderGuard<'a> {
pub(super) fn arm(sc: &'a OwnedChild, mut lock: Guard<'a>) -> Self {
let token = lock.next_token;
lock.next_token += 1;
lock.set(State::W { token });
sc.notify(&mut lock);
HolderGuard {
sc,
token,
lock: Some(lock),
done: false,
}
}
pub(super) fn unlock(&mut self) {
self.lock = None;
}
pub(super) fn relock(&mut self) {
if self.lock.is_none() {
self.lock = Some(self.sc.lock());
}
#[cfg(test)]
super::seams::panic_after_relock_if_armed();
self.assert_own();
}
fn assert_own(&self) {
let state = self.lock.as_ref().map(|lock| lock.state);
debug_assert!(
matches!(state, Some(State::W { token }) if token == self.token),
"the holder found the state {state:?}, not its own W {{ token: {} }}",
self.token
);
}
pub(super) fn finish(mut self, state: State) -> Guard<'a> {
let mut lock = self.lock.take().unwrap_or_else(|| self.sc.lock());
debug_assert!(
matches!(lock.state, State::W { token } if token == self.token),
"the holder finished over the state {:?}, not its own W",
lock.state
);
lock.set(state);
self.sc.notify(&mut lock);
self.done = true;
lock
}
}
impl Drop for HolderGuard<'_> {
fn drop(&mut self) {
if self.done {
return;
}
let mut lock = self.lock.take().unwrap_or_else(|| self.sc.lock());
debug_assert!(
matches!(lock.state, State::W { token } if token == self.token),
"the holder was dropped over the state {:?}, not its own W {{ token: {} }}",
lock.state,
self.token
);
lock.set(State::N);
self.sc.notify(&mut lock);
}
}