1use zu_common::{Result, ZuError, gqlstatus::codes};
26
27use crate::arena::{MorselArena, Pod};
28use crate::bitmap::Bitmap;
29use crate::sel::SelVector;
30use crate::vector::{PhysType, ValueVector, VecEncoding};
31
32#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33pub enum BinOp {
34 Add,
35 Sub,
36 Mul,
37 Div,
38 Mod,
39}
40
41#[inline(always)]
45fn apply_i64(op: BinOp, a: i64, b: i64) -> i64 {
46 match op {
47 BinOp::Add => a.wrapping_add(b),
48 BinOp::Sub => a.wrapping_sub(b),
49 BinOp::Mul => a.wrapping_mul(b),
50 BinOp::Div => a.wrapping_div(if b == 0 { 1 } else { b }),
51 BinOp::Mod => a.wrapping_rem(if b == 0 { 1 } else { b }),
52 }
53}
54
55#[inline(always)]
56fn apply_f64(op: BinOp, a: f64, b: f64) -> f64 {
57 match op {
58 BinOp::Add => a + b,
59 BinOp::Sub => a - b,
60 BinOp::Mul => a * b,
61 BinOp::Div => a / b,
62 BinOp::Mod => a % b,
63 }
64}
65
66#[inline(always)]
77fn fill<T: Pod, F: Fn(T, T) -> T>(
78 dst: &mut [T],
79 l: &ValueVector,
80 r: &ValueVector,
81 len: usize,
82 f: F,
83) -> Result<()> {
84 match (l.encoding, r.encoding) {
85 (VecEncoding::Flat, VecEncoding::Flat) => {
86 let (a, b) = (l.values::<T>(), r.values::<T>());
87 for i in 0..len {
88 dst[i] = f(a[i], b[i]);
89 }
90 }
91 (VecEncoding::Flat, VecEncoding::Constant) => {
92 let a = l.values::<T>();
93 let c = r.constant_value::<T>();
94 for i in 0..len {
95 dst[i] = f(a[i], c);
96 }
97 }
98 (VecEncoding::Constant, VecEncoding::Flat) => {
99 let c = l.constant_value::<T>();
100 let b = r.values::<T>();
101 for i in 0..len {
102 dst[i] = f(c, b[i]);
103 }
104 }
105 _ => {
106 return Err(ZuError::InvalidArgument(
107 "arithmetic on dict vectors: materialize first".into(),
108 ));
109 }
110 }
111 Ok(())
112}
113
114pub fn binary(
122 arena: &mut MorselArena,
123 op: BinOp,
124 l: &ValueVector,
125 r: &ValueVector,
126 sel: Option<&SelVector>,
127) -> Result<ValueVector> {
128 debug_assert_eq!(l.len, r.len);
129 if l.phys != r.phys {
130 return Err(ZuError::InvalidArgument(format!(
131 "no arithmetic kernel for {:?} vs {:?}",
132 l.phys, r.phys
133 )));
134 }
135 let len = l.len as usize;
136 check(op, l, r, sel, len)?;
137 if let (VecEncoding::Constant, VecEncoding::Constant) = (l.encoding, r.encoding)
143 && matches!(
144 l.phys,
145 PhysType::Int64 | PhysType::Interval | PhysType::Float64
146 )
147 {
148 let mut out = match l.phys {
149 PhysType::Float64 => {
150 let v = apply_f64(op, l.constant_value::<f64>(), r.constant_value::<f64>());
151 ValueVector::constant(arena, l.phys, v, len)
152 }
153 _ => {
154 let v = apply_i64(op, l.constant_value::<i64>(), r.constant_value::<i64>());
155 ValueVector::constant(arena, l.phys, v, len)
156 }
157 };
158 out.validity = merged_validity(arena, l, r, len);
159 return Ok(out);
160 }
161 let mut out = ValueVector::flat_uninit(arena, l.phys, len);
162 match l.phys {
163 PhysType::Int64 | PhysType::Interval => {
164 {
165 let dst = out.values_mut::<i64>();
166 match op {
167 BinOp::Add => fill(dst, l, r, len, i64::wrapping_add)?,
168 BinOp::Sub => fill(dst, l, r, len, i64::wrapping_sub)?,
169 BinOp::Mul => fill(dst, l, r, len, i64::wrapping_mul)?,
170 BinOp::Div => fill(dst, l, r, len, |a: i64, b: i64| {
176 a.wrapping_div(if b == 0 { 1 } else { b })
177 })?,
178 BinOp::Mod => fill(dst, l, r, len, |a: i64, b: i64| {
179 a.wrapping_rem(if b == 0 { 1 } else { b })
180 })?,
181 }
182 }
183 out.validity = merged_validity(arena, l, r, len);
184 }
185 PhysType::Float64 => {
186 {
187 let dst = out.values_mut::<f64>();
188 match op {
189 BinOp::Add => fill(dst, l, r, len, |a: f64, b: f64| a + b)?,
190 BinOp::Sub => fill(dst, l, r, len, |a: f64, b: f64| a - b)?,
191 BinOp::Mul => fill(dst, l, r, len, |a: f64, b: f64| a * b)?,
192 BinOp::Div => fill(dst, l, r, len, |a: f64, b: f64| a / b)?,
193 BinOp::Mod => fill(dst, l, r, len, |a: f64, b: f64| a % b)?,
194 }
195 }
196 out.validity = merged_validity(arena, l, r, len);
197 }
198 _ => {
199 return Err(ZuError::InvalidArgument(format!(
200 "no arithmetic kernel for {:?}",
201 l.phys
202 )));
203 }
204 }
205 Ok(out)
206}
207
208fn divide_by_zero(op: BinOp) -> ZuError {
213 let what = if matches!(op, BinOp::Mod) {
214 "modulus"
215 } else {
216 "division"
217 };
218 ZuError::gql(codes::C22012, format!("{what} by zero"))
219}
220
221fn overflow() -> ZuError {
231 ZuError::gql(codes::C22003, "integer overflow".to_string())
232}
233
234fn check(
242 op: BinOp,
243 l: &ValueVector,
244 r: &ValueVector,
245 sel: Option<&SelVector>,
246 len: usize,
247) -> Result<()> {
248 let risky = match l.phys {
249 PhysType::Int64 | PhysType::Interval => match op {
250 BinOp::Add | BinOp::Sub => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 62,
257 BinOp::Mul => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 31,
258 BinOp::Div | BinOp::Mod => awkward_divisor(r, len),
261 },
262 PhysType::Float64 => matches!(op, BinOp::Div | BinOp::Mod) && zero_divisor_f64(r, len),
266 _ => false,
267 };
268 if !risky {
269 return Ok(());
270 }
271 let float = l.phys == PhysType::Float64;
272 let visit = |i: usize| -> Result<()> {
273 if !l.is_valid(i) || !r.is_valid(i) {
274 return Ok(());
275 }
276 if float {
277 if at_f64(r, i) == 0.0 {
278 return Err(divide_by_zero(op));
279 }
280 return Ok(());
281 }
282 let (a, b) = (at_i64(l, i), at_i64(r, i));
283 let fits = match op {
284 BinOp::Add => a.checked_add(b).is_some(),
285 BinOp::Sub => a.checked_sub(b).is_some(),
286 BinOp::Mul => a.checked_mul(b).is_some(),
287 BinOp::Div | BinOp::Mod => {
288 if b == 0 {
289 return Err(divide_by_zero(op));
290 }
291 a.checked_div(b).is_some()
292 }
293 };
294 if fits { Ok(()) } else { Err(overflow()) }
295 };
296 match sel {
297 Some(sel) => {
298 for &row in sel.as_slice() {
299 visit(row as usize)?;
300 }
301 }
302 None => {
303 for i in 0..len {
304 visit(i)?;
305 }
306 }
307 }
308 Ok(())
309}
310
311fn magnitude(v: &ValueVector, len: usize) -> u64 {
316 match v.encoding {
317 VecEncoding::Flat => v.values::<i64>()[..len]
318 .iter()
319 .fold(0u64, |acc, x| acc | x.unsigned_abs()),
320 VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
321 VecEncoding::Dict { .. } => u64::MAX,
322 }
323}
324
325fn awkward_divisor(v: &ValueVector, len: usize) -> bool {
327 match v.encoding {
328 VecEncoding::Flat => v.values::<i64>()[..len].iter().any(|&x| x == 0 || x == -1),
329 VecEncoding::Constant => matches!(v.constant_value::<i64>(), 0 | -1),
330 VecEncoding::Dict { .. } => true,
331 }
332}
333
334fn zero_divisor_f64(v: &ValueVector, len: usize) -> bool {
337 match v.encoding {
338 VecEncoding::Flat => v.values::<f64>()[..len].contains(&0.0),
341 VecEncoding::Constant => v.constant_value::<f64>() == 0.0,
342 VecEncoding::Dict { .. } => true,
343 }
344}
345
346fn at_i64(v: &ValueVector, i: usize) -> i64 {
347 match v.encoding {
348 VecEncoding::Constant => v.constant_value::<i64>(),
349 _ => v.values::<i64>()[i],
350 }
351}
352
353fn at_f64(v: &ValueVector, i: usize) -> f64 {
354 match v.encoding {
355 VecEncoding::Constant => v.constant_value::<f64>(),
356 _ => v.values::<f64>()[i],
357 }
358}
359
360fn merged_validity(
363 arena: &mut MorselArena,
364 l: &ValueVector,
365 r: &ValueVector,
366 len: usize,
367) -> Option<Bitmap> {
368 match (&l.validity, &r.validity) {
369 (None, None) => None,
370 (a, b) => {
371 let mut v = Bitmap::new_in(arena, len, true);
372 if let Some(a) = a {
373 v.and_with(a);
374 }
375 if let Some(b) = b {
376 v.and_with(b);
377 }
378 Some(v)
379 }
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386
387 use crate::sel::SelVector;
388
389 fn raised(out: Result<ValueVector>) -> String {
393 match out {
394 Ok(_) => panic!("the kernel answered where it has no answer"),
395 Err(err) => err.to_string(),
396 }
397 }
398
399 #[test]
400 fn add_flat_const() {
401 let mut arena = MorselArena::new();
402 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2, 3]);
403 let r = ValueVector::constant(&mut arena, PhysType::Int64, 10i64, 3);
404 let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
405 assert_eq!(out.values::<i64>(), &[11, 12, 13]);
406 assert!(out.validity.is_none());
407 }
408
409 #[test]
412 fn div_by_zero_raises() {
413 let mut arena = MorselArena::new();
414 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
415 let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
416 let out = binary(&mut arena, BinOp::Div, &l, &r, None);
417 assert_eq!(raised(out), "22012: division by zero");
418 let out = binary(&mut arena, BinOp::Mod, &l, &r, None);
419 assert_eq!(raised(out), "22012: modulus by zero");
420 }
421
422 #[test]
425 fn a_row_outside_the_selection_raises_nothing() {
426 let mut arena = MorselArena::new();
427 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
428 let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
429 let mut sel = SelVector::with_capacity(&mut arena, 2);
430 sel.push(0);
431 sel.push(2);
432 let out = binary(&mut arena, BinOp::Div, &l, &r, Some(&sel)).unwrap();
433 assert_eq!(out.values::<i64>()[0], 5);
434 assert_eq!(out.values::<i64>()[2], 10);
435 }
436
437 #[test]
440 fn a_null_operand_is_not_a_condition() {
441 let mut arena = MorselArena::new();
442 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
443 let mut r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
444 let mut valid = Bitmap::new_in(&mut arena, 3, true);
445 valid.clear(1);
446 r.validity = Some(valid);
447 let out = binary(&mut arena, BinOp::Div, &l, &r, None).unwrap();
448 assert!(!out.is_valid(1), "null in, null out");
449 }
450
451 #[test]
457 fn an_integer_answer_that_does_not_fit_raises() {
458 let mut arena = MorselArena::new();
459 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, i64::MAX]);
460 let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64, 2);
461 let out = binary(&mut arena, BinOp::Add, &l, &r, None);
462 assert_eq!(raised(out), "22003: integer overflow");
463
464 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 1 << 40]);
465 let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64 << 40, 2);
466 let out = binary(&mut arena, BinOp::Mul, &l, &r, None);
467 assert_eq!(raised(out), "22003: integer overflow");
468
469 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MIN]);
471 let r = ValueVector::constant(&mut arena, PhysType::Int64, -1i64, 1);
472 let out = binary(&mut arena, BinOp::Div, &l, &r, None);
473 assert_eq!(raised(out), "22003: integer overflow");
474 }
475
476 #[test]
480 fn a_float_divisor_of_nought_raises() {
481 let mut arena = MorselArena::new();
482 let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &[1.0f64, 2.0]);
483 let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 0.0]);
484 let out = binary(&mut arena, BinOp::Div, &l, &r, None);
485 assert_eq!(raised(out), "22012: division by zero");
486 }
487
488 #[test]
490 fn a_wide_answer_that_fits_is_an_answer() {
491 let mut arena = MorselArena::new();
492 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MAX, i64::MIN]);
493 let r = ValueVector::constant(&mut arena, PhysType::Int64, 0i64, 2);
494 let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
495 assert_eq!(out.values::<i64>(), &[i64::MAX, i64::MIN]);
496 }
497
498 #[test]
505 fn every_operation_answers_what_one_pair_answers() {
506 const OPS: [BinOp; 5] = [BinOp::Add, BinOp::Sub, BinOp::Mul, BinOp::Div, BinOp::Mod];
507 let whole: [i64; 4] = [7, -30, 1, 5];
508 let real: [f64; 4] = [7.5, -30.25, 1.0, 5.0];
509 let mut arena = MorselArena::new();
510 for op in OPS {
511 let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &whole);
512 let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 3, 4, 5]);
513 let c = ValueVector::constant(&mut arena, PhysType::Int64, 3i64, 4);
514 for (name, l, r) in [("flat flat", &l, &r), ("flat const", &l, &c)] {
515 let out = binary(&mut arena, op, l, r, None).unwrap();
516 for i in 0..4 {
517 let want = apply_i64(op, at_i64(l, i), at_i64(r, i));
518 assert_eq!(out.values::<i64>()[i], want, "{op:?} {name} row {i}");
519 }
520 }
521 let out = binary(&mut arena, op, &c, &r, None).unwrap();
522 for i in 0..4 {
523 let want = apply_i64(op, 3, at_i64(&r, i));
524 assert_eq!(out.values::<i64>()[i], want, "{op:?} const flat row {i}");
525 }
526
527 let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &real);
528 let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 3.0, 4.0, 0.5]);
529 let out = binary(&mut arena, op, &l, &r, None).unwrap();
530 for (i, x) in real.iter().enumerate() {
531 let want = apply_f64(op, *x, at_f64(&r, i));
532 assert_eq!(out.values::<f64>()[i], want, "{op:?} float row {i}");
533 }
534 }
535 }
536}