use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PendingInvalidation {
One(String),
All,
}
#[derive(Clone, Default)]
pub struct InvalidationHandle {
pending: Arc<Mutex<Vec<PendingInvalidation>>>,
woken: Arc<AtomicBool>,
}
impl InvalidationHandle {
pub fn new() -> Self {
Self::default()
}
pub fn invalidate(&self, id: impl Into<String>) {
self.push(PendingInvalidation::One(id.into()));
}
pub fn invalidate_all(&self) {
self.push(PendingInvalidation::All);
}
#[doc(hidden)]
pub fn drain(&self) -> Vec<PendingInvalidation> {
self.woken.store(false, Ordering::Relaxed);
let mut queue = self
.pending
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
std::mem::take(&mut *queue)
}
#[doc(hidden)]
pub fn has_pending(&self) -> bool {
self.woken.load(Ordering::Relaxed)
}
fn push(&self, item: PendingInvalidation) {
{
let mut queue = self
.pending
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
queue.push(item);
}
self.woken.store(true, Ordering::Relaxed);
}
}
const _: () = {
fn assert_send_sync<T: Send + Sync>() {}
let _ = assert_send_sync::<InvalidationHandle>;
};