use crate::{
any::TypeName,
effect::{Effect, Effective, ErasedEffective},
higher_ranked_type,
hkt::Marker,
protocol::{
walker::hint::{HintMeta, Meta},
DynVisitor,
},
Flow,
};
use super::VisitResult;
/// Protocol for visiting a sequence.
///
/// This protocol uses a scope to give temporary control to the visitor.
/// The visitor will drive the walker for each item.
pub trait Sequence<'ctx, E: Effect> {
fn visit<'a>(
&'a mut self,
scope: DynSequenceScope<'a, 'ctx, E>,
) -> ErasedEffective<'a, VisitResult<DynSequenceScope<'a, 'ctx, E>>, E>;
}
pub struct SequenceProto<E: Effect>(Marker<E>);
higher_ranked_type! {
impl TypeName {
impl['a, 'ctx, E] type T['a, 'ctx] for SequenceProto<E> =
dyn Sequence<'ctx, E> + Send + Sync + 'a
where {
E: Effect
};
impl['a, 'ctx, E] type HigherRanked['a, 'ctx] for dyn Sequence<'ctx, E> + Send + Sync + 'a =
SequenceProto<E>
where {
E: Effect
};
}
}
pub trait SequenceScope<'ctx, E: Effect> {
fn size_hint(&mut self) -> ErasedEffective<'_, (usize, Option<usize>), E>;
fn next<'a>(&'a mut self, visitor: DynVisitor<'a, 'ctx>) -> ErasedEffective<'a, Flow, E>;
}
pub type DynSequenceScope<'a, 'ctx, E> = &'a mut (dyn SequenceScope<'ctx, E> + Send + Sync + 'a);
#[derive(Default)]
pub struct SequenceKnown {
pub len: (usize, Option<usize>),
}
higher_ranked_type! {
impl Meta {
impl['a, 'ctx] type T['a, 'ctx] for SequenceKnown =
SequenceKnown;
impl['a, 'ctx] type HigherRanked['a, 'ctx] for SequenceKnown =
SequenceKnown;
}
}
pub struct SequenceHint {
pub len: (usize, Option<usize>),
}
higher_ranked_type! {
impl Meta {
impl['a, 'ctx] type T['a, 'ctx] for SequenceHint =
SequenceHint;
impl['a, 'ctx] type HigherRanked['a, 'ctx] for SequenceHint =
SequenceHint;
}
}
impl<E: Effect> HintMeta for SequenceProto<E> {
type Known = SequenceKnown;
type Hint = SequenceHint;
type Effect = E;
}
#[inline(always)]
pub fn visit_sequence<'a, 'ctx, E: Effect>(
visitor: DynVisitor<'a, 'ctx>,
scope: DynSequenceScope<'a, 'ctx, E>,
) -> ErasedEffective<'a, VisitResult<DynSequenceScope<'a, 'ctx, E>>, E> {
if let Some(object) = visitor.0.upcast_mut::<SequenceProto<E>>() {
// Allow the visitor to give a hint if it wants.
object.visit(scope)
} else {
// If the visitor doesn't support request hint then we continue.
E::ready(VisitResult::Skipped(scope)).into_erased()
}
}