use crate::{
any::TypeName,
effect::{Effect, ErasedEffective, ReadyExt as _},
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: 'c, 'b: 'c, 'c>(
&'a mut self,
scope: DynSequenceScope<'b, 'ctx, E>,
) -> ErasedEffective<'c, VisitResult<DynSequenceScope<'b, 'ctx, E>>, E>
where
'ctx: 'a;
}
pub struct SequenceProto<E: Effect>(Marker<E>);
impl<'a, 'ctx, E> TypeName::MemberTypeForLt<'a, 'ctx, &'a &'ctx ()> for SequenceProto<E>
where
E: Effect,
{
type T = dyn Sequence<'ctx, E> + Send + Sync + 'a;
}
impl<'a, 'ctx, E> TypeName::LowerTypeWithBound<'a, 'ctx, &'a &'ctx ()>
for dyn Sequence<'ctx, E> + Send + Sync + 'a
where
E: Effect,
{
type Higher = SequenceProto<E>;
}
pub trait SequenceScope<'ctx, E: Effect> {
fn size_hint(&mut self) -> ErasedEffective<'_, (usize, Option<usize>), E>;
fn next<'a: 'c, 'b: 'c, 'c>(
&'a mut self,
visitor: DynVisitor<'b, 'ctx>,
) -> ErasedEffective<'c, Flow, E>
where
'ctx: 'c + 'a + 'b;
}
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>),
}
impl<'a, 'ctx> Meta::MemberTypeForLt<'a, 'ctx, &'a &'ctx ()> for SequenceKnown {
type T = SequenceKnown;
}
impl<'a, 'ctx> Meta::LowerTypeWithBound<'a, 'ctx, &'a &'ctx ()> for SequenceKnown {
type Higher = SequenceKnown;
}
pub struct SequenceHint {
pub len: (usize, Option<usize>),
}
impl<'a, 'ctx> Meta::MemberTypeForLt<'a, 'ctx, &'a &'ctx ()> for SequenceHint {
type T = SequenceHint;
}
impl<'a, 'ctx> Meta::LowerTypeWithBound<'a, 'ctx, &'a &'ctx ()> for SequenceHint {
type Higher = 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 walk the sequence scope.
object.visit(scope)
} else {
// If the visitor doesn't support sequence then we continue.
VisitResult::Skipped(scope).ready()
}
}