Refactor: Extract AutoAbortJoinHandle

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-06-08 21:46:32 +10:00
parent 358bea5c6d
commit 5d70f61317
No known key found for this signature in database
GPG key ID: 591C0B03040416D6
2 changed files with 49 additions and 44 deletions

View file

@ -0,0 +1,45 @@
use std::{
future::Future,
ops::{Deref, DerefMut},
pin::Pin,
task::{Context, Poll},
};
use tokio::task::{JoinError, JoinHandle};
#[derive(Debug)]
pub struct AutoAbortJoinHandle<T>(JoinHandle<T>);
impl<T> AutoAbortJoinHandle<T> {
pub fn new(handle: JoinHandle<T>) -> Self {
Self(handle)
}
}
impl<T> Drop for AutoAbortJoinHandle<T> {
fn drop(&mut self) {
self.0.abort();
}
}
impl<T> Deref for AutoAbortJoinHandle<T> {
type Target = JoinHandle<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for AutoAbortJoinHandle<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> Future for AutoAbortJoinHandle<T> {
type Output = Result<T, JoinError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut Pin::into_inner(self).0).poll(cx)
}
}