use tokio::task::{AbortHandle, JoinError, JoinHandle};
use std::{
future::Future,
mem::ManuallyDrop,
pin::Pin,
task::{Context, Poll},
};
#[must_use = "Dropping the handle aborts the task immediately"]
pub struct AbortOnDropHandle<T>(JoinHandle<T>);
impl<T> Drop for AbortOnDropHandle<T> {
fn drop(&mut self) {
self.abort()
}
}
impl<T> AbortOnDropHandle<T> {
pub fn new(handle: JoinHandle<T>) -> Self {
Self(handle)
}
#[inline]
pub fn abort(&self) {
self.0.abort()
}
#[inline]
pub fn is_finished(&self) -> bool {
self.0.is_finished()
}
pub fn abort_handle(&self) -> AbortHandle {
self.0.abort_handle()
}
pub fn detach(self) -> JoinHandle<T> {
let this = ManuallyDrop::new(self);
unsafe { std::ptr::read(&this.0) }
}
}
impl<T> std::fmt::Debug for AbortOnDropHandle<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AbortOnDropHandle")
.field("id", &self.0.id())
.finish()
}
}
impl<T> Future for AbortOnDropHandle<T> {
type Output = Result<T, JoinError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0).poll(cx)
}
}
impl<T> AsRef<JoinHandle<T>> for AbortOnDropHandle<T> {
fn as_ref(&self) -> &JoinHandle<T> {
&self.0
}
}
#[must_use = "Dropping the handle aborts the task immediately"]
pub struct AbortOnDrop(AbortHandle);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.abort()
}
}
impl AbortOnDrop {
pub fn new(handle: AbortHandle) -> Self {
Self(handle)
}
#[inline]
pub fn abort(&self) {
self.0.abort()
}
#[inline]
pub fn is_finished(&self) -> bool {
self.0.is_finished()
}
pub fn detach(self) -> AbortHandle {
let this = ManuallyDrop::new(self);
unsafe { std::ptr::read(&this.0) }
}
}
impl std::fmt::Debug for AbortOnDrop {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AbortOnDrop")
.field("id", &self.0.id())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
struct NotDebug;
fn is_debug<T: std::fmt::Debug>() {}
#[test]
fn assert_debug() {
is_debug::<AbortOnDrop>();
is_debug::<AbortOnDropHandle<NotDebug>>();
}
}