use std::collections::BTreeMap;
use relate_core::{Result, Value};
use relate_ir::Expr;
use crate::eval::{eval, PercentileSample};
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::row::Row;
pub(super) struct OperandPool<'e> {
operand: &'e Expr,
pub(super) lenient: bool,
sample: PercentileSample,
charged: usize,
stopped: bool,
non_numeric: bool,
}
impl<'e> OperandPool<'e> {
pub(super) fn new(operand: &'e Expr, lenient: bool) -> Self {
Self {
operand,
lenient,
sample: PercentileSample::default(),
charged: 0,
stopped: false,
non_numeric: false,
}
}
pub(super) fn open(&self) -> Self {
Self::new(self.operand, self.lenient)
}
pub(super) fn reads(&self, operand: &Expr) -> bool {
self.operand == operand
}
pub(super) fn stop(&mut self) {
self.stopped = true;
}
pub(super) fn offer(
&mut self,
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<()> {
if self.stopped {
return Ok(());
}
graph.cancel_tick()?;
let value = eval(graph, row, self.operand, params, cypher_version)?;
if self.sample.offer(&value).is_err() {
self.stopped = true;
self.non_numeric = true;
}
Ok(())
}
pub(super) fn settle(
&mut self,
graph: &ExecGraph<'_>,
total: &mut RetainedTotal,
) -> Result<()> {
let len = self.sample.len();
if len > self.charged {
total.add_bytes(
graph,
crate::workspace::buffer_growth(self.charged, len, size_of::<f64>() as u64),
)?;
self.charged = len;
}
Ok(())
}
pub(super) fn finish(self) -> SortedPool {
SortedPool {
vals: self.sample.into_sorted(),
non_numeric: self.non_numeric,
}
}
}
pub(super) struct SortedPool {
pub(super) vals: Vec<f64>,
pub(super) non_numeric: bool,
}
pub(super) fn shareable(operand: &Expr) -> bool {
match operand {
Expr::Null
| Expr::Bool(_)
| Expr::Int(_)
| Expr::Float(_)
| Expr::String(_)
| Expr::Parameter(_)
| Expr::Variable(_) => true,
Expr::Property { expr, .. } | Expr::Unary { expr, .. } => shareable(expr),
Expr::Binary { left, right, .. } => shareable(left) && shareable(right),
_ => false,
}
}