use std::future::Future;
use crate::BaseParserError::{self, ExpectedMoreInput};
use crate::parsing::{Outcome, Update};
pub trait ParserState<I>: Sized
where
I: ?Sized,
{
type Output;
type Error: From<BaseParserError>;
fn feed(self, input: &I) -> Result<Update<Self, Self::Output>, Self::Error>;
fn end_input(self, final_input: &I) -> Result<Self::Output, Self::Error> {
let _ = final_input;
Err(Self::Error::from(ExpectedMoreInput))
}
fn run_parser<F, E>(self, mut f: F) -> Result<Self::Output, E>
where
F: FnMut(Self) -> Result<Outcome<Self, Self::Output>, E>,
{
use Outcome::{Next, Parsed};
let mut parser = self;
loop {
match f(parser)? {
Next(p) => {
parser = p;
}
Parsed(output) => {
return Ok(output);
}
}
}
}
fn run_parser_async<F, E, S, Fut>(
self,
init: S,
f: F,
) -> impl Future<Output = Result<Self::Output, E>>
where
F: Fn(Self, S) -> Fut,
Fut: Future<Output = Result<Outcome<(Self, S), Self::Output>, E>>,
{
use Outcome::{Next, Parsed};
async move {
let mut parser = self;
let mut state = init;
loop {
match f(parser, state).await? {
Next((p, st)) => {
parser = p;
state = st;
}
Parsed(output) => {
return Ok(output);
}
}
}
}
}
}