//! 使用库提供的取消通知,支持别名读取与不依赖读取者再次 poll 的同步关闭。 use super::*; use futures_util::Stream; use std::future::poll_fn; pub(super) struct SharedDownload(Arc>); struct Shared { source: Mutex>>>, reading: tokio::sync::Mutex<()>, closed: CancellationToken, } impl Clone for SharedDownload { fn clone(&self) -> Self { Self(self.0.clone()) } } impl SharedDownload { pub fn new(source: S) -> Self { Self(Arc::new(Shared { source: Mutex::new(Some(Box::pin(source))), reading: tokio::sync::Mutex::new(()), closed: CancellationToken::new(), })) } pub fn close(&self) { self.0.closed.cancel(); // panic 后也必须释放源;已经关闭的 next 直接由取消通知结束。 let source = self .0 .source .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .take(); drop(source); } pub fn close_on_drop(&self) -> CloseOnDrop<'_, S> { CloseOnDrop(self) } } impl>> SharedDownload { pub async fn next(&self) -> io::Result> { let read = async { let _reader = self.0.reading.lock().await; poll_fn(|cx| { let mut source = self.0.source.lock().unwrap(); let value = match source.as_mut() { Some(stream) => stream.as_mut().poll_next(cx), None => return Poll::Ready(Ok(None)), }; if matches!(value, Poll::Ready(None | Some(Err(_)))) { source.take(); } value.map(Option::transpose) }) .await }; match self.0.closed.run_until_cancelled(read).await { Some(value) => value, None => Ok(None), } } } pub(super) struct CloseOnDrop<'a, S>(&'a SharedDownload); impl Drop for CloseOnDrop<'_, S> { fn drop(&mut self) { self.0.close(); } }