use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use futures::future::BoxFuture;
type CloseFn = Box<dyn FnOnce() -> BoxFuture<'static, ()> + Send>;
#[derive(Default)]
pub struct CloseGroup {
closed: AtomicBool,
callbacks: Mutex<Vec<CloseFn>>,
}
impl CloseGroup {
pub fn new() -> Self {
CloseGroup::default()
}
pub fn register<F>(&self, f: F)
where
F: FnOnce() -> BoxFuture<'static, ()> + Send + 'static,
{
if self.is_closed() {
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(f());
}
return;
}
self.lock().push(Box::new(f));
}
pub fn is_closed(&self) -> bool {
self.closed.load(Ordering::SeqCst)
}
pub async fn close(&self) {
if self.closed.swap(true, Ordering::SeqCst) {
return;
}
let callbacks = std::mem::take(&mut *self.lock());
for cb in callbacks {
cb().await;
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<CloseFn>> {
self.callbacks.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl fmt::Debug for CloseGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CloseGroup")
.field("closed", &self.is_closed())
.field("callbacks", &self.lock().len())
.finish()
}
}