use super::*;
use crate::input::{Checkpoint, Cursor};
pub trait Inspector<'src, I: Input<'src>> {
type Checkpoint: Clone;
fn on_token(&mut self, token: &I::Token);
fn on_save<'parse>(&self, cursor: &Cursor<'src, 'parse, I>) -> Self::Checkpoint;
fn on_rewind<'parse>(&mut self, marker: &Checkpoint<'src, 'parse, I, Self::Checkpoint>);
}
impl<'src, I: Input<'src>> Inspector<'src, I> for () {
type Checkpoint = ();
#[inline(always)]
fn on_token(&mut self, _: &<I as Input<'src>>::Token) {}
#[inline(always)]
fn on_save<'parse>(&self, _: &Cursor<'src, 'parse, I>) -> Self::Checkpoint {}
#[inline(always)]
fn on_rewind<'parse>(&mut self, _: &Checkpoint<'src, 'parse, I, Self>) {}
}
#[derive(Copy, Clone, Default, Debug)]
pub struct SimpleState<T>(pub T);
impl<'src, T, I: Input<'src>> Inspector<'src, I> for SimpleState<T> {
type Checkpoint = ();
#[inline(always)]
fn on_token(&mut self, _: &<I as Input<'src>>::Token) {}
#[inline(always)]
fn on_save<'parse>(&self, _: &Cursor<'src, 'parse, I>) -> Self::Checkpoint {}
#[inline(always)]
fn on_rewind<'parse>(&mut self, _: &Checkpoint<'src, 'parse, I, Self::Checkpoint>) {}
}
impl<T> Deref for SimpleState<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for SimpleState<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for SimpleState<T> {
fn from(value: T) -> Self {
Self(value)
}
}
#[derive(Copy, Clone, Default, Debug)]
pub struct RollbackState<T>(pub T);
impl<'src, T: Clone, I: Input<'src>> Inspector<'src, I> for RollbackState<T> {
type Checkpoint = T;
#[inline(always)]
fn on_token(&mut self, _: &<I as Input<'src>>::Token) {}
#[inline(always)]
fn on_save<'parse>(&self, _: &Cursor<'src, 'parse, I>) -> Self::Checkpoint {
self.0.clone()
}
#[inline(always)]
fn on_rewind<'parse>(&mut self, cp: &Checkpoint<'src, 'parse, I, Self::Checkpoint>) {
self.0 = cp.inspector.clone();
}
}
impl<T> Deref for RollbackState<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for RollbackState<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for RollbackState<T> {
fn from(value: T) -> Self {
Self(value)
}
}
#[derive(Clone, Default, Debug)]
pub struct TruncateState<T>(pub Vec<T>);
impl<'src, T: Clone, I: Input<'src>> Inspector<'src, I> for TruncateState<T> {
type Checkpoint = usize;
#[inline(always)]
fn on_token(&mut self, _: &<I as Input<'src>>::Token) {}
#[inline(always)]
fn on_save<'parse>(&self, _: &Cursor<'src, 'parse, I>) -> Self::Checkpoint {
self.0.len()
}
#[inline(always)]
fn on_rewind<'parse>(&mut self, cp: &Checkpoint<'src, 'parse, I, Self::Checkpoint>) {
self.0.truncate(cp.inspector);
}
}
impl<T> Deref for TruncateState<T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for TruncateState<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<Vec<T>> for TruncateState<T> {
fn from(value: Vec<T>) -> Self {
Self(value)
}
}