use std::ops::Range;
use vortex_error::VortexResult;
use vortex_mask::Mask;
use vortex_session::VortexSession;
use super::DEFAULT_CAPACITY;
use super::port::PortId;
use super::port::SourceEnd;
use super::scan::Core;
use super::values::ValueCache;
use crate::execution::operator::Operator;
use crate::execution::operator::Source;
use crate::plan::ConcatPlan;
use crate::plan::PlanRef;
use crate::source::SegmentId;
pub struct Chain {
pub(crate) source: Box<dyn Source>,
pub(crate) stages: Vec<Box<dyn Operator>>,
pub(crate) inlets: Vec<PortId>,
}
impl Chain {
pub fn new(source: impl Source + 'static) -> Self {
Self {
source: Box::new(source),
stages: Vec::new(),
inlets: Vec::new(),
}
}
pub fn with(mut self, stage: impl Operator + 'static) -> Self {
self.stages.push(Box::new(stage));
self
}
}
impl Core {
pub(crate) fn compile(
&mut self,
plan: &PlanRef,
rows: Range<u64>,
mask: &Mask,
) -> VortexResult<Option<Chain>> {
Compiler { core: self }.compile(plan, rows, mask)
}
}
pub struct Compiler<'a> {
pub(crate) core: &'a mut Core,
}
impl Compiler<'_> {
pub fn compile(
&mut self,
plan: &PlanRef,
rows: Range<u64>,
mask: &Mask,
) -> VortexResult<Option<Chain>> {
if rows.start >= rows.end {
return Ok(None);
}
plan.compile(rows, mask, self)
}
pub fn join(&mut self, chains: Vec<Chain>, source: impl Source + 'static) -> Chain {
self.join_with(chains, |_| DEFAULT_CAPACITY, source)
}
pub fn join_with(
&mut self,
chains: Vec<Chain>,
capacity: impl Fn(usize) -> usize,
source: impl Source + 'static,
) -> Chain {
let inlets = chains
.into_iter()
.enumerate()
.map(|(index, chain)| {
let port = self
.core
.arena
.create(capacity(index), None, SourceEnd::Unclaimed);
self.core.add_pipeline(chain, smallvec::smallvec![port]);
port
})
.collect();
Chain {
source: Box::new(source),
stages: Vec::new(),
inlets,
}
}
pub fn row_offset(&self) -> u64 {
self.core.row_offset
}
pub fn session(&self) -> &VortexSession {
&self.core.session
}
pub(crate) fn values(&self) -> &ValueCache {
&self.core.values
}
pub fn register_segment(&mut self, segment: SegmentId) {
self.core.segments.push(segment);
}
}
pub(crate) fn overlapping<'a>(
concat: &'a ConcatPlan,
rows: &Range<u64>,
) -> impl Iterator<Item = (usize, u64, Range<u64>)> + 'a {
let offsets = concat.row_offsets();
let first = offsets
.partition_point(|&offset| offset <= rows.start)
.saturating_sub(1);
let end = offsets.partition_point(|&offset| offset < rows.end);
let rows = rows.clone();
(first..end).filter_map(move |index| {
let start = offsets[index];
let chunk_end = offsets
.get(index + 1)
.copied()
.unwrap_or_else(|| concat.row_count());
let local = rows.start.max(start)..rows.end.min(chunk_end);
(local.start < local.end).then_some((index, start, local))
})
}