drop-guard.rs/src/ext/tokio1.rs

89 lines
2.2 KiB
Rust

#[cfg(feature = "tokio1-task")]
pub use join_handle_ext::*;
#[cfg(feature = "tokio1-sync")]
pub use sender_ext::*;
#[cfg(all(feature = "tokio1-sync", feature = "std"))]
pub use semaphore_ext::*;
#[cfg(feature = "tokio1-task")]
mod join_handle_ext {
use tokio1::task::{JoinError, JoinHandle};
use crate::DropFn;
crate::macros::join_handle_ext!(JoinHandleExt for JoinHandle, AbortOnDrop, abort, |T| Result<T, JoinError>);
}
#[cfg(feature = "tokio1-sync")]
mod sender_ext {
use tokio1::sync::oneshot::Sender;
use crate::{DropFn, DropGuard};
pub struct SendOnDrop<T>(T);
impl<T> DropFn for SendOnDrop<T> {
type Data = Sender<T>;
fn on_drop(self, data: Self::Data) {
_ = data.send(self.0);
}
}
trait Sealed {}
pub trait SenderExt {
type Value;
/// Wraps the sender in a [`DropGuard`] that will [`send`](Sender::send) the given `value` on drop.
fn send_on_drop(self, value: Self::Value) -> DropGuard<SendOnDrop<Self::Value>>;
}
impl<T> Sealed for Sender<T> {}
impl<T> SenderExt for Sender<T> {
type Value = T;
fn send_on_drop(self, value: T) -> DropGuard<SendOnDrop<T>> {
DropGuard::with_data(SendOnDrop(value), self)
}
}
}
#[cfg(all(feature = "tokio1-sync", feature = "std"))]
mod semaphore_ext {
use std::marker::PhantomData;
use std::ops::Deref;
use tokio1::sync::Semaphore;
use crate::{DropFn, DropGuard};
pub struct CloseOnDrop<T>(PhantomData<fn() -> T>);
impl<T> DropFn for CloseOnDrop<T>
where
T: Deref<Target = Semaphore>,
{
type Data = T;
fn on_drop(self, data: Self::Data) {
data.close();
}
}
trait Sealed {}
pub trait SemaphoreExt: Sized + Deref<Target = Semaphore> {
/// Wraps the semaphore in a [`DropGuard`] that will call [`Semaphore::close`] on drop.
fn close_on_drop(self) -> DropGuard<CloseOnDrop<Self>>;
}
impl<T> Sealed for T where T: Deref<Target = Semaphore> {}
impl<T> SemaphoreExt for T
where
T: Deref<Target = Semaphore>,
{
fn close_on_drop(self) -> DropGuard<CloseOnDrop<Self>> {
DropGuard::with_data(CloseOnDrop(PhantomData), self)
}
}
}