69 lines
2.1 KiB
Rust
69 lines
2.1 KiB
Rust
//! 使用库提供的取消通知,支持别名读取与不依赖读取者再次 poll 的同步关闭。
|
|
use super::*;
|
|
use futures_util::Stream;
|
|
use std::future::poll_fn;
|
|
|
|
pub(super) struct SharedDownload<S>(Arc<Shared<S>>);
|
|
struct Shared<S> {
|
|
source: Mutex<Option<Pin<Box<S>>>>,
|
|
reading: tokio::sync::Mutex<()>,
|
|
closed: CancellationToken,
|
|
}
|
|
impl<S> Clone for SharedDownload<S> {
|
|
fn clone(&self) -> Self {
|
|
Self(self.0.clone())
|
|
}
|
|
}
|
|
impl<S> SharedDownload<S> {
|
|
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<S: Stream<Item = io::Result<Bytes>>> SharedDownload<S> {
|
|
pub async fn next(&self) -> io::Result<Option<Bytes>> {
|
|
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<S>);
|
|
impl<S> Drop for CloseOnDrop<'_, S> {
|
|
fn drop(&mut self) {
|
|
self.0.close();
|
|
}
|
|
}
|