From 75135e5772e844e585568e9266b58b9c51e106aa Mon Sep 17 00:00:00 2001 From: Mattias Wadman Date: Mon, 11 Nov 2024 19:37:18 +0100 Subject: [PATCH] Make reminder be integer reminder This is same as jq modulo (hoh) error message: ``` $ jq -n 'def f: -2, -1, 0, 2.1, 3, 4000000001; [f as $a | f as $b | try ($a % $b) catch .]' [ 0, 0, "number (-2) and number (0) cannot be divided (remainder) because the divisor is zero", 0, -2, -2, -1, 0, "number (-1) and number (0) cannot be divided (remainder) because the divisor is zero", -1, -1, -1, 0, 0, "number (0) and number (0) cannot be divided (remainder) because the divisor is zero", 0, 0, 0, 0, 0, "number (2.1) and number (0) cannot be divided (remainder) because the divisor is zero", 0, 2, 2, 1, 0, "number (3) and number (0) cannot be divided (remainder) because the divisor is zero", 1, 0, 3, 1, 0, "number (4000000001) and number (0) cannot be divided (remainder) because the divisor is zero", 1, 2, 0 ] ``` --- jaq-json/src/lib.rs | 7 ++++++- jaq-json/tests/funs.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/jaq-json/src/lib.rs b/jaq-json/src/lib.rs index 6acaeb402..18297e9d6 100644 --- a/jaq-json/src/lib.rs +++ b/jaq-json/src/lib.rs @@ -765,9 +765,14 @@ impl core::ops::Div for Val { impl core::ops::Rem for Val { type Output = ValR; fn rem(self, rhs: Self) -> Self::Output { - use Val::Int; + use Val::{Float, Int, Num}; match (self, rhs) { (Int(x), Int(y)) if y != 0 => Ok(Int(x % y)), + (Float(f), Int(i)) if i != 0 => Ok(Int(f as isize % i)), + (Int(i), Float(f)) if f != 0.0 => Ok(Int(i % f as isize)), + (Float(x), Float(y)) if y != 0.0 => Ok(Int(x as isize % y as isize)), + (Num(n), r) => Self::from_dec_str(&n) % r, + (l, Num(n)) => l % Self::from_dec_str(&n), (l, r) => Err(Error::math(l, ops::Math::Rem, r)), } } diff --git a/jaq-json/tests/funs.rs b/jaq-json/tests/funs.rs index bf94ad901..feffc00fa 100644 --- a/jaq-json/tests/funs.rs +++ b/jaq-json/tests/funs.rs @@ -77,3 +77,46 @@ fn tojson() { give(json!(0), "0.0 / 0.0 | tojson", json!("null")); give(json!(0), "1.0 / 0.0 | tojson", json!("null")); } + +yields!( + math_rem, + "def f: -2, -1, 0, 2.1, 3, 4000000001; [f as $a | f as $b | try ($a % $b) catch .]", + json!([ + 0, + 0, + "cannot calculate -2 % 0", + 0, + -2, + -2, + -1, + 0, + "cannot calculate -1 % 0", + -1, + -1, + -1, + 0, + 0, + "cannot calculate 0 % 0", + 0, + 0, + 0, + 0, + 0, + "cannot calculate 2.1 % 0", + 0, + 2, + 2, + 1, + 0, + "cannot calculate 3 % 0", + 1, + 0, + 3, + 1, + 0, + "cannot calculate 4000000001 % 0", + 1, + 2, + 0 + ]) +);