use std::{ future::Future, ops::{Deref, DerefMut}, pin::Pin, task::{Context, Poll}, }; use tokio::task::JoinHandle; use crate::errors::BinstallError; #[derive(Debug)] pub struct AutoAbortJoinHandle(JoinHandle); impl AutoAbortJoinHandle { pub fn new(handle: JoinHandle) -> Self { Self(handle) } } impl AutoAbortJoinHandle where T: Send + 'static, { pub fn spawn(future: F) -> Self where F: Future + Send + 'static, { Self(tokio::spawn(future)) } } impl Drop for AutoAbortJoinHandle { fn drop(&mut self) { self.0.abort(); } } impl Deref for AutoAbortJoinHandle { type Target = JoinHandle; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for AutoAbortJoinHandle { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Future for AutoAbortJoinHandle { type Output = Result; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { Pin::new(&mut Pin::into_inner(self).0) .poll(cx) .map_err(BinstallError::TaskJoinError) } } impl AutoAbortJoinHandle> where E: Into, { pub async fn flattened_join(self) -> Result { self.await?.map_err(Into::into) } }