use std::cell::Cell;
use relate_core::Result;
use crate::ctx::ExecCtx;
use crate::exec::pattern_policies::{MatchTail, Matched};
use crate::exec::pushdown::{MatchCap, Residual};
use crate::exec::rider::{PathProbe, Rider};
use crate::row::Row;
use crate::UsedSet;
pub(crate) struct MatchedSink<'r, 'a> {
residual: &'r Residual<'r>,
kind: SinkKind<'r, 'a>,
folded: usize,
}
enum SinkKind<'r, 'a> {
Probe(&'a PathProbe<'a>),
Collect {
tail: MatchTail<'r>,
out: &'r mut Matched,
cap: Option<&'r mut MatchCap<'a>>,
halt: &'r Cell<bool>,
},
Fold {
fold: &'r mut dyn FnMut(Row) -> Result<()>,
halt: &'r Cell<bool>,
},
}
impl<'r, 'a> MatchedSink<'r, 'a> {
pub(crate) fn new(
rider: Option<&'r mut Rider<'a, '_>>,
collect_halt: &'r Cell<bool>,
residual: &'r Residual<'r>,
tail: MatchTail<'r>,
out: &'r mut Matched,
) -> Self {
let kind = match rider {
Some(Rider::Probe(probe)) => SinkKind::Probe(probe),
Some(Rider::Cap(cap)) => SinkKind::Collect {
tail,
out,
cap: Some(&mut **cap),
halt: collect_halt,
},
None => SinkKind::Collect {
tail,
out,
cap: None,
halt: collect_halt,
},
};
Self {
residual,
kind,
folded: 0,
}
}
pub(crate) fn fold(
residual: &'r Residual<'r>,
halt: &'r Cell<bool>,
fold: &'r mut dyn FnMut(Row) -> Result<()>,
) -> Self {
Self {
residual,
kind: SinkKind::Fold { fold, halt },
folded: 0,
}
}
pub(super) fn residual(&self) -> &'r Residual<'r> {
self.residual
}
pub(super) fn halt_cell(&self) -> &'r Cell<bool> {
match &self.kind {
SinkKind::Probe(probe) => probe.halt,
SinkKind::Collect { halt, .. } | SinkKind::Fold { halt, .. } => halt,
}
}
pub(super) fn folded(&self) -> usize {
self.folded
}
pub(super) fn halted(&self) -> bool {
self.halt_cell().get()
}
pub(super) fn offer(
&mut self,
ctx: ExecCtx<'_>,
row: Row,
used: impl FnOnce() -> UsedSet,
) -> Result<()> {
let residual = self.residual;
match &mut self.kind {
SinkKind::Probe(probe) => {
ctx.graph.cancel_tick()?;
probe.accept_row(
ctx.graph,
row,
used(),
residual,
ctx.params,
ctx.cypher_version,
)?;
}
SinkKind::Collect {
tail,
out,
cap,
halt,
} => {
if let Some(row) = tail.finish_row(ctx.graph, row, cap.as_deref_mut())? {
tail.store_row(row, used, out);
}
if cap.as_ref().is_some_and(|cap| cap.full()) {
halt.set(true);
}
}
SinkKind::Fold { fold, .. } => {
ctx.graph.cancel_tick()?;
fold(row)?;
self.folded += 1;
}
}
Ok(())
}
}