use std::sync::Weak;
use crate::HandlerId;
use super::AsyncRegistry;
#[must_use = "dropping the AsyncHandlerGuard immediately unregisters the handler; \
bind it to a name to keep the handler alive"]
pub struct AsyncHandlerGuard<E: Send + Sync + 'static> {
id: HandlerId,
registry: Weak<AsyncRegistry<E>>,
}
impl<E: Send + Sync + 'static> AsyncHandlerGuard<E> {
pub(crate) fn new(id: HandlerId, registry: Weak<AsyncRegistry<E>>) -> Self {
Self { id, registry }
}
#[inline]
#[must_use]
pub fn id(&self) -> HandlerId {
self.id
}
pub fn forget(self) {
let mut me = std::mem::ManuallyDrop::new(self);
me.registry = Weak::new();
}
}
impl<E: Send + Sync + 'static> Drop for AsyncHandlerGuard<E> {
fn drop(&mut self) {
if let Some(registry) = self.registry.upgrade() {
let _ = registry.unregister(self.id);
}
}
}
impl<E: Send + Sync + 'static> core::fmt::Debug for AsyncHandlerGuard<E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AsyncHandlerGuard")
.field("id", &self.id)
.field("registry_alive", &(self.registry.strong_count() > 0))
.finish()
}
}