1use zu_common::{Result, ZuError, gqlstatus::codes};
34
35use crate::arena::{MorselArena, Pod};
36use crate::bitmap::Bitmap;
37use crate::sel::SelVector;
38use crate::vector::{PhysType, ValueVector, VecEncoding};
39
40#[inline(always)]
48fn fill1<S: Pod, D: Pod, F: Fn(S) -> D>(dst: &mut [D], v: &ValueVector, len: usize, f: F) {
49 match v.encoding {
50 VecEncoding::Constant => dst[..len].fill(f(v.constant_value::<S>())),
51 _ => {
52 let src = v.values::<S>();
53 for i in 0..len {
54 dst[i] = f(src[i]);
55 }
56 }
57 }
58}
59
60#[inline(always)]
63fn fill2<S: Pod, D: Pod, F: Fn(S, S) -> D>(
64 dst: &mut [D],
65 l: &ValueVector,
66 r: &ValueVector,
67 len: usize,
68 f: F,
69) {
70 match (l.encoding, r.encoding) {
71 (VecEncoding::Constant, VecEncoding::Constant) => {
72 dst[..len].fill(f(l.constant_value::<S>(), r.constant_value::<S>()));
73 }
74 (VecEncoding::Constant, _) => {
75 let c = l.constant_value::<S>();
76 let b = r.values::<S>();
77 for i in 0..len {
78 dst[i] = f(c, b[i]);
79 }
80 }
81 (_, VecEncoding::Constant) => {
82 let a = l.values::<S>();
83 let c = r.constant_value::<S>();
84 for i in 0..len {
85 dst[i] = f(a[i], c);
86 }
87 }
88 _ => {
89 let (a, b) = (l.values::<S>(), r.values::<S>());
90 for i in 0..len {
91 dst[i] = f(a[i], b[i]);
92 }
93 }
94 }
95}
96
97#[derive(Clone, Copy, PartialEq, Eq, Debug)]
103pub enum MathOp {
104 Abs,
105 Ceil,
106 Floor,
107 Sign,
108 Round(i64),
109 Sqrt,
110 Exp,
111 Ln,
112 Log10,
113 Sin,
114 Cos,
115 Tan,
116 Cot,
117 Asin,
118 Acos,
119 Atan,
120 Degrees,
121 Radians,
122}
123
124impl MathOp {
125 fn name(self) -> &'static str {
128 match self {
129 MathOp::Abs => "abs",
130 MathOp::Ceil => "ceil",
131 MathOp::Floor => "floor",
132 MathOp::Sign => "sign",
133 MathOp::Round(_) => "round",
134 MathOp::Sqrt => "sqrt",
135 MathOp::Exp => "exp",
136 MathOp::Ln => "ln",
137 MathOp::Log10 => "log10",
138 MathOp::Sin => "sin",
139 MathOp::Cos => "cos",
140 MathOp::Tan => "tan",
141 MathOp::Cot => "cot",
142 MathOp::Asin => "asin",
143 MathOp::Acos => "acos",
144 MathOp::Atan => "atan",
145 MathOp::Degrees => "degrees",
146 MathOp::Radians => "radians",
147 }
148 }
149
150 fn is_real(self) -> bool {
154 !matches!(
155 self,
156 MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Sign | MathOp::Round(_)
157 )
158 }
159
160 pub fn may_raise(self) -> bool {
165 match self {
166 MathOp::Abs => true,
170 MathOp::Round(digits) => digits != 0,
171 MathOp::Ceil | MathOp::Floor | MathOp::Sign => false,
172 MathOp::Sin | MathOp::Cos | MathOp::Tan | MathOp::Atan | MathOp::Radians => false,
178 _ => true,
179 }
180 }
181
182 pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
184 match (self, arg) {
185 (_, PhysType::Int64 | PhysType::Float64) if self.is_real() => Some(PhysType::Float64),
186 (MathOp::Sign, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Int64),
187 (_, PhysType::Int64) => Some(PhysType::Int64),
188 (_, PhysType::Float64) => Some(PhysType::Float64),
189 _ => None,
190 }
191 }
192}
193
194pub fn unary(
202 arena: &mut MorselArena,
203 op: MathOp,
204 v: &ValueVector,
205 sel: Option<&SelVector>,
206) -> Result<ValueVector> {
207 let len = v.len as usize;
208 if matches!(v.encoding, VecEncoding::Dict { .. }) {
209 return Err(ZuError::InvalidArgument(
210 "numeric functions on dict vectors: materialize first".into(),
211 ));
212 }
213 let Some(answer) = op.answer_type(v.phys) else {
214 return Err(ZuError::InvalidArgument(format!(
215 "no {}() kernel for {:?}",
216 op.name(),
217 v.phys
218 )));
219 };
220 check(op, v, sel, len)?;
221 let mut out = ValueVector::flat_uninit(arena, answer, len);
222 match (v.phys, answer) {
223 (PhysType::Int64, PhysType::Int64) => fill_exact(op, out.values_mut::<i64>(), v, len),
224 (PhysType::Float64, PhysType::Int64) => {
225 fill1(out.values_mut::<i64>(), v, len, sign_f64);
226 }
227 (PhysType::Int64, PhysType::Float64) => {
230 fill_real(op, out.values_mut::<f64>(), v, len, |x: i64| x as f64);
231 }
232 (PhysType::Float64, PhysType::Float64) => {
233 fill_real(op, out.values_mut::<f64>(), v, len, |x: f64| x);
234 }
235 _ => unreachable!("answer_type answers for these four shapes only"),
236 }
237 out.validity = v.validity.as_ref().map(|valid| {
240 let mut copy = Bitmap::new_in(arena, len, true);
241 copy.and_with(valid);
242 copy
243 });
244 Ok(out)
245}
246
247#[derive(Clone, Copy, PartialEq, Eq, Debug)]
257pub enum MathPair {
258 Power,
259 Log,
260 Mod,
261}
262
263impl MathPair {
264 fn name(self) -> &'static str {
265 match self {
266 MathPair::Power => "power",
267 MathPair::Log => "log",
268 MathPair::Mod => "mod",
269 }
270 }
271
272 pub fn answer_type(self, l: PhysType, r: PhysType) -> Option<PhysType> {
276 if l != r {
277 return None;
278 }
279 match (self, l) {
280 (MathPair::Mod, PhysType::Int64) => Some(PhysType::Int64),
283 (_, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Float64),
284 _ => None,
285 }
286 }
287}
288
289pub fn pair(
298 arena: &mut MorselArena,
299 op: MathPair,
300 l: &ValueVector,
301 r: &ValueVector,
302 sel: Option<&SelVector>,
303) -> Result<ValueVector> {
304 debug_assert_eq!(l.len, r.len);
305 if matches!(l.encoding, VecEncoding::Dict { .. })
306 || matches!(r.encoding, VecEncoding::Dict { .. })
307 {
308 return Err(ZuError::InvalidArgument(
309 "numeric functions on dict vectors: materialize first".into(),
310 ));
311 }
312 let Some(answer) = op.answer_type(l.phys, r.phys) else {
313 return Err(ZuError::InvalidArgument(format!(
314 "no {}() kernel for {:?} and {:?}",
315 op.name(),
316 l.phys,
317 r.phys
318 )));
319 };
320 let len = l.len as usize;
321 let mut out = ValueVector::flat_uninit(arena, answer, len);
322 match answer {
323 PhysType::Int64 => {
324 fill2(out.values_mut::<i64>(), l, r, len, |x: i64, y: i64| {
328 x.wrapping_rem(if y == 0 { 1 } else { y })
329 });
330 }
331 _ if l.phys == PhysType::Int64 => {
332 fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: i64| x as f64);
333 }
334 _ => {
335 fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: f64| x);
336 }
337 }
338 verify_pair(op, l, r, &out, sel, len)?;
339 out.validity = merged_validity(arena, l, r, len);
342 Ok(out)
343}
344
345#[inline(always)]
349fn fill_pair_real<S: Pod, C: Fn(S) -> f64 + Copy>(
350 op: MathPair,
351 dst: &mut [f64],
352 l: &ValueVector,
353 r: &ValueVector,
354 len: usize,
355 conv: C,
356) {
357 match op {
358 MathPair::Power => fill2(dst, l, r, len, |x, y| conv(x).powf(conv(y))),
359 MathPair::Log => fill2(dst, l, r, len, |x, y| conv(y).log(conv(x))),
362 MathPair::Mod => fill2(dst, l, r, len, |x, y| conv(x) % conv(y)),
363 }
364}
365
366fn verify_pair(
369 op: MathPair,
370 l: &ValueVector,
371 r: &ValueVector,
372 out: &ValueVector,
373 sel: Option<&SelVector>,
374 len: usize,
375) -> Result<()> {
376 if !risky_pair(op, l, r, out, len) {
377 return Ok(());
378 }
379 let visit = |i: usize| -> Result<()> {
380 if !l.is_valid(i) || !r.is_valid(i) {
381 return Ok(());
382 }
383 if out.phys == PhysType::Int64 {
384 let (x, y) = (at_i64(l, i), at_i64(r, i));
385 if y == 0 {
386 return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
387 }
388 return x.checked_rem(y).map(|_| ()).ok_or_else(|| {
389 out_of_range(op.name(), format!("of {x} and {y} does not fit an integer"))
390 });
391 }
392 one_pair(op, arg_f64(l, i), arg_f64(r, i), out.values::<f64>()[i])
393 };
394 match sel {
395 Some(sel) => {
396 for &row in sel.as_slice() {
397 visit(row as usize)?;
398 }
399 }
400 None => {
401 for i in 0..len {
402 visit(i)?;
403 }
404 }
405 }
406 Ok(())
407}
408
409fn risky_pair(
411 op: MathPair,
412 l: &ValueVector,
413 r: &ValueVector,
414 out: &ValueVector,
415 len: usize,
416) -> bool {
417 if out.phys == PhysType::Int64 {
418 let (lo, hi) = span(r, len);
423 return (lo <= 0.0 && hi >= 0.0) || (lo <= -1.0 && hi >= -1.0);
424 }
425 if !all_finite(out, len) {
430 return true;
431 }
432 let (lo, hi) = span(l, len);
433 match op {
434 MathPair::Power => lo <= 0.0,
438 MathPair::Log => {
443 let base = lo > 1.0 || (lo > 0.0 && hi < 1.0);
444 !base || span(r, len).0 <= 0.0
445 }
446 MathPair::Mod => {
447 let (lo, hi) = span(r, len);
448 lo <= 0.0 && hi >= 0.0
449 }
450 }
451}
452
453fn one_pair(op: MathPair, x: f64, y: f64, answer: f64) -> Result<()> {
456 match op {
457 MathPair::Mod if y == 0.0 => {
458 return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
459 }
460 MathPair::Power if x == 0.0 && y < 0.0 => {
461 return Err(ZuError::gql(
462 codes::C2201F,
463 "power() has no answer for nought raised to a negative power".to_string(),
464 ));
465 }
466 MathPair::Power if x < 0.0 && y.fract() != 0.0 && y.is_finite() => {
467 return Err(ZuError::gql(
468 codes::C2201F,
469 format!("power() has no answer for {x} raised to {y}, which is not whole"),
470 ));
471 }
472 MathPair::Log if x <= 0.0 || x == 1.0 => {
473 return Err(ZuError::gql(
474 codes::C2201E,
475 format!("log() has no answer in base {x}"),
476 ));
477 }
478 MathPair::Log if y <= 0.0 => {
479 return Err(ZuError::gql(
480 codes::C2201E,
481 format!("log() has no answer for {y}, which is not above nought"),
482 ));
483 }
484 _ => {}
485 }
486 if answer.is_finite() || !x.is_finite() || !y.is_finite() {
487 Ok(())
488 } else {
489 Err(out_of_range(
490 op.name(),
491 format!("of {x} and {y} is outside the range of a float"),
492 ))
493 }
494}
495
496fn all_finite(out: &ValueVector, len: usize) -> bool {
498 out.values::<f64>()[..len].iter().all(|x| x.is_finite())
499}
500
501fn merged_validity(
504 arena: &mut MorselArena,
505 l: &ValueVector,
506 r: &ValueVector,
507 len: usize,
508) -> Option<Bitmap> {
509 if l.validity.is_none() && r.validity.is_none() {
510 return None;
511 }
512 let mut copy = Bitmap::new_in(arena, len, true);
513 if let Some(valid) = l.validity.as_ref() {
514 copy.and_with(valid);
515 }
516 if let Some(valid) = r.validity.as_ref() {
517 copy.and_with(valid);
518 }
519 Some(copy)
520}
521
522#[inline(always)]
529fn fill_exact(op: MathOp, dst: &mut [i64], v: &ValueVector, len: usize) {
530 match op {
531 MathOp::Abs => fill1(dst, v, len, i64::wrapping_abs),
532 MathOp::Sign => fill1(dst, v, len, i64::signum),
533 MathOp::Ceil | MathOp::Floor => fill1(dst, v, len, |x: i64| x),
538 MathOp::Round(digits) if digits >= 0 => fill1(dst, v, len, |x: i64| x),
539 MathOp::Round(digits) => fill1(dst, v, len, move |x: i64| {
540 rounded_int(x, digits).unwrap_or(0)
541 }),
542 _ => unreachable!("the approximate half answers a float"),
543 }
544}
545
546#[inline(always)]
557fn fill_real<S: Pod, C: Fn(S) -> f64 + Copy>(
558 op: MathOp,
559 dst: &mut [f64],
560 v: &ValueVector,
561 len: usize,
562 conv: C,
563) {
564 match op {
565 MathOp::Abs => fill1(dst, v, len, |x| conv(x).abs()),
566 MathOp::Ceil => fill1(dst, v, len, |x| conv(x).ceil()),
567 MathOp::Floor => fill1(dst, v, len, |x| conv(x).floor()),
568 MathOp::Round(0) => fill1(dst, v, len, |x| conv(x).round()),
569 MathOp::Round(digits) => {
570 let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
571 fill1(dst, v, len, move |x| (conv(x) * scale).round() / scale);
572 }
573 MathOp::Sqrt => fill1(dst, v, len, |x| conv(x).sqrt()),
574 MathOp::Exp => fill1(dst, v, len, |x| conv(x).exp()),
575 MathOp::Ln => fill1(dst, v, len, |x| conv(x).ln()),
576 MathOp::Log10 => fill1(dst, v, len, |x| conv(x).log10()),
577 MathOp::Sin => fill1(dst, v, len, |x| conv(x).sin()),
578 MathOp::Cos => fill1(dst, v, len, |x| conv(x).cos()),
579 MathOp::Tan => fill1(dst, v, len, |x| conv(x).tan()),
580 MathOp::Cot => fill1(dst, v, len, |x| cot(conv(x))),
586 MathOp::Asin => fill1(dst, v, len, |x| conv(x).asin()),
587 MathOp::Acos => fill1(dst, v, len, |x| conv(x).acos()),
588 MathOp::Atan => fill1(dst, v, len, |x| conv(x).atan()),
589 MathOp::Degrees => fill1(dst, v, len, |x| conv(x).to_degrees()),
590 MathOp::Radians => fill1(dst, v, len, |x| conv(x).to_radians()),
591 MathOp::Sign => unreachable!("sign answers an integer"),
592 }
593}
594
595#[inline(never)]
607pub fn cot(x: f64) -> f64 {
608 x.cos() / x.sin()
609}
610
611#[inline(always)]
612fn sign_f64(x: f64) -> i64 {
613 if x > 0.0 {
614 1
615 } else if x < 0.0 {
616 -1
617 } else {
618 0
619 }
620}
621
622fn rounded_int(value: i64, digits: i64) -> Option<i64> {
627 let places = u32::try_from(-digits).ok()?;
628 if places > 19 {
631 return Some(0);
632 }
633 let factor = 10i128.checked_pow(places)?;
634 let value = value as i128;
635 let half = factor / 2;
636 let carried = if value >= 0 {
637 (value + half) / factor
638 } else {
639 (value - half) / factor
640 };
641 i64::try_from(carried.checked_mul(factor)?).ok()
642}
643
644fn check(op: MathOp, v: &ValueVector, sel: Option<&SelVector>, len: usize) -> Result<()> {
651 if !risky(op, v, len) {
652 return Ok(());
653 }
654 let visit = |i: usize| -> Result<()> {
655 if !v.is_valid(i) {
656 return Ok(());
657 }
658 match v.phys {
659 PhysType::Int64 if !op.is_real() => {
660 let x = at_i64(v, i);
661 match op {
662 MathOp::Abs => x.checked_abs().map(|_| ()).ok_or_else(|| {
663 out_of_range(
664 op.name(),
665 format!("of {x} is one past the top of an integer"),
666 )
667 }),
668 MathOp::Round(digits) => rounded_int(x, digits).map(|_| ()).ok_or_else(|| {
669 out_of_range(op.name(), format!("of {x} to {digits} digits does not fit"))
670 }),
671 _ => Ok(()),
672 }
673 }
674 _ => one_real(op, arg_f64(v, i)),
675 }
676 };
677 match sel {
678 Some(sel) => {
679 for &row in sel.as_slice() {
680 visit(row as usize)?;
681 }
682 }
683 None => {
684 for i in 0..len {
685 visit(i)?;
686 }
687 }
688 }
689 Ok(())
690}
691
692fn risky(op: MathOp, v: &ValueVector, len: usize) -> bool {
696 if !op.may_raise() {
697 return false;
698 }
699 if op.is_real() {
700 let (lo, hi) = span(v, len);
701 return match op {
702 MathOp::Sqrt => lo < 0.0,
703 MathOp::Ln | MathOp::Log10 => lo <= 0.0,
704 MathOp::Asin | MathOp::Acos => lo < -1.0 || hi > 1.0,
705 MathOp::Exp => hi > 709.0,
708 MathOp::Degrees => lo <= -3.0e306 || hi >= 3.0e306,
712 _ => true,
717 };
718 }
719 match (v.phys, op) {
720 (PhysType::Int64, MathOp::Abs) => magnitude(v, len) >= 1u64 << 63,
725 (PhysType::Int64, MathOp::Round(digits)) => digits < 0,
730 (PhysType::Float64, MathOp::Round(digits)) => digits != 0,
735 _ => false,
736 }
737}
738
739fn real(op: MathOp, x: f64) -> f64 {
745 match op {
746 MathOp::Abs => x.abs(),
747 MathOp::Ceil => x.ceil(),
748 MathOp::Floor => x.floor(),
749 MathOp::Round(0) => x.round(),
750 MathOp::Round(digits) => {
751 let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
752 (x * scale).round() / scale
753 }
754 MathOp::Sqrt => x.sqrt(),
755 MathOp::Exp => x.exp(),
756 MathOp::Ln => x.ln(),
757 MathOp::Log10 => x.log10(),
758 MathOp::Sin => x.sin(),
759 MathOp::Cos => x.cos(),
760 MathOp::Tan => x.tan(),
761 MathOp::Cot => cot(x),
762 MathOp::Asin => x.asin(),
763 MathOp::Acos => x.acos(),
764 MathOp::Atan => x.atan(),
765 MathOp::Degrees => x.to_degrees(),
766 MathOp::Radians => x.to_radians(),
767 MathOp::Sign => unreachable!("sign answers an integer"),
768 }
769}
770
771fn one_real(op: MathOp, x: f64) -> Result<()> {
775 match op {
776 MathOp::Sqrt if x < 0.0 => {
780 return Err(ZuError::gql(
781 codes::C2201F,
782 format!("sqrt() has no answer for {x}, which is below nought"),
783 ));
784 }
785 MathOp::Ln | MathOp::Log10 if x <= 0.0 => {
786 return Err(ZuError::gql(
787 codes::C2201E,
788 format!(
789 "{}() has no answer for {x}, which is not above nought",
790 op.name()
791 ),
792 ));
793 }
794 MathOp::Cot if x.sin() == 0.0 => {
795 return Err(ZuError::gql(
796 codes::C22012,
797 format!("cot() has no answer for {x}, where the sine is nought"),
798 ));
799 }
800 MathOp::Asin | MathOp::Acos if !(-1.0..=1.0).contains(&x) && x.is_finite() => {
801 return Err(out_of_range(
802 op.name(),
803 format!("has no answer for {x}, which is outside minus one to one"),
804 ));
805 }
806 _ => {}
807 }
808 let answer = real(op, x);
809 if answer.is_finite() || !x.is_finite() {
810 Ok(())
811 } else {
812 Err(out_of_range(
813 op.name(),
814 format!("of {x} is outside the range of a float"),
815 ))
816 }
817}
818
819fn out_of_range(name: &str, detail: String) -> ZuError {
822 ZuError::gql(codes::C22003, format!("{name}() {detail}"))
823}
824
825fn magnitude(v: &ValueVector, len: usize) -> u64 {
828 match v.encoding {
829 VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
830 _ => v.values::<i64>()[..len]
831 .iter()
832 .fold(0u64, |acc, x| acc | x.unsigned_abs()),
833 }
834}
835
836fn at_i64(v: &ValueVector, i: usize) -> i64 {
837 match v.encoding {
838 VecEncoding::Constant => v.constant_value::<i64>(),
839 _ => v.values::<i64>()[i],
840 }
841}
842
843fn span(v: &ValueVector, len: usize) -> (f64, f64) {
849 let mut lo = f64::INFINITY;
850 let mut hi = f64::NEG_INFINITY;
851 let mut fold = |x: f64| {
852 lo = lo.min(x);
853 hi = hi.max(x);
854 };
855 match (v.encoding, v.phys) {
856 (VecEncoding::Constant, PhysType::Int64) => fold(v.constant_value::<i64>() as f64),
857 (VecEncoding::Constant, _) => fold(v.constant_value::<f64>()),
858 (_, PhysType::Int64) => {
859 for &x in &v.values::<i64>()[..len] {
860 fold(x as f64);
861 }
862 }
863 _ => {
864 for &x in &v.values::<f64>()[..len] {
865 fold(x);
866 }
867 }
868 }
869 (lo, hi)
870}
871
872fn arg_f64(v: &ValueVector, i: usize) -> f64 {
875 match v.phys {
876 PhysType::Int64 => at_i64(v, i) as f64,
877 _ => match v.encoding {
878 VecEncoding::Constant => v.constant_value::<f64>(),
879 _ => v.values::<f64>()[i],
880 },
881 }
882}
883
884#[cfg(test)]
885mod tests {
886 use super::*;
887
888 fn raised(out: Result<ValueVector>) -> String {
890 match out {
891 Ok(_) => panic!("the kernel answered where it has no answer"),
892 Err(err) => err.to_string(),
893 }
894 }
895
896 fn ints(arena: &mut MorselArena, vals: &[i64]) -> ValueVector {
897 ValueVector::flat_from(arena, PhysType::Int64, vals)
898 }
899
900 fn floats(arena: &mut MorselArena, vals: &[f64]) -> ValueVector {
901 ValueVector::flat_from(arena, PhysType::Float64, vals)
902 }
903
904 #[test]
908 fn an_exact_argument_stays_exact() {
909 let mut arena = MorselArena::new();
910 let big = 9_007_199_254_740_993i64;
911 let v = ints(&mut arena, &[-3, 0, big]);
912 for op in [MathOp::Ceil, MathOp::Floor, MathOp::Round(0)] {
913 let out = unary(&mut arena, op, &v, None).unwrap();
914 assert_eq!(out.phys, PhysType::Int64);
915 assert_eq!(out.values::<i64>(), &[-3, 0, big]);
916 }
917 let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
918 assert_eq!(out.values::<i64>(), &[3, 0, big]);
919 let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
920 assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
921 }
922
923 #[test]
926 fn the_sign_of_a_float_is_an_integer() {
927 let mut arena = MorselArena::new();
928 let v = floats(&mut arena, &[-0.5, 0.0, 2.5]);
929 let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
930 assert_eq!(out.phys, PhysType::Int64);
931 assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
932 }
933
934 #[test]
937 fn halves_round_away_from_nought() {
938 let mut arena = MorselArena::new();
939 let v = floats(&mut arena, &[2.5, -2.5, 1.4999]);
940 let out = unary(&mut arena, MathOp::Round(0), &v, None).unwrap();
941 assert_eq!(out.values::<f64>(), &[3.0, -3.0, 1.0]);
942 }
943
944 #[test]
948 fn a_negative_digit_count_rounds_left_of_the_point() {
949 let mut arena = MorselArena::new();
950 let v = ints(&mut arena, &[150, -150, 149]);
951 let out = unary(&mut arena, MathOp::Round(-2), &v, None).unwrap();
952 assert_eq!(out.values::<i64>(), &[200, -200, 100]);
953
954 let v = floats(&mut arena, &[1.234, 1.236]);
955 let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
956 assert_eq!(out.values::<f64>(), &[1.23, 1.24]);
957 }
958
959 #[test]
962 fn the_bottom_integer_has_no_distance_from_nought() {
963 let mut arena = MorselArena::new();
964 let v = ints(&mut arena, &[1, i64::MIN]);
965 let out = unary(&mut arena, MathOp::Abs, &v, None);
966 assert_eq!(
967 raised(out),
968 "22003: abs() of -9223372036854775808 is one past the top of an integer"
969 );
970 }
971
972 #[test]
975 fn a_carry_past_the_top_of_an_integer_raises() {
976 let mut arena = MorselArena::new();
977 let v = ints(&mut arena, &[i64::MAX]);
978 let out = unary(&mut arena, MathOp::Round(-1), &v, None);
979 assert_eq!(
980 raised(out),
981 "22003: round() of 9223372036854775807 to -1 digits does not fit"
982 );
983 }
984
985 #[test]
988 fn a_row_outside_the_selection_raises_nothing() {
989 let mut arena = MorselArena::new();
990 let v = ints(&mut arena, &[7, i64::MIN, 9]);
991 let mut sel = SelVector::with_capacity(&mut arena, 2);
992 sel.push(0);
993 sel.push(2);
994 let out = unary(&mut arena, MathOp::Abs, &v, Some(&sel)).unwrap();
995 assert_eq!(out.values::<i64>()[0], 7);
996 assert_eq!(out.values::<i64>()[2], 9);
997 }
998
999 #[test]
1002 fn a_null_argument_is_not_a_condition() {
1003 let mut arena = MorselArena::new();
1004 let mut v = ints(&mut arena, &[7, i64::MIN, 9]);
1005 let mut valid = Bitmap::new_in(&mut arena, 3, true);
1006 valid.clear(1);
1007 v.validity = Some(valid);
1008 let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
1009 assert!(!out.is_valid(1), "null in, null out");
1010 assert!(out.is_valid(0) && out.is_valid(2));
1011 }
1012
1013 #[test]
1017 fn an_infinite_argument_is_not_a_condition() {
1018 let mut arena = MorselArena::new();
1019 let v = floats(&mut arena, &[f64::INFINITY]);
1020 let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
1021 assert!(out.values::<f64>()[0].is_infinite());
1022 }
1023
1024 #[test]
1028 fn the_approximate_half_answers_a_float_whatever_arrived() {
1029 let mut arena = MorselArena::new();
1030 let v = ints(&mut arena, &[0, 1, 4]);
1031 let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
1032 assert_eq!(out.phys, PhysType::Float64);
1033 assert_eq!(out.values::<f64>(), &[0.0, 1.0, 2.0]);
1034
1035 let out = unary(&mut arena, MathOp::Cos, &v, None).unwrap();
1036 assert_eq!(out.values::<f64>()[0], 1.0);
1037
1038 let v = floats(&mut arena, &[100.0, 1000.0]);
1039 let out = unary(&mut arena, MathOp::Log10, &v, None).unwrap();
1040 assert_eq!(out.values::<f64>(), &[2.0, 3.0]);
1041 }
1042
1043 #[test]
1046 fn the_angles_and_the_readings_cannot_raise() {
1047 for op in [
1048 MathOp::Sin,
1049 MathOp::Cos,
1050 MathOp::Tan,
1051 MathOp::Atan,
1052 MathOp::Radians,
1053 MathOp::Ceil,
1054 MathOp::Floor,
1055 MathOp::Sign,
1056 MathOp::Round(0),
1057 ] {
1058 assert!(!op.may_raise(), "{op:?} says it can raise");
1059 }
1060 for op in [
1061 MathOp::Sqrt,
1062 MathOp::Exp,
1063 MathOp::Ln,
1064 MathOp::Log10,
1065 MathOp::Cot,
1066 MathOp::Asin,
1067 MathOp::Acos,
1068 MathOp::Degrees,
1069 MathOp::Abs,
1070 MathOp::Round(1),
1071 ] {
1072 assert!(op.may_raise(), "{op:?} says it cannot raise");
1073 }
1074 }
1075
1076 #[test]
1080 fn a_root_or_a_logarithm_outside_its_domain_raises() {
1081 let mut arena = MorselArena::new();
1082 let v = floats(&mut arena, &[4.0, -1.0]);
1083 assert_eq!(
1084 raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
1085 "2201F: sqrt() has no answer for -1, which is below nought"
1086 );
1087
1088 let v = floats(&mut arena, &[1.0, 0.0]);
1089 assert_eq!(
1090 raised(unary(&mut arena, MathOp::Ln, &v, None)),
1091 "2201E: ln() has no answer for 0, which is not above nought"
1092 );
1093 assert_eq!(
1094 raised(unary(&mut arena, MathOp::Log10, &v, None)),
1095 "2201E: log10() has no answer for 0, which is not above nought"
1096 );
1097
1098 let v = ints(&mut arena, &[2, -4]);
1099 assert_eq!(
1100 raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
1101 "2201F: sqrt() has no answer for -4, which is below nought"
1102 );
1103 }
1104
1105 #[test]
1109 fn an_inverse_angle_outside_minus_one_to_one_raises() {
1110 let mut arena = MorselArena::new();
1111 let v = floats(&mut arena, &[0.5, 2.0]);
1112 assert_eq!(
1113 raised(unary(&mut arena, MathOp::Asin, &v, None)),
1114 "22003: asin() has no answer for 2, which is outside minus one to one"
1115 );
1116 assert_eq!(
1117 raised(unary(&mut arena, MathOp::Acos, &v, None)),
1118 "22003: acos() has no answer for 2, which is outside minus one to one"
1119 );
1120 }
1121
1122 #[test]
1126 fn a_cotangent_where_the_sine_is_nought_raises() {
1127 let mut arena = MorselArena::new();
1128 let v = floats(&mut arena, &[1.0, 0.0]);
1129 assert_eq!(
1130 raised(unary(&mut arena, MathOp::Cot, &v, None)),
1131 "22012: cot() has no answer for 0, where the sine is nought"
1132 );
1133
1134 let v = floats(&mut arena, &[1.0, 2.0]);
1135 let out = unary(&mut arena, MathOp::Cot, &v, None).unwrap();
1136 assert!(out.values::<f64>()[0].is_finite());
1137 }
1138
1139 #[test]
1143 fn an_answer_past_the_top_of_a_float_raises() {
1144 let mut arena = MorselArena::new();
1145 let v = floats(&mut arena, &[1.0, 710.0]);
1146 assert_eq!(
1147 raised(unary(&mut arena, MathOp::Exp, &v, None)),
1148 "22003: exp() of 710 is outside the range of a float"
1149 );
1150
1151 let v = floats(&mut arena, &[f64::MAX]);
1152 assert!(
1153 raised(unary(&mut arena, MathOp::Degrees, &v, None))
1154 .starts_with("22003: degrees() of "),
1155 );
1156
1157 let v = floats(&mut arena, &[1.0, 700.0]);
1159 assert!(
1160 unary(&mut arena, MathOp::Exp, &v, None)
1161 .unwrap()
1162 .values::<f64>()[0]
1163 > 2.7
1164 );
1165 }
1166
1167 #[test]
1171 fn the_approximate_half_skips_what_nobody_asked_about() {
1172 let mut arena = MorselArena::new();
1173 let v = floats(&mut arena, &[4.0, -1.0, 9.0]);
1174 let mut sel = SelVector::with_capacity(&mut arena, 2);
1175 sel.push(0);
1176 sel.push(2);
1177 let out = unary(&mut arena, MathOp::Sqrt, &v, Some(&sel)).unwrap();
1178 assert_eq!(out.values::<f64>()[2], 3.0);
1179
1180 let mut v = floats(&mut arena, &[4.0, -1.0, 9.0]);
1181 let mut valid = Bitmap::new_in(&mut arena, 3, true);
1182 valid.clear(1);
1183 v.validity = Some(valid);
1184 let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
1185 assert!(!out.is_valid(1));
1186 }
1187
1188 #[test]
1191 fn a_finite_number_rounded_out_of_range_raises() {
1192 let mut arena = MorselArena::new();
1193 let v = floats(&mut arena, &[f64::MAX]);
1194 let out = unary(&mut arena, MathOp::Round(2), &v, None);
1195 assert!(
1196 raised(out).starts_with("22003: round() of "),
1197 "the row engine's condition"
1198 );
1199 }
1200
1201 #[test]
1205 fn a_remainder_stays_exact_and_the_other_two_do_not() {
1206 let mut arena = MorselArena::new();
1207 let l = ints(&mut arena, &[7, -7, 8]);
1208 let r = ints(&mut arena, &[3, 3, 2]);
1209 let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1210 assert_eq!(out.phys, PhysType::Int64);
1211 assert_eq!(out.values::<i64>(), &[1, -1, 0]);
1212
1213 let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
1214 assert_eq!(out.phys, PhysType::Float64);
1215 assert_eq!(out.values::<f64>(), &[343.0, -343.0, 64.0]);
1216
1217 let base = ints(&mut arena, &[2, 2, 2]);
1218 let of = ints(&mut arena, &[8, 4, 1]);
1219 let out = pair(&mut arena, MathPair::Log, &base, &of, None).unwrap();
1220 assert_eq!(out.values::<f64>(), &[3.0, 2.0, 0.0]);
1221 }
1222
1223 #[test]
1227 fn an_approximate_remainder_keeps_the_sign_of_the_dividend() {
1228 let mut arena = MorselArena::new();
1229 let l = floats(&mut arena, &[7.5, -7.5]);
1230 let r = floats(&mut arena, &[2.0, 2.0]);
1231 let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1232 assert_eq!(out.values::<f64>(), &[1.5, -1.5]);
1233 }
1234
1235 #[test]
1240 fn a_remainder_with_no_answer_raises() {
1241 let mut arena = MorselArena::new();
1242 let l = ints(&mut arena, &[7, 1]);
1243 let r = ints(&mut arena, &[3, 0]);
1244 assert_eq!(
1245 raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1246 "22012: division by zero"
1247 );
1248
1249 let l = floats(&mut arena, &[7.0, 1.0]);
1250 let r = floats(&mut arena, &[3.0, 0.0]);
1251 assert_eq!(
1252 raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1253 "22012: division by zero"
1254 );
1255
1256 let l = ints(&mut arena, &[i64::MIN]);
1257 let r = ints(&mut arena, &[-1]);
1258 assert_eq!(
1259 raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1260 "22003: mod() of -9223372036854775808 and -1 does not fit an integer"
1261 );
1262 }
1263
1264 #[test]
1268 fn a_power_with_no_answer_raises() {
1269 let mut arena = MorselArena::new();
1270 let l = floats(&mut arena, &[2.0, 0.0]);
1271 let r = floats(&mut arena, &[3.0, -1.0]);
1272 assert_eq!(
1273 raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
1274 "2201F: power() has no answer for nought raised to a negative power"
1275 );
1276
1277 let l = floats(&mut arena, &[2.0, -2.0]);
1278 let r = floats(&mut arena, &[3.0, 0.5]);
1279 assert_eq!(
1280 raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
1281 "2201F: power() has no answer for -2 raised to 0.5, which is not whole"
1282 );
1283
1284 let l = floats(&mut arena, &[-2.0]);
1287 let r = floats(&mut arena, &[3.0]);
1288 let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
1289 assert_eq!(out.values::<f64>(), &[-8.0]);
1290 }
1291
1292 #[test]
1295 fn a_logarithm_outside_its_domain_raises() {
1296 let mut arena = MorselArena::new();
1297 let base = floats(&mut arena, &[2.0, 1.0]);
1298 let of = floats(&mut arena, &[8.0, 8.0]);
1299 assert_eq!(
1300 raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
1301 "2201E: log() has no answer in base 1"
1302 );
1303
1304 let base = floats(&mut arena, &[2.0, 2.0]);
1305 let of = floats(&mut arena, &[8.0, 0.0]);
1306 assert_eq!(
1307 raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
1308 "2201E: log() has no answer for 0, which is not above nought"
1309 );
1310 }
1311
1312 #[test]
1316 fn a_power_past_the_top_of_a_float_raises() {
1317 let mut arena = MorselArena::new();
1318 let l = floats(&mut arena, &[1.0e300]);
1319 let r = floats(&mut arena, &[2.0]);
1320 assert!(
1321 raised(pair(&mut arena, MathPair::Power, &l, &r, None))
1322 .starts_with("22003: power() of "),
1323 );
1324 }
1325
1326 #[test]
1329 fn a_pair_skips_what_nobody_asked_about() {
1330 let mut arena = MorselArena::new();
1331 let l = ints(&mut arena, &[7, 1, 9]);
1332 let r = ints(&mut arena, &[3, 0, 2]);
1333 let mut sel = SelVector::with_capacity(&mut arena, 2);
1334 sel.push(0);
1335 sel.push(2);
1336 let out = pair(&mut arena, MathPair::Mod, &l, &r, Some(&sel)).unwrap();
1337 assert_eq!(out.values::<i64>()[0], 1);
1338 assert_eq!(out.values::<i64>()[2], 1);
1339
1340 let mut r = ints(&mut arena, &[3, 0, 2]);
1341 let mut valid = Bitmap::new_in(&mut arena, 3, true);
1342 valid.clear(1);
1343 r.validity = Some(valid);
1344 let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1345 assert!(!out.is_valid(1), "null in, null out");
1346 assert!(out.is_valid(0) && out.is_valid(2));
1347 }
1348
1349 #[test]
1353 fn the_two_arguments_hold_the_one_type() {
1354 assert_eq!(
1355 MathPair::Mod.answer_type(PhysType::Int64, PhysType::Int64),
1356 Some(PhysType::Int64)
1357 );
1358 assert_eq!(
1359 MathPair::Power.answer_type(PhysType::Int64, PhysType::Int64),
1360 Some(PhysType::Float64)
1361 );
1362 assert_eq!(
1363 MathPair::Mod.answer_type(PhysType::Int64, PhysType::Float64),
1364 None
1365 );
1366 assert_eq!(
1367 MathPair::Log.answer_type(PhysType::Str, PhysType::Str),
1368 None
1369 );
1370 }
1371
1372 #[test]
1379 fn every_function_fills_what_one_row_answers() {
1380 const OPS: [MathOp; 18] = [
1381 MathOp::Abs,
1382 MathOp::Ceil,
1383 MathOp::Floor,
1384 MathOp::Round(0),
1385 MathOp::Round(2),
1386 MathOp::Sqrt,
1387 MathOp::Exp,
1388 MathOp::Ln,
1389 MathOp::Log10,
1390 MathOp::Sin,
1391 MathOp::Cos,
1392 MathOp::Tan,
1393 MathOp::Cot,
1394 MathOp::Asin,
1395 MathOp::Acos,
1396 MathOp::Atan,
1397 MathOp::Degrees,
1398 MathOp::Radians,
1399 ];
1400 let reals: [f64; 3] = [0.25, 0.5, 1.0];
1401 let wholes: [i64; 3] = [1, 1, 1];
1407 let mut arena = MorselArena::new();
1408 for op in OPS {
1409 let v = floats(&mut arena, &reals);
1410 let out = unary(&mut arena, op, &v, None).unwrap();
1411 for (i, x) in reals.iter().enumerate() {
1412 assert_eq!(out.values::<f64>()[i], real(op, *x), "{op:?} on {x}");
1413 }
1414 if !matches!(
1418 op,
1419 MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Round(_)
1420 ) {
1421 let v = ints(&mut arena, &wholes);
1422 let out = unary(&mut arena, op, &v, None).unwrap();
1423 for (i, x) in wholes.iter().enumerate() {
1424 let want = real(op, *x as f64);
1425 assert_eq!(out.values::<f64>()[i], want, "{op:?} on the whole {x}");
1426 }
1427 }
1428 let c = ValueVector::constant(&mut arena, PhysType::Float64, 0.5f64, 3);
1431 let out = unary(&mut arena, op, &c, None).unwrap();
1432 assert_eq!(
1433 out.values::<f64>()[2],
1434 real(op, 0.5),
1435 "{op:?} on a constant"
1436 );
1437 }
1438 }
1439}