Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
verify: compare floats relative to their size, keep the sign of zero
Milosz8ed5b5baeb8a
diff --git a/README.md b/README.mdindex 259c15e..62006d9 100644--- a/README.md+++ b/README.md@@ -56,7 +56,7 @@ Or step by step:<p align="center"><img src="https://raw.githubusercontent.com/EL4CTEO/fast-anything/main/docs/assets/verify.gif" alt="verify catches a wrong port" width="820"></p>-That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases and lets the original answer them: edge cases (NaN, ±infinity, -0.0, zero and ±1, non-ASCII text, empty and up to 16× bigger inputs) and shrunk inputs (tiny and random slices). Nothing is enabled until every case matches: same values (floats within 1e-9), errors where the original errors. A port that is right but slower per call than the original (calling into Rust costs more than the work saved) isn't enabled either. `FAST_ANYTHING_DISABLE=1` runs the original any time.+That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases and lets the original answer them: edge cases (NaN, ±infinity, -0.0, zero and ±1, non-ASCII text, empty and up to 16× bigger inputs) and shrunk inputs (tiny and random slices). Nothing is enabled until every case matches: same values (floats within 1e-9 of their size or of the largest value in the same list, -0.0 not 0.0), errors where the original errors. A port that is right but slower per call than the original (calling into Rust costs more than the work saved) isn't enabled either. `FAST_ANYTHING_DISABLE=1` runs the original any time.## Resultsdiff --git a/src/native.rs b/src/native.rsindex 6a7cded..16eb18a 100644--- a/src/native.rs+++ b/src/native.rs@@ -206,6 +206,7 @@ Only edit files in this folder. Don't touch the {label} project.\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\- Same result for every input, edge cases included: empty input, zero, negatives, non-ASCII text, very long input. verify tests these too.\n\+- Floats must match within 1e-9 of their size (or of the largest value in the same array), and zeros keep their sign: -0.0 is not 0.0. Keep the same order of float operations.\n\{rules}\- Return `Err(message)` where the original would fail.\n\- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases. Threads are fine if the result is the same.\n\@@ -410,20 +411,25 @@ pub fn replay(job_path: &Path) -> Result<()> {/// Same value, give or take float rounding.pub fn same(a: &Value, b: &Value, loose_empty: bool) -> bool {+ same_in(a, b, 0.0, loose_empty)+}++/// `scale`: the largest finite magnitude in the expected array holding `a` (0 outside arrays).+fn same_in(a: &Value, b: &Value, scale: f64, loose_empty: bool) -> bool {match (a, b) {(Value::Number(x), Value::Number(y)) => {if x.is_f64() || y.is_f64() {- let (x, y) = (x.as_f64().unwrap_or(f64::NAN), y.as_f64().unwrap_or(f64::NAN));- x == y || (x - y).abs() <= f64::max(1e-12, 1e-9 * x.abs().max(y.abs()))+ close(x.as_f64().unwrap_or(f64::NAN), y.as_f64().unwrap_or(f64::NAN), scale)} else {x == y}}(Value::Array(x), Value::Array(y)) => {- x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q, loose_empty))+ let scale = x.iter().filter_map(Value::as_f64).filter(|v| v.is_finite()).fold(0.0, |m, v| v.abs().max(m));+ x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_in(p, q, scale, loose_empty))}(Value::Object(x), Value::Object(y)) => {- x.len() == y.len() && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| same(p, q, loose_empty)))+ x.len() == y.len() && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| same_in(p, q, 0.0, loose_empty)))}(Value::Null, Value::Array(v)) | (Value::Array(v), Value::Null) => loose_empty && v.is_empty(),(Value::Null, Value::Object(v)) | (Value::Object(v), Value::Null) => loose_empty && v.is_empty(),@@ -434,6 +440,17 @@ pub fn same(a: &Value, b: &Value, loose_empty: bool) -> bool {}}+/// Floats within 1e-9 of their size (or of `scale`). -0.0 isn't 0.0: it prints differently.+fn close(x: f64, y: f64, scale: f64) -> bool {+ if x.is_nan() || y.is_nan() {+ return x.is_nan() && y.is_nan();+ }+ if x == y {+ return x.is_sign_negative() == y.is_sign_negative();+ }+ x.is_finite() && y.is_finite() && (x - y).abs() <= 1e-9 * x.abs().max(y.abs()).max(scale)+}+// ------------------------------------------------------------------ temporary edits/// Files changed (or created) for one run. Everything goes back on restore() or drop, and a copy@@ -629,6 +646,22 @@ mod tests {assert!(same(&j("3"), &j("3.0"), false));}+ #[test]+ fn floats_match_to_their_size_or_their_lists() {+ let j = |s: &str| serde_json::from_str::<Value>(s).unwrap();+ assert!(!same(&j("4.2441e-19"), &j("4.2441e-28"), false));+ assert!(!same(&j("-0.0"), &j("0.0"), false) && !same(&j("-0"), &j("0.0"), false));+ assert!(same(&j("-0.0"), &j("-0"), false) && same(&j("[0.0]"), &j("[0]"), false));+ assert!(same(&j("[1.0, 2.0, 5.551115123125783e-17]"), &j("[1.0, 2.0, 0.0]"), false));+ assert!(!same(&j("{\"a\": 1.0, \"b\": 5.551115123125783e-17}"), &j("{\"a\": 1.0, \"b\": 0.0}"), false));+ assert!(!same(&j("[5.551115123125783e-17, [1.0]]"), &j("[0.0, [1.0]]"), false));+ assert!(same(&j("1.0"), &j("1.0000000005"), false) && !same(&j("1.0"), &j("1.000000002"), false));+ assert!(!same(&j("[1e10, 3]"), &j("[1e10, 4]"), false));+ assert!(close(f64::NAN, f64::NAN, 0.0) && !close(f64::NAN, 1.0, 0.0));+ assert!(close(f64::INFINITY, f64::INFINITY, 1.0) && !close(f64::INFINITY, f64::NEG_INFINITY, 1.0));+ assert!(!close(f64::INFINITY, f64::MAX, f64::MAX));+ }+#[test]fn only_languages_that_read_tagged_floats_get_them() {let hs = Hotspot { name: "mean".into(), params: vec![Default::default()], ..Hotspot::default() };diff --git a/src/node.rs b/src/node.rsindex 5a8eab3..48fa6c4 100644--- a/src/node.rs+++ b/src/node.rs@@ -461,7 +461,7 @@ fast-anything recorded {recorded} real calls (out of {seen} while the app ran).- JavaScript strings are UTF-16: `.length`, indexing and `charCodeAt` count UTF-16 code units. \Use `s.encode_utf16()` for anything index- or length-based (bytes are fine after checking `is_ascii()`).\n\- JavaScript numbers are f64. Integer math is exact only up to 2^53; use `f64` unless the values are clearly small integers.\n\-- Results are compared with a relative tolerance of 1e-9. Keep the same order of float operations.\n\+- Numbers must match within 1e-9 of their size (or of the largest value in the same array), and zeros keep their sign: -0 is not 0. Keep the same order of float operations.\n\- Where JavaScript throws, return `Err(Error::from_reason(...))`.\n\- Each call crosses from JavaScript into Rust: keep conversions cheap, don't clone big inputs.\n\- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases.\n\@@ -1021,6 +1021,39 @@ for (const worst of [assert!(out.status.success(), "{}", combined(&out));}+ #[test]+ fn numbers_match_to_their_size_or_their_arrays() {+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no node on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-node-same-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ let stripped = RUNNER.split("const [mode, jobPath]").next().unwrap();+ fs::write(dir.join("lib.mjs"), format!("{stripped}\nexport {{ same }};\n")).unwrap();+ fs::write(+ dir.join("check.mjs"),+ r#"import assert from "node:assert/strict";+import { same } from "./lib.mjs";++assert.ok(!same(4.2441e-19, 4.2441e-28));+assert.ok(!same(-0, 0) && !same(0, -0) && same(-0, -0) && same(0, 0));+assert.ok(same([1.0, 2.0, 5.551115123125783e-17], [1.0, 2.0, 0.0]));+assert.ok(same(new Float64Array([1, 5.551115123125783e-17]), new Float64Array([1, 0])));+assert.ok(!same({ a: 1, b: 5.551115123125783e-17 }, { a: 1, b: 0 }));+assert.ok(!same([1e10, 3], [1e10, 4]));+assert.ok(same(1.0, 1.0 + 5e-10) && !same(1.0, 1.0 + 2e-9));+assert.ok(same(NaN, NaN) && !same(NaN, 0) && same(Infinity, Infinity) && !same(Infinity, -Infinity));+assert.ok(!same([Number.MAX_VALUE, Infinity], [Number.MAX_VALUE, Number.MAX_VALUE]));+"#,+ )+ .unwrap();+ let out = Command::new("node").arg("check.mjs").current_dir(&dir).output().unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert!(out.status.success(), "{}", combined(&out));+ }+#[test]fn bun_and_deno_get_their_own_command_lines() {let args = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();diff --git a/src/node/runner.mjs b/src/node/runner.mjsindex fb14fba..cb129bf 100644--- a/src/node/runner.mjs+++ b/src/node/runner.mjs@@ -876,11 +876,15 @@ function dec(v) {throw new Error("unknown tag " + tag);}-function same(a, b) {+// Numbers match within 1e-9 of their size, or of `scale` (the largest number in the expected array+// holding them) unless both are whole. -0 isn't 0: it prints differently.+function same(a, b, scale = 0) {if (a == null && b == null) return true;if (typeof a === "number" && typeof b === "number") {- if (Number.isNaN(a) || Number.isNaN(b)) return Number.isNaN(a) && Number.isNaN(b);- return a === b || Math.abs(a - b) <= Math.max(1e-12, 1e-9 * Math.max(Math.abs(a), Math.abs(b)));+ if (a === b || Number.isNaN(a) || Number.isNaN(b)) return Object.is(a, b);+ if (!Number.isFinite(a) || !Number.isFinite(b)) return false;+ if (Number.isInteger(a) && Number.isInteger(b)) scale = 0;+ return Math.abs(a - b) <= 1e-9 * Math.max(Math.abs(a), Math.abs(b), scale);}if (typeof a === "bigint" || typeof b === "bigint") {try {@@ -890,7 +894,11 @@ function same(a, b) {}}const seq = (x) => Array.isArray(x) || (ArrayBuffer.isView(x) && !(x instanceof DataView));- if (seq(a) && seq(b)) return a.length === b.length && Array.from(a).every((x, i) => same(x, b[i]));+ if (seq(a) && seq(b)) {+ let big = 0;+ for (const x of a) if (typeof x === "number" && Number.isFinite(x)) big = Math.max(big, Math.abs(x));+ return a.length === b.length && Array.from(a).every((x, i) => same(x, b[i], big));+ }if (a instanceof Set && b instanceof Set) return a.size === b.size && [...a].every((x) => b.has(x));if (a instanceof Map && b instanceof Map) return a.size === b.size && [...a].every(([k, x]) => b.has(k) && same(x, b.get(k)));if (a && b && typeof a === "object" && typeof b === "object") {diff --git a/src/python.rs b/src/python.rsindex 9d53d88..5fe7489 100644--- a/src/python.rs+++ b/src/python.rs@@ -784,7 +784,7 @@ fast-anything recorded {recorded} real calls (out of {seen} while the app ran).- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\- Python `str` indexes by Unicode code point: use `.chars()` (or bytes only after checking `is_ascii()`).\n\- Python ints don't overflow. `i64` is fine unless the recorded values are bigger.\n\-- Float results are compared with a relative tolerance of 1e-9. Keep the same order of operations.\n\+- Floats must match within 1e-9 of their size (or of the largest value in the same list), and zeros keep their sign: -0.0 is not 0.0. Keep the same order of float operations.\n\- Where Python raises, raise too (`PyValueError::new_err(...)`, `PyKeyError`, ...).\n\- Make it fast: no needless allocation or cloning, borrow inputs, `with_capacity`, fast paths for common cases.\n\- std only, unless a crate clearly pays off. Keep the function and module names as they are.\n\@@ -1482,14 +1482,21 @@ sys.exit(1 if fails else 0)};let runner = std::env::temp_dir().join(format!("fa-runner-test-{}.py", std::process::id()));fs::write(&runner, RUNNER).unwrap();- let check = "import runpy, sys\n\+ let check = "import math, runpy, sys\n\same = runpy.run_path(sys.argv[1])['same']\n\assert not same(3.0, 3) and not same(3, 3.0)\n\assert not same([1.5, 2.0], [1.5, 2])\n\assert not same({'k': 2.0}, {'k': 2})\n\assert same(3.0, 3.0 + 1e-12) and same(3, 3) and same((1.0, 2), (1.0, 2))\n\assert not same((1, 2), [1, 2]) and not same([(1, 2)], [[1, 2]])\n\- assert same(float('nan'), float('nan')) and not same(True, 1)\n";+ assert same(float('nan'), float('nan')) and not same(True, 1)\n\+ assert not same(4.2441e-19, 4.2441e-28) and not same(-0.0, 0.0) and same(-0.0, -0.0)\n\+ assert same([1.0, 2.0, 5.551115123125783e-17], [1.0, 2.0, 0.0])\n\+ assert same((1, 5.551115123125783e-17), (1, 0.0)) and not same([[1.0], 5.551115123125783e-17], [[1.0], 0.0])\n\+ assert not same({'a': 1.0, 'b': 5.551115123125783e-17}, {'a': 1.0, 'b': 0.0})\n\+ assert same(1.0, 1.0 + 5e-10) and not same(1.0, 1.0 + 2e-9)\n\+ assert not same(math.inf, -math.inf) and not same([1e308, math.inf], [1e308, 1e308])\n\+ assert same([10 ** 400, 1.0], [10 ** 400, 1.0]) and not same([10 ** 400, 1.0], [10 ** 400 + 1, 1.0])\n";let out = Command::new(python).args(["-I", "-c", check]).arg(&runner).output().unwrap();let _ = fs::remove_file(&runner);assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));@@ -1665,6 +1672,11 @@ sys.exit(1 if fails else 0)assert type(dec(json.loads(json.dumps(enc(np.int32(7)))))) is np.int32\n\assert not same(a, a.astype(np.float32)) and not same(a, a.tolist()) and not same(a, a[0])\n\assert same(np.array([math.nan, 1.0]), np.array([math.nan, 1.0 + 1e-12]))\n\+ assert not same(np.array([1.0, -0.0]), np.array([1.0, 0.0])) and same(np.array([-0.0]), np.array([-0.0]))\n\+ assert not same(np.array([4.2441e-19, 5e-19]), np.array([4.2441e-28, 5e-28])) and same(np.array([4.2441e-19, 0.0]), np.array([4.2441e-19, 1e-30]))\n\+ assert same(np.array([[1.0, 2.0], [5.551115123125783e-17, math.inf]]), np.array([[1.0, 2.0], [0.0, math.inf]]))\n\+ assert not same(np.array([math.inf, 1.0]), np.array([-math.inf, 1.0])) and not same(np.array([math.inf]), np.array([1e308]))\n\+ assert not same(np.array([1.0, 1.0]), np.array([1.0, 1.0 + 2e-9])) and same(np.zeros((0, 2)), np.zeros((0, 2)))\n\assert same(np.float64(0.5), 0.5) and not same(np.int64(3), 3.0)\n\x = np.array([1.0, 2.0, 3.0])\n\e = edges(x); assert len(e[0]) == 0 and math.isnan(e[1][0]) and x[0] == 1.0\n\diff --git a/src/python/runner.py b/src/python/runner.pyindex 3af372f..a319116 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -154,8 +154,9 @@ def dec(v):return v-def same(a, b):- """Equality the way a caller would see it: floats within 1e-9, but 3 != 3.0 (it prints+def same(a, b, scale=0.0):+ """Equality the way a caller would see it: floats within 1e-9 of their size (or of `scale`, the+ largest number in the expected list holding them), but -0.0 != 0.0 and 3 != 3.0 (they printdifferently) and a list isn't a tuple (it can't be hashed)."""np = sys.modules.get("numpy")if np is not None:@@ -163,7 +164,7 @@ def same(a, b):if not (isinstance(a, np.ndarray) and isinstance(b, np.ndarray)) or a.shape != b.shape or a.dtype != b.dtype:return Falseif a.dtype.kind == "f":- return bool(np.allclose(a, b, rtol=1e-9, atol=1e-12, equal_nan=True))+ return same_floats(np, a, b)return bool(np.array_equal(a, b))# a NumPy scalar compares like the Python number it holds (a.sum() vs a port's f64)a = a.item() if isinstance(a, np.generic) else a@@ -178,16 +179,43 @@ def same(a, b):return Falseif math.isnan(a) or math.isnan(b):return math.isnan(a) and math.isnan(b)- return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)+ if a == b:+ return math.copysign(1.0, a) == math.copysign(1.0, b)+ return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-9 * scale)if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):if isinstance(a, tuple) != isinstance(b, tuple):return False- return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))+ scale = largest(a)+ return len(a) == len(b) and all(same(x, y, scale) for x, y in zip(a, b))if isinstance(a, dict) and isinstance(b, dict):return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)return a == b+def largest(xs):+ """The largest finite magnitude among the numbers in a list (0.0 if there are none)."""+ big = 0.0+ for x in xs:+ if isinstance(x, (int, float)) and not isinstance(x, bool) and big < abs(x) < math.inf:+ big = abs(x)+ return float(min(big, sys.float_info.max))+++def same_floats(np, a, b):+ """Float arrays element by element like same(), all within 1e-9 of the largest expected one."""+ nan = np.isnan(a)+ if not np.array_equal(nan, np.isnan(b)):+ return False+ finite = np.isfinite(a) & np.isfinite(b)+ infinite = ~finite & ~nan+ if not np.array_equal(a[infinite], b[infinite]) or np.any((a == b) & (np.signbit(a) != np.signbit(b))):+ return False+ x, y = a[finite], b[finite]+ scale = np.abs(a[np.isfinite(a)]).max(initial=0.0)+ with np.errstate(over="ignore"):+ return bool(np.all((x == y) | (np.abs(x - y) <= 1e-9 * np.maximum(np.maximum(np.abs(x), np.abs(y)), scale))))++def show(v, limit=160):text = repr(v)return text if len(text) <= limit else text[: limit - 1] + "…"diff --git a/src/r.rs b/src/r.rsindex ac908a4..9918fda 100644--- a/src/r.rs+++ b/src/r.rs@@ -531,6 +531,7 @@ fast-anything recorded {recorded} real calls (out of {seen} while the app ran).- Integer vs double doesn't matter to verify (R prints them alike); names, NA and list structure do. Where R stops with an error, return `Err(message)`.\n\n\## Rules\n\n\- Same result for every input, edge cases included: empty vectors, zero, negatives, NA, non-ASCII text, very long input. verify tests these too.\n\+- Doubles must match within 1e-9 of their size (or of the largest value in the same vector), and zeros keep their sign: -0 is not 0. Keep the same order of float operations.\n\- R strings index by character: use `.chars()` (or bytes only after checking `is_ascii()`). R indexes from 1.\n\- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases.\n\- Keep the function name.\n\n\@@ -690,7 +691,11 @@ mod tests {fa$.fa_same(5L, 5), fa$.fa_same(c(a = 1), c(a = 1 + 1e-12)), !fa$.fa_same(c(a = 1), c(b = 1)),fa$.fa_same(NA_real_, NA), fa$.fa_same(NA_character_, NA), !fa$.fa_same(NA, 1),fa$.fa_same(Inf, Inf), !fa$.fa_same(Inf, -Inf), fa$.fa_same(character(0), NULL),- !fa$.fa_same(list(1), 1), fa$.fa_same(list(c(1L, 2L)), list(c(1, 2))), !fa$.fa_same("a", "b")+ !fa$.fa_same(list(1), 1), fa$.fa_same(list(c(1L, 2L)), list(c(1, 2))), !fa$.fa_same("a", "b"),+ !fa$.fa_same(4.2441e-19, 4.2441e-28), !fa$.fa_same(-0, 0), !fa$.fa_same(0L, -0), fa$.fa_same(-0, -0),+ fa$.fa_same(c(1, 2, 5.551115123125783e-17), c(1, 2, 0)), !fa$.fa_same(list(1, 5.551115123125783e-17), list(1, 0)),+ fa$.fa_same(1, 1 + 5e-10), !fa$.fa_same(1, 1 + 2e-9), fa$.fa_same(NaN, NaN), !fa$.fa_same(NaN, NA_real_),+ !fa$.fa_same(c(1e10, 3), c(1e10, 4)), !fa$.fa_same(c(1e308, Inf), c(1e308, 1e308)))"#;let script = bridge.with_extension("check.R");diff --git a/src/r/bridge.R b/src/r/bridge.Rindex da9af22..6b9aa50 100644--- a/src/r/bridge.R+++ b/src/r/bridge.R@@ -94,8 +94,9 @@.fa_like(original, function(args) invoke(port, unname(args)))}-# Same result the way R code sees it: integer and double are both numbers, doubles within 1e-9,-# NA where NA, zero-length vectors and NULL alike, names and list structure must match.+# Same result the way R code sees it: integer and double are both numbers, doubles within 1e-9 of+# their size or of the largest in the expected vector (unless both are whole), -0 isn't 0 (1/x+# differs), NA where NA, zero-length vectors and NULL alike, names and list structure must match..fa_same <- function(a, b) {if (length(a) == 0L && length(b) == 0L && !is.list(a) && !is.list(b)) return(TRUE)if (is.list(a) || is.list(b)) {@@ -115,7 +116,9 @@if (!identical(a[inf], b[inf])) return(FALSE)a <- a[!inf]b <- b[!inf]- return(all(a == b | abs(a - b) <= pmax(1e-12, 1e-9 * pmax(abs(a), abs(b)))))+ scale <- max(abs(a), 0)+ tol <- 1e-9 * pmax(abs(a), abs(b), ifelse(a == round(a) & b == round(b), 0, scale))+ return(all(ifelse(a == b, 1 / a == 1 / b, abs(a - b) <= tol)))}identical(typeof(a), typeof(b)) && identical(unname(a), unname(b))}diff --git a/src/ruby.rs b/src/ruby.rsindex f27cdfd..ea7002a 100644--- a/src/ruby.rs+++ b/src/ruby.rs@@ -236,6 +236,7 @@ Only edit files in this folder. Don't touch the Ruby project.\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\+- Floats must match within 1e-9 of their size (or of the largest value in the same Array), and zeros keep their sign: -0.0 is not 0.0. Keep the same order of float operations.\n\- Change the `serde_json::Value` parameter and return types to concrete ones: they're deserialized for you.\n\- Ruby strings index by character: use `.chars()` (or bytes only after checking `is_ascii()`).\n\- Ruby Integers don't overflow. `i64` is fine unless the recorded values are bigger. Keep Integer vs Float as Ruby has it.\n\@@ -522,6 +523,13 @@ mod tests {raise "unwire" unless FastAnything.same(back, args)raise "lookalike" unless FastAnything.unwire({ "$float" => "nan" }) == { "$float" => "nan" }raise "plain" unless JSON.generate(FastAnything.wire([1.0, -0.0])) == "[1.0,-0.0]"+ raise "tiny" if FastAnything.same(4.2441e-19, 4.2441e-28)+ raise "zero sign" if FastAnything.same(-0.0, 0.0) || !FastAnything.same(-0.0, -0.0)+ raise "list scale" unless FastAnything.same([1.0, 2.0, 5.551115123125783e-17], [1.0, 2.0, 0.0])+ raise "hash scale" if FastAnything.same({ "a" => 1.0, "b" => 5.551115123125783e-17 }, { "a" => 1.0, "b" => 0.0 })+ raise "1e-9" unless FastAnything.same(1.0, 1.0 + 5e-10) && !FastAnything.same(1.0, 1.0 + 2e-9)+ raise "ints" if FastAnything.same([10**10, 3], [10**10, 4]) || FastAnything.same(inf, -inf)+ raise "nan" unless FastAnything.same(nan, nan) && FastAnything.same([10**400, 1.0], [10**400, 1.0])"#;fs::write(dir.join("check.rb"), check).unwrap();let run = Command::new("ruby").arg("check.rb").current_dir(&dir).output().unwrap();diff --git a/src/ruby/recorder.rb b/src/ruby/recorder.rbindex c691c5b..55cf62b 100644--- a/src/ruby/recorder.rb+++ b/src/ruby/recorder.rb@@ -63,13 +63,19 @@ module FastAnythingendend- def same(a, b)+ # Floats match within 1e-9 of their size, or of scale (the largest number in the expected Array+ # holding them). -0.0 isn't 0.0: it prints differently.+ def same(a, b, scale = 0.0)if a.is_a?(Float) || b.is_a?(Float)return false unless a.is_a?(Float) && b.is_a?(Float)return a.nan? && b.nan? if a.nan? || b.nan?- return a == b || (a - b).abs <= [1e-12, 1e-9 * [a.abs, b.abs].max].max+ return 1.0 / a == 1.0 / b if a == b+ return a.finite? && b.finite? && (a - b).abs <= 1e-9 * [a.abs, b.abs, scale].max+ end+ if a.is_a?(Array) && b.is_a?(Array)+ big = [a.grep(Numeric).map(&:abs).select { |x| x < Float::INFINITY }.max || 0, Float::MAX].min.to_f+ return a.length == b.length && a.zip(b).all? { |x, y| same(x, y, big) }end- return a.length == b.length && a.zip(b).all? { |x, y| same(x, y) } if a.is_a?(Array) && b.is_a?(Array)return a.keys.sort == b.keys.sort && a.all? { |k, x| same(x, b[k]) } if a.is_a?(Hash) && b.is_a?(Hash)a.class == b.class && a == b