use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::Stream;
use crate::input::Chunk;
use crate::record::Fault;
use crate::step::Stepper;
#[derive(Debug)]
pub struct Workflow<S, St: Stepper> {
source: S,
stepper: St,
ready: VecDeque<Result<St::Record, Fault>>,
ended: bool,
}
pub fn workflow<S, St>(source: S, stepper: St, opening: Vec<St::Record>) -> Workflow<S, St>
where
S: Stream<Item = Chunk<St::Input>>,
St: Stepper,
{
Workflow { source, stepper, ready: opening.into_iter().map(Ok).collect(), ended: false }
}
impl<S, St: Stepper> Workflow<S, St> {
pub fn stepper(&self) -> &St {
&self.stepper
}
}
impl<S, St> Stream for Workflow<S, St>
where
S: Stream<Item = Chunk<St::Input>> + Unpin,
St: Stepper + Unpin,
St::Record: Unpin,
{
type Item = Result<St::Record, Fault>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
if let Some(item) = this.ready.pop_front() {
return Poll::Ready(Some(item));
}
if this.ended {
return Poll::Ready(None);
}
match Pin::new(&mut this.source).poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(None) => this.ended = true,
Poll::Ready(Some(chunk)) => {
let mut records = Vec::new();
let result = this.stepper.apply(chunk, &mut records);
this.ready.extend(records.into_iter().map(Ok));
if let Err(fault) = result {
this.ended = !fault.code.is_recoverable();
this.ready.push_back(Err(fault));
}
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.ready.len(), if self.ended { Some(self.ready.len()) } else { None })
}
}