use crate::{Error, Result, core, core::Reason};
use std::{
cell::RefCell,
pin::Pin,
rc::Rc,
task::{Context, Poll, Waker},
};
pub trait ByteSource: 'static {
fn poll_next(&mut self, context: &mut Context<'_>) -> Poll<Option<Result<Vec<u8>>>>;
fn close(&mut self);
fn poll_closed(&mut self, context: &mut Context<'_>) -> Poll<Result<()>>;
}
enum State {
Open,
Finished,
Expired,
Cancelled,
}
struct Shared {
source: Box<dyn ByteSource>,
state: State,
closed: bool,
reader: Option<Waker>,
}
impl Shared {
fn close_once(&mut self) {
if !self.closed {
self.closed = true;
self.source.close();
}
}
}
pub struct ByteStream(Rc<RefCell<Shared>>);
impl ByteStream {
pub fn new(source: impl ByteSource) -> Self {
Self(Rc::new(RefCell::new(Shared {
source: Box::new(source),
state: State::Open,
closed: false,
reader: None,
})))
}
pub async fn close(self) -> Result<()> {
self.0.borrow_mut().close_once();
let shared = self.0.clone();
futures::future::poll_fn(move |context| shared.borrow_mut().source.poll_closed(context))
.await
}
pub(crate) fn root_stream(&self) -> std::rc::Weak<dyn RootStream> {
let shared: Rc<dyn RootStream> = self.0.clone();
Rc::downgrade(&shared)
}
}
impl futures::Stream for ByteStream {
type Item = Result<Vec<u8>>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut shared = self.0.borrow_mut();
match shared.state {
State::Open => {}
State::Finished => return Poll::Ready(None),
State::Expired => return Poll::Ready(Some(Err(expired()))),
State::Cancelled => return Poll::Ready(Some(Err(cancelled()))),
}
shared.reader = Some(context.waker().clone());
let next = shared.source.poll_next(context);
if matches!(next, Poll::Ready(None | Some(Err(_)))) {
shared.state = State::Finished;
}
next
}
}
impl Drop for ByteStream {
fn drop(&mut self) {
self.0.borrow_mut().close_once();
}
}
pub(crate) trait RootStream {
fn end_root(&self);
fn cancel_root(&self);
}
impl RootStream for RefCell<Shared> {
fn end_root(&self) {
settle(self, State::Expired);
}
fn cancel_root(&self) {
settle(self, State::Cancelled);
}
}
fn settle(cell: &RefCell<Shared>, state: State) {
let reader = {
let mut shared = cell.borrow_mut();
if matches!(shared.state, State::Open) {
shared.state = state;
}
shared.close_once();
shared.reader.take()
};
if let Some(reader) = reader {
reader.wake();
}
}
fn expired() -> Error {
Error::new(
core::Code::Expired,
Reason::Root,
"the stream's root has ended",
)
}
fn cancelled() -> Error {
Error::new(
core::Code::Cancelled,
Reason::Root,
"the stream's root was cancelled",
)
}