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
php: pass NaN and infinity between PHP and the port
Mohit Mishra5faefc118287
diff --git a/src/php.rs b/src/php.rsindex 7f2a493..4a4987b 100644--- a/src/php.rs+++ b/src/php.rs@@ -312,7 +312,7 @@ pub const FLAVOR: Flavor = Flavor {"PHP ints are `i64` and turn into floats on overflow; `/` gives a float unless the division is exact, `intdiv` truncates.","Untyped parameters arrive as `serde_json::Value`: pick concrete types from the recorded calls.",],- floats: None,+ floats: Some(native::FLOATS),};pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {@@ -460,6 +460,77 @@ mod tests {assert_eq!(after, app);}+ #[test]+ fn nan_and_infinity_travel_tagged() {+ if !Command::new("php").arg("-v").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no php on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-php-floats-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("rec.php"), REC).unwrap();+ let bridge = BRIDGE.replace("/*CLASS*/", "Bridge").replace("/*ID*/", "scale").replace("/*LIB*/", "'none'");+ fs::write(dir.join("bridge.php"), format!("<?php\n{bridge}\n")).unwrap();+ // the recorder, then the bridge's own conversions both ways (the port isn't built here)+ let check = r#"<?php+ require __DIR__ . '/rec.php';+ require __DIR__ . '/bridge.php';+ function scale(array $xs, float $k): array+ {+ return array_map(fn($x) => $x * $k, $xs);+ }+ FastAnythingRec::record('scale', [[1.5, INF], -INF], 'scale');+ FastAnythingRec::record('scale', [[0.0], 2.0], 'scale');+ $wire = new ReflectionMethod('Bridge', 'wire');+ $unwire = new ReflectionMethod('Bridge', 'unwire');+ $sent = ['xs' => [NAN, -0.5, -INF], 'm' => ['k' => INF]];+ echo json_encode($wire->invoke(null, $sent)), "\n";+ $back = $unwire->invoke(null, json_decode('{"a":[1.5,{"$float":"NaN"},{"$float":"Infinity"},{"$float":"-Infinity"}],"b":{"$float":"x"},"c":[]}', true));+ var_export([$back['a'][0], is_nan($back['a'][1]), $back['a'][2], $back['a'][3], $back['b'], $back['c']]);+ "#;+ fs::write(dir.join("check.php"), check).unwrap();+ let out = dir.join("rec.jsonl");+ let run = Command::new("php")+ .arg("check.php")+ .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 recorded: Vec<Value> = text+ .lines()+ .map(|l| serde_json::from_str::<Value>(l).unwrap())+ .filter(|c| c.get("derived").is_none())+ .collect();+ assert_eq!(+ recorded[0],+ serde_json::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| {+ text.lines()+ .map(|l| serde_json::from_str::<Value>(l).unwrap())+ .any(|c| c["derived"] == "edge" && c["args"][1] == serde_json::json!({"$float": want}))+ };+ assert!(edge("NaN") && edge("Infinity") && edge("-Infinity"), "{text}");+ let mut lines = stdout.lines();+ assert_eq!(+ lines.next(),+ Some(r#"{"xs":[{"$float":"NaN"},-0.5,{"$float":"-Infinity"}],"m":{"k":{"$float":"Infinity"}}}"#)+ );+ let rest: String = lines.collect::<Vec<_>>().join("\n");+ assert!(+ rest.contains("1.5,\n 1 => true,\n 2 => INF,\n 3 => -INF,\n 4 => \n array (\n '$float' => 'x',"),+ "{rest}"+ );+ }+#[test]fn the_recorder_adds_edge_cases() {use serde_json::json;diff --git a/src/php/bridge.php b/src/php/bridge.phpindex 514bee3..de65116 100644--- a/src/php/bridge.php+++ b/src/php/bridge.php@@ -22,7 +22,7 @@ final class /*CLASS*/{$ps = self::$params[$name] ??= (str_contains($name, '::') ? new \ReflectionMethod(...explode('::', $name, 2)) : new \ReflectionFunction($name))->getParameters();for ($i = count($args); $i < count($ps) && $ps[$i]->isDefaultValueAvailable(); $i++) $args[] = $ps[$i]->getDefaultValue();- $in = json_encode($args, JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);+ $in = json_encode(self::wire($args), JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);$len = self::$ffi->new('size_t');$out = self::$ffi->fa_call($in, strlen($in), \FFI::addr($len));$n = $len->cdata;@@ -30,6 +30,24 @@ final class /*CLASS*/self::$ffi->fa_free($out, $n);$reply = json_decode($text, true, 512, JSON_THROW_ON_ERROR);if (array_key_exists('error', $reply)) throw new \RuntimeException('fast-anything: ' . $reply['error']);- return $reply['ok'];+ return self::unwire($reply['ok']);+ }++ // NaN and infinity, which JSON has no numbers for, travel as {"$float": "NaN"} (or+ // "Infinity", "-Infinity"), as the port's C entry point reads and writes them+ private static function wire($v)+ {+ if (is_float($v) && !is_finite($v)) return ['$float' => is_nan($v) ? 'NaN' : ($v > 0 ? 'Infinity' : '-Infinity')];+ return is_array($v) ? array_map([self::class, 'wire'], $v) : $v;+ }++ private static function unwire($v)+ {+ if (!is_array($v)) return $v;+ if (count($v) === 1 && is_string($v['$float'] ?? null)) {+ $f = ['NaN' => NAN, 'Infinity' => INF, '-Infinity' => -INF][$v['$float']] ?? null;+ if ($f !== null) return $f;+ }+ return array_map([self::class, 'unwire'], $v);}}\ No newline at end of filediff --git a/src/php/rec.php b/src/php/rec.phpindex ec32909..ba32ac9 100644--- a/src/php/rec.php+++ b/src/php/rec.php@@ -26,13 +26,20 @@ final class FastAnythingRecpublic static function enc($v): string{self::check($v);- return json_encode($v, JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);+ return json_encode(self::wire($v), JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);+ }++ // NaN and infinity, which JSON has no numbers for, travel as {"$float": "NaN"} (or+ // "Infinity", "-Infinity"), as the port's C entry point reads and writes them+ private static function wire($v)+ {+ if (is_float($v) && !is_finite($v)) return ['$float' => is_nan($v) ? 'NaN' : ($v > 0 ? 'Infinity' : '-Infinity')];+ return is_array($v) ? array_map([self::class, 'wire'], $v) : $v;}private static function check($v): void{if (is_array($v)) { foreach ($v as $x) self::check($x); return; }- if (is_float($v) && !is_finite($v)) throw new InvalidArgumentException('NaN or INF');if (is_string($v) && !preg_match('//u', $v)) throw new InvalidArgumentException('binary string');if (is_object($v)) throw new InvalidArgumentException(get_class($v) . ' object');if (is_resource($v)) throw new InvalidArgumentException('resource');@@ -110,7 +117,7 @@ final class FastAnythingRecif (is_int($v)) {foreach ([0, 1, -1] as $x) if ($x !== $v) $out[] = $x;} elseif (is_float($v)) {- foreach ([0.0, 1.0, -1.0, 1e300, 5e-324] as $x) if ($x !== $v) $out[] = $x;+ foreach ([0.0, -0.0, 1.0, -1.0, 1e300, 5e-324, NAN, INF, -INF] as $x) if ($x !== $v) $out[] = $x;} elseif (is_string($v)) {$chars = preg_split('//u', $v, -1, PREG_SPLIT_NO_EMPTY);if ($chars === false) return [];