Skip to content

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.

java: pass NaN and infinity between Java and the port

Mohit Mishrae24047cc1c71
diff --git a/src/java.rs b/src/java.rs
index 182d79f..7c2285b 100644
--- a/src/java.rs
+++ b/src/java.rs
@@ -513,7 +513,7 @@ pub const FLAVOR: Flavor = Flavor {
"`/` and `%` on integers truncate toward zero, as in Rust. `Math.round` rounds half up: `(x + 0.5).floor()`.",
"Arrays and Lists arrive as JSON arrays, Maps as objects with String keys.",
],
- floats: None,
+ floats: Some(native::FLOATS),
};
pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
@@ -673,6 +673,72 @@ mod tests {
assert!(edges.len() <= 100);
}
+ #[test]
+ fn nan_and_infinity_travel_tagged() {
+ use serde_json::json;
+ if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no java on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-java-floats-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let rec = REC.replace("/*PACKAGE*/", "").replace("/*ID*/", "Check.scale").replace("/*JSON*/", JSON);
+ fs::write(dir.join("FastAnythingRec.java"), rec).unwrap();
+ // the recorder, then the JSON the bridge uses, both ways (the port isn't built here)
+ let check = r#"
+ public class Check {
+ static double[] scale(double[] xs, double k) {
+ double[] out = new double[xs.length];
+ for (int i = 0; i < xs.length; i++) out[i] = xs[i] * k;
+ return out;
+ }
+ public static void main(String[] a) {
+ FastAnythingRec.record(new Object[] {new double[] {1.5, Double.POSITIVE_INFINITY}, Double.NEGATIVE_INFINITY},
+ args -> scale((double[]) args[0], (double) args[1]));
+ FastAnythingRec.record(new Object[] {new double[] {0.0}, 2.0}, args -> scale((double[]) args[0], (double) args[1]));
+ Object back = FastAnythingRec.Json.parse(
+ "{\"a\":[1.5,{\"$float\":\"NaN\"},{\"$float\":\"Infinity\"},{\"$float\":\"-Infinity\"}],\"b\":{\"$float\":\"x\"},\"c\":{}}");
+ System.out.println(FastAnythingRec.Json.enc(back));
+ Object xs = FastAnythingRec.Json.convert(((java.util.Map<?, ?>) back).get("a"), double[].class);
+ System.out.println(java.util.Arrays.toString((double[]) xs));
+ System.out.println(FastAnythingRec.Json.enc(new Object[] {Float.NaN, -0.0, Float.NEGATIVE_INFINITY}));
+ }
+ }
+ "#;
+ fs::write(dir.join("Check.java"), check).unwrap();
+ let out = dir.join("rec.jsonl");
+ let run = Command::new("java")
+ .arg("Check.java")
+ .current_dir(&dir)
+ .env("FAST_ANYTHING_RECORD_OUT", &out)
+ .env("FAST_ANYTHING_RECORD_META", dir.join("meta.json"))
+ .output()
+ .unwrap();
+ let text = fs::read_to_string(&out).unwrap_or_default();
+ let _ = fs::remove_dir_all(&dir);
+ let stdout = String::from_utf8_lossy(&run.stdout);
+ assert!(run.status.success(), "{stdout}{}", String::from_utf8_lossy(&run.stderr));
+ let calls: Vec<Value> = text.lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect();
+ assert_eq!(
+ calls.iter().find(|c| c.get("derived").is_none()),
+ Some(&json!({"args": [[1.5, {"$float": "Infinity"}], {"$float": "-Infinity"}],
+ "result": [{"$float": "-Infinity"}, {"$float": "-Infinity"}]})),
+ "{text}"
+ );
+ // and NaN and infinity are edge cases now that they can be passed
+ let edge = |want: &str| calls.iter().any(|c| c["derived"] == "edge" && c["args"][1] == json!({"$float": want}));
+ assert!(edge("NaN") && edge("Infinity") && edge("-Infinity"), "{text}");
+ let lines: Vec<&str> = stdout.lines().collect();
+ assert_eq!(
+ lines,
+ [
+ r#"{"a":[1.5,{"$float":"NaN"},{"$float":"Infinity"},{"$float":"-Infinity"}],"b":{"$float":"x"},"c":{}}"#,
+ "[1.5, NaN, Infinity, -Infinity]",
+ r#"[{"$float":"NaN"},-0.0,{"$float":"-Infinity"}]"#,
+ ]
+ );
+ }
+
#[test]
fn varargs_are_portable_as_arrays() {
if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {
diff --git a/src/java/Json.java b/src/java/Json.java
index 47c89d3..1bb2f50 100644
--- a/src/java/Json.java
+++ b/src/java/Json.java
@@ -15,8 +15,10 @@
else if (v instanceof Boolean || v instanceof Integer || v instanceof Long || v instanceof Short || v instanceof Byte) b.append(v);
else if (v instanceof Double || v instanceof Float) {
double d = ((Number) v).doubleValue();
- if (!Double.isFinite(d)) throw new Unsupported("NaN or Infinity");
- b.append(v);
+ // JSON has no NaN or infinity: they travel tagged, as the port reads and writes them
+ if (Double.isNaN(d)) b.append("{\"$float\":\"NaN\"}");
+ else if (Double.isInfinite(d)) b.append(d > 0 ? "{\"$float\":\"Infinity\"}" : "{\"$float\":\"-Infinity\"}");
+ else b.append(v);
} else if (v instanceof String s) str(s, b);
else if (v.getClass().isArray()) {
b.append('[');
@@ -100,7 +102,7 @@
i[0]++; // :
m.put(k, value(s, i));
ws(s, i);
- if (s.charAt(i[0]++) == '}') return m;
+ if (s.charAt(i[0]++) == '}') return untag(m);
}
}
if (c == '[') {
@@ -143,6 +145,19 @@
try { return Long.parseLong(num); } catch (NumberFormatException ex) { return Double.parseDouble(num); }
}
+ /** {"$float": "NaN"} and the like, the way the port sends NaN and infinity, as a Double. */
+ static Object untag(java.util.Map<String, Object> m) {
+ if (m.size() == 1 && m.get("$float") instanceof String f) {
+ switch (f) {
+ case "NaN": return Double.NaN;
+ case "Infinity": return Double.POSITIVE_INFINITY;
+ case "-Infinity": return Double.NEGATIVE_INFINITY;
+ default: break;
+ }
+ }
+ return m;
+ }
+
/** A parsed JSON value as the Java type t (from the original method's signature). */
static Object convert(Object v, java.lang.reflect.Type t) {
if (v == null) return null;
diff --git a/src/java/Rec.java b/src/java/Rec.java
index c3a2123..dcc1da7 100644
--- a/src/java/Rec.java
+++ b/src/java/Rec.java
@@ -132,9 +132,11 @@ final class FastAnythingRec {
if (!e.equals(v)) out.add(e);
}
} else if (v instanceof Double d) {
- for (double x : new double[] {0, 1, -1, 1e300, Double.MIN_VALUE}) if (x != d) out.add(x);
+ for (double x : new double[] {0, -0.0, 1, -1, 1e300, Double.MIN_VALUE, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY})
+ if (Double.compare(x, d) != 0) out.add(x);
} else if (v instanceof Float f) {
- for (float x : new float[] {0, 1, -1, 1e30f, Float.MIN_VALUE}) if (x != f) out.add(x);
+ for (float x : new float[] {0, -0.0f, 1, -1, 1e30f, Float.MIN_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY})
+ if (Float.compare(x, f) != 0) out.add(x);
} else if (v instanceof String s) {
int mid = s.offsetByCodePoints(0, s.codePointCount(0, s.length()) / 2);
for (String x : new String[] {s.substring(0, mid) + NON_ASCII[0] + s.substring(mid), s + NON_ASCII[1], NON_ASCII[2] + s, s + NON_ASCII[3], ""}) {
diff --git a/src/kotlin.rs b/src/kotlin.rs
index 08b25cb..4fff9ca 100644
--- a/src/kotlin.rs
+++ b/src/kotlin.rs
@@ -906,7 +906,7 @@ pub const FLAVOR: Flavor = Flavor {
"`lowercase()` / `uppercase()` don't depend on the locale; integer `/` and `%` truncate toward zero, as in Rust.",
"Lists and arrays arrive as JSON arrays, Maps as objects with String keys, null as null (`Option<T>` for `T?`). For an extension function, the receiver is the first argument.",
],
- floats: None,
+ floats: Some(native::FLOATS), // the recorder and bridge are Java's
};
pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {