use zu_common::{Result, ZuError, gqlstatus::codes};
use crate::arena::{MorselArena, Pod};
use crate::bitmap::Bitmap;
use crate::sel::SelVector;
use crate::vector::{PhysType, ValueVector, VecEncoding};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
}
#[inline(always)]
fn apply_i64(op: BinOp, a: i64, b: i64) -> i64 {
match op {
BinOp::Add => a.wrapping_add(b),
BinOp::Sub => a.wrapping_sub(b),
BinOp::Mul => a.wrapping_mul(b),
BinOp::Div => a.wrapping_div(if b == 0 { 1 } else { b }),
BinOp::Mod => a.wrapping_rem(if b == 0 { 1 } else { b }),
}
}
#[inline(always)]
fn apply_f64(op: BinOp, a: f64, b: f64) -> f64 {
match op {
BinOp::Add => a + b,
BinOp::Sub => a - b,
BinOp::Mul => a * b,
BinOp::Div => a / b,
BinOp::Mod => a % b,
}
}
#[inline(always)]
fn fill<T: Pod, F: Fn(T, T) -> T>(
dst: &mut [T],
l: &ValueVector,
r: &ValueVector,
len: usize,
f: F,
) -> Result<()> {
match (l.encoding, r.encoding) {
(VecEncoding::Flat, VecEncoding::Flat) => {
let (a, b) = (l.values::<T>(), r.values::<T>());
for i in 0..len {
dst[i] = f(a[i], b[i]);
}
}
(VecEncoding::Flat, VecEncoding::Constant) => {
let a = l.values::<T>();
let c = r.constant_value::<T>();
for i in 0..len {
dst[i] = f(a[i], c);
}
}
(VecEncoding::Constant, VecEncoding::Flat) => {
let c = l.constant_value::<T>();
let b = r.values::<T>();
for i in 0..len {
dst[i] = f(c, b[i]);
}
}
_ => {
return Err(ZuError::InvalidArgument(
"arithmetic on dict vectors: materialize first".into(),
));
}
}
Ok(())
}
pub fn binary(
arena: &mut MorselArena,
op: BinOp,
l: &ValueVector,
r: &ValueVector,
sel: Option<&SelVector>,
) -> Result<ValueVector> {
debug_assert_eq!(l.len, r.len);
if l.phys != r.phys {
return Err(ZuError::InvalidArgument(format!(
"no arithmetic kernel for {:?} vs {:?}",
l.phys, r.phys
)));
}
let len = l.len as usize;
check(op, l, r, sel, len)?;
if let (VecEncoding::Constant, VecEncoding::Constant) = (l.encoding, r.encoding)
&& matches!(
l.phys,
PhysType::Int64 | PhysType::Interval | PhysType::Float64
)
{
let mut out = match l.phys {
PhysType::Float64 => {
let v = apply_f64(op, l.constant_value::<f64>(), r.constant_value::<f64>());
ValueVector::constant(arena, l.phys, v, len)
}
_ => {
let v = apply_i64(op, l.constant_value::<i64>(), r.constant_value::<i64>());
ValueVector::constant(arena, l.phys, v, len)
}
};
out.validity = merged_validity(arena, l, r, len);
return Ok(out);
}
let mut out = ValueVector::flat_uninit(arena, l.phys, len);
match l.phys {
PhysType::Int64 | PhysType::Interval => {
{
let dst = out.values_mut::<i64>();
match op {
BinOp::Add => fill(dst, l, r, len, i64::wrapping_add)?,
BinOp::Sub => fill(dst, l, r, len, i64::wrapping_sub)?,
BinOp::Mul => fill(dst, l, r, len, i64::wrapping_mul)?,
BinOp::Div => fill(dst, l, r, len, |a: i64, b: i64| {
a.wrapping_div(if b == 0 { 1 } else { b })
})?,
BinOp::Mod => fill(dst, l, r, len, |a: i64, b: i64| {
a.wrapping_rem(if b == 0 { 1 } else { b })
})?,
}
}
out.validity = merged_validity(arena, l, r, len);
}
PhysType::Float64 => {
{
let dst = out.values_mut::<f64>();
match op {
BinOp::Add => fill(dst, l, r, len, |a: f64, b: f64| a + b)?,
BinOp::Sub => fill(dst, l, r, len, |a: f64, b: f64| a - b)?,
BinOp::Mul => fill(dst, l, r, len, |a: f64, b: f64| a * b)?,
BinOp::Div => fill(dst, l, r, len, |a: f64, b: f64| a / b)?,
BinOp::Mod => fill(dst, l, r, len, |a: f64, b: f64| a % b)?,
}
}
out.validity = merged_validity(arena, l, r, len);
}
_ => {
return Err(ZuError::InvalidArgument(format!(
"no arithmetic kernel for {:?}",
l.phys
)));
}
}
Ok(out)
}
fn divide_by_zero(op: BinOp) -> ZuError {
let what = if matches!(op, BinOp::Mod) {
"modulus"
} else {
"division"
};
ZuError::gql(codes::C22012, format!("{what} by zero"))
}
fn overflow() -> ZuError {
ZuError::gql(codes::C22003, "integer overflow".to_string())
}
fn check(
op: BinOp,
l: &ValueVector,
r: &ValueVector,
sel: Option<&SelVector>,
len: usize,
) -> Result<()> {
let risky = match l.phys {
PhysType::Int64 | PhysType::Interval => match op {
BinOp::Add | BinOp::Sub => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 62,
BinOp::Mul => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 31,
BinOp::Div | BinOp::Mod => awkward_divisor(r, len),
},
PhysType::Float64 => matches!(op, BinOp::Div | BinOp::Mod) && zero_divisor_f64(r, len),
_ => false,
};
if !risky {
return Ok(());
}
let float = l.phys == PhysType::Float64;
let visit = |i: usize| -> Result<()> {
if !l.is_valid(i) || !r.is_valid(i) {
return Ok(());
}
if float {
if at_f64(r, i) == 0.0 {
return Err(divide_by_zero(op));
}
return Ok(());
}
let (a, b) = (at_i64(l, i), at_i64(r, i));
let fits = match op {
BinOp::Add => a.checked_add(b).is_some(),
BinOp::Sub => a.checked_sub(b).is_some(),
BinOp::Mul => a.checked_mul(b).is_some(),
BinOp::Div | BinOp::Mod => {
if b == 0 {
return Err(divide_by_zero(op));
}
a.checked_div(b).is_some()
}
};
if fits { Ok(()) } else { Err(overflow()) }
};
match sel {
Some(sel) => {
for &row in sel.as_slice() {
visit(row as usize)?;
}
}
None => {
for i in 0..len {
visit(i)?;
}
}
}
Ok(())
}
fn magnitude(v: &ValueVector, len: usize) -> u64 {
match v.encoding {
VecEncoding::Flat => v.values::<i64>()[..len]
.iter()
.fold(0u64, |acc, x| acc | x.unsigned_abs()),
VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
VecEncoding::Dict { .. } => u64::MAX,
}
}
fn awkward_divisor(v: &ValueVector, len: usize) -> bool {
match v.encoding {
VecEncoding::Flat => v.values::<i64>()[..len].iter().any(|&x| x == 0 || x == -1),
VecEncoding::Constant => matches!(v.constant_value::<i64>(), 0 | -1),
VecEncoding::Dict { .. } => true,
}
}
fn zero_divisor_f64(v: &ValueVector, len: usize) -> bool {
match v.encoding {
VecEncoding::Flat => v.values::<f64>()[..len].contains(&0.0),
VecEncoding::Constant => v.constant_value::<f64>() == 0.0,
VecEncoding::Dict { .. } => true,
}
}
fn at_i64(v: &ValueVector, i: usize) -> i64 {
match v.encoding {
VecEncoding::Constant => v.constant_value::<i64>(),
_ => v.values::<i64>()[i],
}
}
fn at_f64(v: &ValueVector, i: usize) -> f64 {
match v.encoding {
VecEncoding::Constant => v.constant_value::<f64>(),
_ => v.values::<f64>()[i],
}
}
fn merged_validity(
arena: &mut MorselArena,
l: &ValueVector,
r: &ValueVector,
len: usize,
) -> Option<Bitmap> {
match (&l.validity, &r.validity) {
(None, None) => None,
(a, b) => {
let mut v = Bitmap::new_in(arena, len, true);
if let Some(a) = a {
v.and_with(a);
}
if let Some(b) = b {
v.and_with(b);
}
Some(v)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sel::SelVector;
fn raised(out: Result<ValueVector>) -> String {
match out {
Ok(_) => panic!("the kernel answered where it has no answer"),
Err(err) => err.to_string(),
}
}
#[test]
fn add_flat_const() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2, 3]);
let r = ValueVector::constant(&mut arena, PhysType::Int64, 10i64, 3);
let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
assert_eq!(out.values::<i64>(), &[11, 12, 13]);
assert!(out.validity.is_none());
}
#[test]
fn div_by_zero_raises() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
let out = binary(&mut arena, BinOp::Div, &l, &r, None);
assert_eq!(raised(out), "22012: division by zero");
let out = binary(&mut arena, BinOp::Mod, &l, &r, None);
assert_eq!(raised(out), "22012: modulus by zero");
}
#[test]
fn a_row_outside_the_selection_raises_nothing() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
let mut sel = SelVector::with_capacity(&mut arena, 2);
sel.push(0);
sel.push(2);
let out = binary(&mut arena, BinOp::Div, &l, &r, Some(&sel)).unwrap();
assert_eq!(out.values::<i64>()[0], 5);
assert_eq!(out.values::<i64>()[2], 10);
}
#[test]
fn a_null_operand_is_not_a_condition() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
let mut r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
r.validity = Some(valid);
let out = binary(&mut arena, BinOp::Div, &l, &r, None).unwrap();
assert!(!out.is_valid(1), "null in, null out");
}
#[test]
fn an_integer_answer_that_does_not_fit_raises() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, i64::MAX]);
let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64, 2);
let out = binary(&mut arena, BinOp::Add, &l, &r, None);
assert_eq!(raised(out), "22003: integer overflow");
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 1 << 40]);
let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64 << 40, 2);
let out = binary(&mut arena, BinOp::Mul, &l, &r, None);
assert_eq!(raised(out), "22003: integer overflow");
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MIN]);
let r = ValueVector::constant(&mut arena, PhysType::Int64, -1i64, 1);
let out = binary(&mut arena, BinOp::Div, &l, &r, None);
assert_eq!(raised(out), "22003: integer overflow");
}
#[test]
fn a_float_divisor_of_nought_raises() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &[1.0f64, 2.0]);
let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 0.0]);
let out = binary(&mut arena, BinOp::Div, &l, &r, None);
assert_eq!(raised(out), "22012: division by zero");
}
#[test]
fn a_wide_answer_that_fits_is_an_answer() {
let mut arena = MorselArena::new();
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MAX, i64::MIN]);
let r = ValueVector::constant(&mut arena, PhysType::Int64, 0i64, 2);
let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
assert_eq!(out.values::<i64>(), &[i64::MAX, i64::MIN]);
}
#[test]
fn every_operation_answers_what_one_pair_answers() {
const OPS: [BinOp; 5] = [BinOp::Add, BinOp::Sub, BinOp::Mul, BinOp::Div, BinOp::Mod];
let whole: [i64; 4] = [7, -30, 1, 5];
let real: [f64; 4] = [7.5, -30.25, 1.0, 5.0];
let mut arena = MorselArena::new();
for op in OPS {
let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &whole);
let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 3, 4, 5]);
let c = ValueVector::constant(&mut arena, PhysType::Int64, 3i64, 4);
for (name, l, r) in [("flat flat", &l, &r), ("flat const", &l, &c)] {
let out = binary(&mut arena, op, l, r, None).unwrap();
for i in 0..4 {
let want = apply_i64(op, at_i64(l, i), at_i64(r, i));
assert_eq!(out.values::<i64>()[i], want, "{op:?} {name} row {i}");
}
}
let out = binary(&mut arena, op, &c, &r, None).unwrap();
for i in 0..4 {
let want = apply_i64(op, 3, at_i64(&r, i));
assert_eq!(out.values::<i64>()[i], want, "{op:?} const flat row {i}");
}
let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &real);
let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 3.0, 4.0, 0.5]);
let out = binary(&mut arena, op, &l, &r, None).unwrap();
for (i, x) in real.iter().enumerate() {
let want = apply_f64(op, *x, at_f64(&r, i));
assert_eq!(out.values::<f64>()[i], want, "{op:?} float row {i}");
}
}
}
}