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};
#[inline(always)]
fn fill1<S: Pod, D: Pod, F: Fn(S) -> D>(dst: &mut [D], v: &ValueVector, len: usize, f: F) {
match v.encoding {
VecEncoding::Constant => dst[..len].fill(f(v.constant_value::<S>())),
_ => {
let src = v.values::<S>();
for i in 0..len {
dst[i] = f(src[i]);
}
}
}
}
#[inline(always)]
fn fill2<S: Pod, D: Pod, F: Fn(S, S) -> D>(
dst: &mut [D],
l: &ValueVector,
r: &ValueVector,
len: usize,
f: F,
) {
match (l.encoding, r.encoding) {
(VecEncoding::Constant, VecEncoding::Constant) => {
dst[..len].fill(f(l.constant_value::<S>(), r.constant_value::<S>()));
}
(VecEncoding::Constant, _) => {
let c = l.constant_value::<S>();
let b = r.values::<S>();
for i in 0..len {
dst[i] = f(c, b[i]);
}
}
(_, VecEncoding::Constant) => {
let a = l.values::<S>();
let c = r.constant_value::<S>();
for i in 0..len {
dst[i] = f(a[i], c);
}
}
_ => {
let (a, b) = (l.values::<S>(), r.values::<S>());
for i in 0..len {
dst[i] = f(a[i], b[i]);
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MathOp {
Abs,
Ceil,
Floor,
Sign,
Round(i64),
Sqrt,
Exp,
Ln,
Log10,
Sin,
Cos,
Tan,
Cot,
Asin,
Acos,
Atan,
Degrees,
Radians,
}
impl MathOp {
fn name(self) -> &'static str {
match self {
MathOp::Abs => "abs",
MathOp::Ceil => "ceil",
MathOp::Floor => "floor",
MathOp::Sign => "sign",
MathOp::Round(_) => "round",
MathOp::Sqrt => "sqrt",
MathOp::Exp => "exp",
MathOp::Ln => "ln",
MathOp::Log10 => "log10",
MathOp::Sin => "sin",
MathOp::Cos => "cos",
MathOp::Tan => "tan",
MathOp::Cot => "cot",
MathOp::Asin => "asin",
MathOp::Acos => "acos",
MathOp::Atan => "atan",
MathOp::Degrees => "degrees",
MathOp::Radians => "radians",
}
}
fn is_real(self) -> bool {
!matches!(
self,
MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Sign | MathOp::Round(_)
)
}
pub fn may_raise(self) -> bool {
match self {
MathOp::Abs => true,
MathOp::Round(digits) => digits != 0,
MathOp::Ceil | MathOp::Floor | MathOp::Sign => false,
MathOp::Sin | MathOp::Cos | MathOp::Tan | MathOp::Atan | MathOp::Radians => false,
_ => true,
}
}
pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
match (self, arg) {
(_, PhysType::Int64 | PhysType::Float64) if self.is_real() => Some(PhysType::Float64),
(MathOp::Sign, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Int64),
(_, PhysType::Int64) => Some(PhysType::Int64),
(_, PhysType::Float64) => Some(PhysType::Float64),
_ => None,
}
}
}
pub fn unary(
arena: &mut MorselArena,
op: MathOp,
v: &ValueVector,
sel: Option<&SelVector>,
) -> Result<ValueVector> {
let len = v.len as usize;
if matches!(v.encoding, VecEncoding::Dict { .. }) {
return Err(ZuError::InvalidArgument(
"numeric functions on dict vectors: materialize first".into(),
));
}
let Some(answer) = op.answer_type(v.phys) else {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
op.name(),
v.phys
)));
};
check(op, v, sel, len)?;
let mut out = ValueVector::flat_uninit(arena, answer, len);
match (v.phys, answer) {
(PhysType::Int64, PhysType::Int64) => fill_exact(op, out.values_mut::<i64>(), v, len),
(PhysType::Float64, PhysType::Int64) => {
fill1(out.values_mut::<i64>(), v, len, sign_f64);
}
(PhysType::Int64, PhysType::Float64) => {
fill_real(op, out.values_mut::<f64>(), v, len, |x: i64| x as f64);
}
(PhysType::Float64, PhysType::Float64) => {
fill_real(op, out.values_mut::<f64>(), v, len, |x: f64| x);
}
_ => unreachable!("answer_type answers for these four shapes only"),
}
out.validity = v.validity.as_ref().map(|valid| {
let mut copy = Bitmap::new_in(arena, len, true);
copy.and_with(valid);
copy
});
Ok(out)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MathPair {
Power,
Log,
Mod,
}
impl MathPair {
fn name(self) -> &'static str {
match self {
MathPair::Power => "power",
MathPair::Log => "log",
MathPair::Mod => "mod",
}
}
pub fn answer_type(self, l: PhysType, r: PhysType) -> Option<PhysType> {
if l != r {
return None;
}
match (self, l) {
(MathPair::Mod, PhysType::Int64) => Some(PhysType::Int64),
(_, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Float64),
_ => None,
}
}
}
pub fn pair(
arena: &mut MorselArena,
op: MathPair,
l: &ValueVector,
r: &ValueVector,
sel: Option<&SelVector>,
) -> Result<ValueVector> {
debug_assert_eq!(l.len, r.len);
if matches!(l.encoding, VecEncoding::Dict { .. })
|| matches!(r.encoding, VecEncoding::Dict { .. })
{
return Err(ZuError::InvalidArgument(
"numeric functions on dict vectors: materialize first".into(),
));
}
let Some(answer) = op.answer_type(l.phys, r.phys) else {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?} and {:?}",
op.name(),
l.phys,
r.phys
)));
};
let len = l.len as usize;
let mut out = ValueVector::flat_uninit(arena, answer, len);
match answer {
PhysType::Int64 => {
fill2(out.values_mut::<i64>(), l, r, len, |x: i64, y: i64| {
x.wrapping_rem(if y == 0 { 1 } else { y })
});
}
_ if l.phys == PhysType::Int64 => {
fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: i64| x as f64);
}
_ => {
fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: f64| x);
}
}
verify_pair(op, l, r, &out, sel, len)?;
out.validity = merged_validity(arena, l, r, len);
Ok(out)
}
#[inline(always)]
fn fill_pair_real<S: Pod, C: Fn(S) -> f64 + Copy>(
op: MathPair,
dst: &mut [f64],
l: &ValueVector,
r: &ValueVector,
len: usize,
conv: C,
) {
match op {
MathPair::Power => fill2(dst, l, r, len, |x, y| conv(x).powf(conv(y))),
MathPair::Log => fill2(dst, l, r, len, |x, y| conv(y).log(conv(x))),
MathPair::Mod => fill2(dst, l, r, len, |x, y| conv(x) % conv(y)),
}
}
fn verify_pair(
op: MathPair,
l: &ValueVector,
r: &ValueVector,
out: &ValueVector,
sel: Option<&SelVector>,
len: usize,
) -> Result<()> {
if !risky_pair(op, l, r, out, len) {
return Ok(());
}
let visit = |i: usize| -> Result<()> {
if !l.is_valid(i) || !r.is_valid(i) {
return Ok(());
}
if out.phys == PhysType::Int64 {
let (x, y) = (at_i64(l, i), at_i64(r, i));
if y == 0 {
return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
}
return x.checked_rem(y).map(|_| ()).ok_or_else(|| {
out_of_range(op.name(), format!("of {x} and {y} does not fit an integer"))
});
}
one_pair(op, arg_f64(l, i), arg_f64(r, i), out.values::<f64>()[i])
};
match sel {
Some(sel) => {
for &row in sel.as_slice() {
visit(row as usize)?;
}
}
None => {
for i in 0..len {
visit(i)?;
}
}
}
Ok(())
}
fn risky_pair(
op: MathPair,
l: &ValueVector,
r: &ValueVector,
out: &ValueVector,
len: usize,
) -> bool {
if out.phys == PhysType::Int64 {
let (lo, hi) = span(r, len);
return (lo <= 0.0 && hi >= 0.0) || (lo <= -1.0 && hi >= -1.0);
}
if !all_finite(out, len) {
return true;
}
let (lo, hi) = span(l, len);
match op {
MathPair::Power => lo <= 0.0,
MathPair::Log => {
let base = lo > 1.0 || (lo > 0.0 && hi < 1.0);
!base || span(r, len).0 <= 0.0
}
MathPair::Mod => {
let (lo, hi) = span(r, len);
lo <= 0.0 && hi >= 0.0
}
}
}
fn one_pair(op: MathPair, x: f64, y: f64, answer: f64) -> Result<()> {
match op {
MathPair::Mod if y == 0.0 => {
return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
}
MathPair::Power if x == 0.0 && y < 0.0 => {
return Err(ZuError::gql(
codes::C2201F,
"power() has no answer for nought raised to a negative power".to_string(),
));
}
MathPair::Power if x < 0.0 && y.fract() != 0.0 && y.is_finite() => {
return Err(ZuError::gql(
codes::C2201F,
format!("power() has no answer for {x} raised to {y}, which is not whole"),
));
}
MathPair::Log if x <= 0.0 || x == 1.0 => {
return Err(ZuError::gql(
codes::C2201E,
format!("log() has no answer in base {x}"),
));
}
MathPair::Log if y <= 0.0 => {
return Err(ZuError::gql(
codes::C2201E,
format!("log() has no answer for {y}, which is not above nought"),
));
}
_ => {}
}
if answer.is_finite() || !x.is_finite() || !y.is_finite() {
Ok(())
} else {
Err(out_of_range(
op.name(),
format!("of {x} and {y} is outside the range of a float"),
))
}
}
fn all_finite(out: &ValueVector, len: usize) -> bool {
out.values::<f64>()[..len].iter().all(|x| x.is_finite())
}
fn merged_validity(
arena: &mut MorselArena,
l: &ValueVector,
r: &ValueVector,
len: usize,
) -> Option<Bitmap> {
if l.validity.is_none() && r.validity.is_none() {
return None;
}
let mut copy = Bitmap::new_in(arena, len, true);
if let Some(valid) = l.validity.as_ref() {
copy.and_with(valid);
}
if let Some(valid) = r.validity.as_ref() {
copy.and_with(valid);
}
Some(copy)
}
#[inline(always)]
fn fill_exact(op: MathOp, dst: &mut [i64], v: &ValueVector, len: usize) {
match op {
MathOp::Abs => fill1(dst, v, len, i64::wrapping_abs),
MathOp::Sign => fill1(dst, v, len, i64::signum),
MathOp::Ceil | MathOp::Floor => fill1(dst, v, len, |x: i64| x),
MathOp::Round(digits) if digits >= 0 => fill1(dst, v, len, |x: i64| x),
MathOp::Round(digits) => fill1(dst, v, len, move |x: i64| {
rounded_int(x, digits).unwrap_or(0)
}),
_ => unreachable!("the approximate half answers a float"),
}
}
#[inline(always)]
fn fill_real<S: Pod, C: Fn(S) -> f64 + Copy>(
op: MathOp,
dst: &mut [f64],
v: &ValueVector,
len: usize,
conv: C,
) {
match op {
MathOp::Abs => fill1(dst, v, len, |x| conv(x).abs()),
MathOp::Ceil => fill1(dst, v, len, |x| conv(x).ceil()),
MathOp::Floor => fill1(dst, v, len, |x| conv(x).floor()),
MathOp::Round(0) => fill1(dst, v, len, |x| conv(x).round()),
MathOp::Round(digits) => {
let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
fill1(dst, v, len, move |x| (conv(x) * scale).round() / scale);
}
MathOp::Sqrt => fill1(dst, v, len, |x| conv(x).sqrt()),
MathOp::Exp => fill1(dst, v, len, |x| conv(x).exp()),
MathOp::Ln => fill1(dst, v, len, |x| conv(x).ln()),
MathOp::Log10 => fill1(dst, v, len, |x| conv(x).log10()),
MathOp::Sin => fill1(dst, v, len, |x| conv(x).sin()),
MathOp::Cos => fill1(dst, v, len, |x| conv(x).cos()),
MathOp::Tan => fill1(dst, v, len, |x| conv(x).tan()),
MathOp::Cot => fill1(dst, v, len, |x| cot(conv(x))),
MathOp::Asin => fill1(dst, v, len, |x| conv(x).asin()),
MathOp::Acos => fill1(dst, v, len, |x| conv(x).acos()),
MathOp::Atan => fill1(dst, v, len, |x| conv(x).atan()),
MathOp::Degrees => fill1(dst, v, len, |x| conv(x).to_degrees()),
MathOp::Radians => fill1(dst, v, len, |x| conv(x).to_radians()),
MathOp::Sign => unreachable!("sign answers an integer"),
}
}
#[inline(never)]
pub fn cot(x: f64) -> f64 {
x.cos() / x.sin()
}
#[inline(always)]
fn sign_f64(x: f64) -> i64 {
if x > 0.0 {
1
} else if x < 0.0 {
-1
} else {
0
}
}
fn rounded_int(value: i64, digits: i64) -> Option<i64> {
let places = u32::try_from(-digits).ok()?;
if places > 19 {
return Some(0);
}
let factor = 10i128.checked_pow(places)?;
let value = value as i128;
let half = factor / 2;
let carried = if value >= 0 {
(value + half) / factor
} else {
(value - half) / factor
};
i64::try_from(carried.checked_mul(factor)?).ok()
}
fn check(op: MathOp, v: &ValueVector, sel: Option<&SelVector>, len: usize) -> Result<()> {
if !risky(op, v, len) {
return Ok(());
}
let visit = |i: usize| -> Result<()> {
if !v.is_valid(i) {
return Ok(());
}
match v.phys {
PhysType::Int64 if !op.is_real() => {
let x = at_i64(v, i);
match op {
MathOp::Abs => x.checked_abs().map(|_| ()).ok_or_else(|| {
out_of_range(
op.name(),
format!("of {x} is one past the top of an integer"),
)
}),
MathOp::Round(digits) => rounded_int(x, digits).map(|_| ()).ok_or_else(|| {
out_of_range(op.name(), format!("of {x} to {digits} digits does not fit"))
}),
_ => Ok(()),
}
}
_ => one_real(op, arg_f64(v, i)),
}
};
match sel {
Some(sel) => {
for &row in sel.as_slice() {
visit(row as usize)?;
}
}
None => {
for i in 0..len {
visit(i)?;
}
}
}
Ok(())
}
fn risky(op: MathOp, v: &ValueVector, len: usize) -> bool {
if !op.may_raise() {
return false;
}
if op.is_real() {
let (lo, hi) = span(v, len);
return match op {
MathOp::Sqrt => lo < 0.0,
MathOp::Ln | MathOp::Log10 => lo <= 0.0,
MathOp::Asin | MathOp::Acos => lo < -1.0 || hi > 1.0,
MathOp::Exp => hi > 709.0,
MathOp::Degrees => lo <= -3.0e306 || hi >= 3.0e306,
_ => true,
};
}
match (v.phys, op) {
(PhysType::Int64, MathOp::Abs) => magnitude(v, len) >= 1u64 << 63,
(PhysType::Int64, MathOp::Round(digits)) => digits < 0,
(PhysType::Float64, MathOp::Round(digits)) => digits != 0,
_ => false,
}
}
fn real(op: MathOp, x: f64) -> f64 {
match op {
MathOp::Abs => x.abs(),
MathOp::Ceil => x.ceil(),
MathOp::Floor => x.floor(),
MathOp::Round(0) => x.round(),
MathOp::Round(digits) => {
let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
(x * scale).round() / scale
}
MathOp::Sqrt => x.sqrt(),
MathOp::Exp => x.exp(),
MathOp::Ln => x.ln(),
MathOp::Log10 => x.log10(),
MathOp::Sin => x.sin(),
MathOp::Cos => x.cos(),
MathOp::Tan => x.tan(),
MathOp::Cot => cot(x),
MathOp::Asin => x.asin(),
MathOp::Acos => x.acos(),
MathOp::Atan => x.atan(),
MathOp::Degrees => x.to_degrees(),
MathOp::Radians => x.to_radians(),
MathOp::Sign => unreachable!("sign answers an integer"),
}
}
fn one_real(op: MathOp, x: f64) -> Result<()> {
match op {
MathOp::Sqrt if x < 0.0 => {
return Err(ZuError::gql(
codes::C2201F,
format!("sqrt() has no answer for {x}, which is below nought"),
));
}
MathOp::Ln | MathOp::Log10 if x <= 0.0 => {
return Err(ZuError::gql(
codes::C2201E,
format!(
"{}() has no answer for {x}, which is not above nought",
op.name()
),
));
}
MathOp::Cot if x.sin() == 0.0 => {
return Err(ZuError::gql(
codes::C22012,
format!("cot() has no answer for {x}, where the sine is nought"),
));
}
MathOp::Asin | MathOp::Acos if !(-1.0..=1.0).contains(&x) && x.is_finite() => {
return Err(out_of_range(
op.name(),
format!("has no answer for {x}, which is outside minus one to one"),
));
}
_ => {}
}
let answer = real(op, x);
if answer.is_finite() || !x.is_finite() {
Ok(())
} else {
Err(out_of_range(
op.name(),
format!("of {x} is outside the range of a float"),
))
}
}
fn out_of_range(name: &str, detail: String) -> ZuError {
ZuError::gql(codes::C22003, format!("{name}() {detail}"))
}
fn magnitude(v: &ValueVector, len: usize) -> u64 {
match v.encoding {
VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
_ => v.values::<i64>()[..len]
.iter()
.fold(0u64, |acc, x| acc | x.unsigned_abs()),
}
}
fn at_i64(v: &ValueVector, i: usize) -> i64 {
match v.encoding {
VecEncoding::Constant => v.constant_value::<i64>(),
_ => v.values::<i64>()[i],
}
}
fn span(v: &ValueVector, len: usize) -> (f64, f64) {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
let mut fold = |x: f64| {
lo = lo.min(x);
hi = hi.max(x);
};
match (v.encoding, v.phys) {
(VecEncoding::Constant, PhysType::Int64) => fold(v.constant_value::<i64>() as f64),
(VecEncoding::Constant, _) => fold(v.constant_value::<f64>()),
(_, PhysType::Int64) => {
for &x in &v.values::<i64>()[..len] {
fold(x as f64);
}
}
_ => {
for &x in &v.values::<f64>()[..len] {
fold(x);
}
}
}
(lo, hi)
}
fn arg_f64(v: &ValueVector, i: usize) -> f64 {
match v.phys {
PhysType::Int64 => at_i64(v, i) as f64,
_ => match v.encoding {
VecEncoding::Constant => v.constant_value::<f64>(),
_ => v.values::<f64>()[i],
},
}
}
#[cfg(test)]
mod tests {
use super::*;
fn raised(out: Result<ValueVector>) -> String {
match out {
Ok(_) => panic!("the kernel answered where it has no answer"),
Err(err) => err.to_string(),
}
}
fn ints(arena: &mut MorselArena, vals: &[i64]) -> ValueVector {
ValueVector::flat_from(arena, PhysType::Int64, vals)
}
fn floats(arena: &mut MorselArena, vals: &[f64]) -> ValueVector {
ValueVector::flat_from(arena, PhysType::Float64, vals)
}
#[test]
fn an_exact_argument_stays_exact() {
let mut arena = MorselArena::new();
let big = 9_007_199_254_740_993i64;
let v = ints(&mut arena, &[-3, 0, big]);
for op in [MathOp::Ceil, MathOp::Floor, MathOp::Round(0)] {
let out = unary(&mut arena, op, &v, None).unwrap();
assert_eq!(out.phys, PhysType::Int64);
assert_eq!(out.values::<i64>(), &[-3, 0, big]);
}
let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
assert_eq!(out.values::<i64>(), &[3, 0, big]);
let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
}
#[test]
fn the_sign_of_a_float_is_an_integer() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[-0.5, 0.0, 2.5]);
let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
assert_eq!(out.phys, PhysType::Int64);
assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
}
#[test]
fn halves_round_away_from_nought() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[2.5, -2.5, 1.4999]);
let out = unary(&mut arena, MathOp::Round(0), &v, None).unwrap();
assert_eq!(out.values::<f64>(), &[3.0, -3.0, 1.0]);
}
#[test]
fn a_negative_digit_count_rounds_left_of_the_point() {
let mut arena = MorselArena::new();
let v = ints(&mut arena, &[150, -150, 149]);
let out = unary(&mut arena, MathOp::Round(-2), &v, None).unwrap();
assert_eq!(out.values::<i64>(), &[200, -200, 100]);
let v = floats(&mut arena, &[1.234, 1.236]);
let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
assert_eq!(out.values::<f64>(), &[1.23, 1.24]);
}
#[test]
fn the_bottom_integer_has_no_distance_from_nought() {
let mut arena = MorselArena::new();
let v = ints(&mut arena, &[1, i64::MIN]);
let out = unary(&mut arena, MathOp::Abs, &v, None);
assert_eq!(
raised(out),
"22003: abs() of -9223372036854775808 is one past the top of an integer"
);
}
#[test]
fn a_carry_past_the_top_of_an_integer_raises() {
let mut arena = MorselArena::new();
let v = ints(&mut arena, &[i64::MAX]);
let out = unary(&mut arena, MathOp::Round(-1), &v, None);
assert_eq!(
raised(out),
"22003: round() of 9223372036854775807 to -1 digits does not fit"
);
}
#[test]
fn a_row_outside_the_selection_raises_nothing() {
let mut arena = MorselArena::new();
let v = ints(&mut arena, &[7, i64::MIN, 9]);
let mut sel = SelVector::with_capacity(&mut arena, 2);
sel.push(0);
sel.push(2);
let out = unary(&mut arena, MathOp::Abs, &v, Some(&sel)).unwrap();
assert_eq!(out.values::<i64>()[0], 7);
assert_eq!(out.values::<i64>()[2], 9);
}
#[test]
fn a_null_argument_is_not_a_condition() {
let mut arena = MorselArena::new();
let mut v = ints(&mut arena, &[7, i64::MIN, 9]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
assert!(!out.is_valid(1), "null in, null out");
assert!(out.is_valid(0) && out.is_valid(2));
}
#[test]
fn an_infinite_argument_is_not_a_condition() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[f64::INFINITY]);
let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
assert!(out.values::<f64>()[0].is_infinite());
}
#[test]
fn the_approximate_half_answers_a_float_whatever_arrived() {
let mut arena = MorselArena::new();
let v = ints(&mut arena, &[0, 1, 4]);
let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
assert_eq!(out.phys, PhysType::Float64);
assert_eq!(out.values::<f64>(), &[0.0, 1.0, 2.0]);
let out = unary(&mut arena, MathOp::Cos, &v, None).unwrap();
assert_eq!(out.values::<f64>()[0], 1.0);
let v = floats(&mut arena, &[100.0, 1000.0]);
let out = unary(&mut arena, MathOp::Log10, &v, None).unwrap();
assert_eq!(out.values::<f64>(), &[2.0, 3.0]);
}
#[test]
fn the_angles_and_the_readings_cannot_raise() {
for op in [
MathOp::Sin,
MathOp::Cos,
MathOp::Tan,
MathOp::Atan,
MathOp::Radians,
MathOp::Ceil,
MathOp::Floor,
MathOp::Sign,
MathOp::Round(0),
] {
assert!(!op.may_raise(), "{op:?} says it can raise");
}
for op in [
MathOp::Sqrt,
MathOp::Exp,
MathOp::Ln,
MathOp::Log10,
MathOp::Cot,
MathOp::Asin,
MathOp::Acos,
MathOp::Degrees,
MathOp::Abs,
MathOp::Round(1),
] {
assert!(op.may_raise(), "{op:?} says it cannot raise");
}
}
#[test]
fn a_root_or_a_logarithm_outside_its_domain_raises() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[4.0, -1.0]);
assert_eq!(
raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
"2201F: sqrt() has no answer for -1, which is below nought"
);
let v = floats(&mut arena, &[1.0, 0.0]);
assert_eq!(
raised(unary(&mut arena, MathOp::Ln, &v, None)),
"2201E: ln() has no answer for 0, which is not above nought"
);
assert_eq!(
raised(unary(&mut arena, MathOp::Log10, &v, None)),
"2201E: log10() has no answer for 0, which is not above nought"
);
let v = ints(&mut arena, &[2, -4]);
assert_eq!(
raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
"2201F: sqrt() has no answer for -4, which is below nought"
);
}
#[test]
fn an_inverse_angle_outside_minus_one_to_one_raises() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[0.5, 2.0]);
assert_eq!(
raised(unary(&mut arena, MathOp::Asin, &v, None)),
"22003: asin() has no answer for 2, which is outside minus one to one"
);
assert_eq!(
raised(unary(&mut arena, MathOp::Acos, &v, None)),
"22003: acos() has no answer for 2, which is outside minus one to one"
);
}
#[test]
fn a_cotangent_where_the_sine_is_nought_raises() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[1.0, 0.0]);
assert_eq!(
raised(unary(&mut arena, MathOp::Cot, &v, None)),
"22012: cot() has no answer for 0, where the sine is nought"
);
let v = floats(&mut arena, &[1.0, 2.0]);
let out = unary(&mut arena, MathOp::Cot, &v, None).unwrap();
assert!(out.values::<f64>()[0].is_finite());
}
#[test]
fn an_answer_past_the_top_of_a_float_raises() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[1.0, 710.0]);
assert_eq!(
raised(unary(&mut arena, MathOp::Exp, &v, None)),
"22003: exp() of 710 is outside the range of a float"
);
let v = floats(&mut arena, &[f64::MAX]);
assert!(
raised(unary(&mut arena, MathOp::Degrees, &v, None))
.starts_with("22003: degrees() of "),
);
let v = floats(&mut arena, &[1.0, 700.0]);
assert!(
unary(&mut arena, MathOp::Exp, &v, None)
.unwrap()
.values::<f64>()[0]
> 2.7
);
}
#[test]
fn the_approximate_half_skips_what_nobody_asked_about() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[4.0, -1.0, 9.0]);
let mut sel = SelVector::with_capacity(&mut arena, 2);
sel.push(0);
sel.push(2);
let out = unary(&mut arena, MathOp::Sqrt, &v, Some(&sel)).unwrap();
assert_eq!(out.values::<f64>()[2], 3.0);
let mut v = floats(&mut arena, &[4.0, -1.0, 9.0]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
assert!(!out.is_valid(1));
}
#[test]
fn a_finite_number_rounded_out_of_range_raises() {
let mut arena = MorselArena::new();
let v = floats(&mut arena, &[f64::MAX]);
let out = unary(&mut arena, MathOp::Round(2), &v, None);
assert!(
raised(out).starts_with("22003: round() of "),
"the row engine's condition"
);
}
#[test]
fn a_remainder_stays_exact_and_the_other_two_do_not() {
let mut arena = MorselArena::new();
let l = ints(&mut arena, &[7, -7, 8]);
let r = ints(&mut arena, &[3, 3, 2]);
let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
assert_eq!(out.phys, PhysType::Int64);
assert_eq!(out.values::<i64>(), &[1, -1, 0]);
let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
assert_eq!(out.phys, PhysType::Float64);
assert_eq!(out.values::<f64>(), &[343.0, -343.0, 64.0]);
let base = ints(&mut arena, &[2, 2, 2]);
let of = ints(&mut arena, &[8, 4, 1]);
let out = pair(&mut arena, MathPair::Log, &base, &of, None).unwrap();
assert_eq!(out.values::<f64>(), &[3.0, 2.0, 0.0]);
}
#[test]
fn an_approximate_remainder_keeps_the_sign_of_the_dividend() {
let mut arena = MorselArena::new();
let l = floats(&mut arena, &[7.5, -7.5]);
let r = floats(&mut arena, &[2.0, 2.0]);
let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
assert_eq!(out.values::<f64>(), &[1.5, -1.5]);
}
#[test]
fn a_remainder_with_no_answer_raises() {
let mut arena = MorselArena::new();
let l = ints(&mut arena, &[7, 1]);
let r = ints(&mut arena, &[3, 0]);
assert_eq!(
raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
"22012: division by zero"
);
let l = floats(&mut arena, &[7.0, 1.0]);
let r = floats(&mut arena, &[3.0, 0.0]);
assert_eq!(
raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
"22012: division by zero"
);
let l = ints(&mut arena, &[i64::MIN]);
let r = ints(&mut arena, &[-1]);
assert_eq!(
raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
"22003: mod() of -9223372036854775808 and -1 does not fit an integer"
);
}
#[test]
fn a_power_with_no_answer_raises() {
let mut arena = MorselArena::new();
let l = floats(&mut arena, &[2.0, 0.0]);
let r = floats(&mut arena, &[3.0, -1.0]);
assert_eq!(
raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
"2201F: power() has no answer for nought raised to a negative power"
);
let l = floats(&mut arena, &[2.0, -2.0]);
let r = floats(&mut arena, &[3.0, 0.5]);
assert_eq!(
raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
"2201F: power() has no answer for -2 raised to 0.5, which is not whole"
);
let l = floats(&mut arena, &[-2.0]);
let r = floats(&mut arena, &[3.0]);
let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
assert_eq!(out.values::<f64>(), &[-8.0]);
}
#[test]
fn a_logarithm_outside_its_domain_raises() {
let mut arena = MorselArena::new();
let base = floats(&mut arena, &[2.0, 1.0]);
let of = floats(&mut arena, &[8.0, 8.0]);
assert_eq!(
raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
"2201E: log() has no answer in base 1"
);
let base = floats(&mut arena, &[2.0, 2.0]);
let of = floats(&mut arena, &[8.0, 0.0]);
assert_eq!(
raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
"2201E: log() has no answer for 0, which is not above nought"
);
}
#[test]
fn a_power_past_the_top_of_a_float_raises() {
let mut arena = MorselArena::new();
let l = floats(&mut arena, &[1.0e300]);
let r = floats(&mut arena, &[2.0]);
assert!(
raised(pair(&mut arena, MathPair::Power, &l, &r, None))
.starts_with("22003: power() of "),
);
}
#[test]
fn a_pair_skips_what_nobody_asked_about() {
let mut arena = MorselArena::new();
let l = ints(&mut arena, &[7, 1, 9]);
let r = ints(&mut arena, &[3, 0, 2]);
let mut sel = SelVector::with_capacity(&mut arena, 2);
sel.push(0);
sel.push(2);
let out = pair(&mut arena, MathPair::Mod, &l, &r, Some(&sel)).unwrap();
assert_eq!(out.values::<i64>()[0], 1);
assert_eq!(out.values::<i64>()[2], 1);
let mut r = ints(&mut arena, &[3, 0, 2]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
r.validity = Some(valid);
let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
assert!(!out.is_valid(1), "null in, null out");
assert!(out.is_valid(0) && out.is_valid(2));
}
#[test]
fn the_two_arguments_hold_the_one_type() {
assert_eq!(
MathPair::Mod.answer_type(PhysType::Int64, PhysType::Int64),
Some(PhysType::Int64)
);
assert_eq!(
MathPair::Power.answer_type(PhysType::Int64, PhysType::Int64),
Some(PhysType::Float64)
);
assert_eq!(
MathPair::Mod.answer_type(PhysType::Int64, PhysType::Float64),
None
);
assert_eq!(
MathPair::Log.answer_type(PhysType::Str, PhysType::Str),
None
);
}
#[test]
fn every_function_fills_what_one_row_answers() {
const OPS: [MathOp; 18] = [
MathOp::Abs,
MathOp::Ceil,
MathOp::Floor,
MathOp::Round(0),
MathOp::Round(2),
MathOp::Sqrt,
MathOp::Exp,
MathOp::Ln,
MathOp::Log10,
MathOp::Sin,
MathOp::Cos,
MathOp::Tan,
MathOp::Cot,
MathOp::Asin,
MathOp::Acos,
MathOp::Atan,
MathOp::Degrees,
MathOp::Radians,
];
let reals: [f64; 3] = [0.25, 0.5, 1.0];
let wholes: [i64; 3] = [1, 1, 1];
let mut arena = MorselArena::new();
for op in OPS {
let v = floats(&mut arena, &reals);
let out = unary(&mut arena, op, &v, None).unwrap();
for (i, x) in reals.iter().enumerate() {
assert_eq!(out.values::<f64>()[i], real(op, *x), "{op:?} on {x}");
}
if !matches!(
op,
MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Round(_)
) {
let v = ints(&mut arena, &wholes);
let out = unary(&mut arena, op, &v, None).unwrap();
for (i, x) in wholes.iter().enumerate() {
let want = real(op, *x as f64);
assert_eq!(out.values::<f64>()[i], want, "{op:?} on the whole {x}");
}
}
let c = ValueVector::constant(&mut arena, PhysType::Float64, 0.5f64, 3);
let out = unary(&mut arena, op, &c, None).unwrap();
assert_eq!(
out.values::<f64>()[2],
real(op, 0.5),
"{op:?} on a constant"
);
}
}
}