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
C++: answer derived and edge cases in child processes
Mohit Mishra5b4318b2dd52
diff --git a/src/cfamily.rs b/src/cfamily.rsindex 4a52a4d..c7cf9d4 100644--- a/src/cfamily.rs+++ b/src/cfamily.rs@@ -1385,6 +1385,62 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {mod tests {use super::*;+ /// Compiles C++ `source` with the recording code of its function `name` and runs it; returns+ /// the recordings, or None without a C++ compiler.+ fn record_cpp(source: &str, name: &str) -> Option<Vec<Value>> {+ let cc = ["c++", "g++", "clang++"].into_iter().find(|c| Command::new(c).arg("--version").output().is_ok())?;+ let f = parse(source).into_iter().find(|f| f.name == name).unwrap();+ let hs = Hotspot {+ name: f.name.clone(),+ params: f.params.clone(),+ returns: Some(f.ret.clone()),+ ..Hotspot::default()+ };+ let dir = std::env::temp_dir().join(format!("fa-cpp-rec-test-{name}-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("fa_rec.hpp"), REC_HPP.replace("/*JSON*/", JSON_HPP)).unwrap();+ let prologue = cpp_record_prologue(&hs).replace('\n', " ");+ fs::write(dir.join("app.cpp"), insert_at(source, vec![(f.body_open + 1, format!(" {prologue}"))])).unwrap();+ let built = Command::new(cc)+ .args(["-std=c++17", "-O1", "-include", "fa_rec.hpp", "app.cpp", "-o", "app"])+ .current_dir(&dir)+ .output()+ .unwrap();+ assert!(built.status.success(), "{}", String::from_utf8_lossy(&built.stderr));+ let ran = Command::new(dir.join("app"))+ .current_dir(&dir)+ .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))+ .env("FAST_ANYTHING_RECORD_META", dir.join("meta.json"))+ .output()+ .unwrap();+ let text = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default();+ let _ = fs::remove_dir_all(&dir);+ assert!(ran.status.success(), "{}", String::from_utf8_lossy(&ran.stderr));+ Some(text.lines().map(|l| serde_json::from_str(l).unwrap()).collect())+ }++ #[cfg(unix)]+ #[test]+ fn cpp_edge_cases_that_hang_or_crash_are_skipped() {+ use serde_json::json;+ // never returns for 0 or -1+ let spin = "long spin(long n) {\n long steps = 0;\n while (n != 1) {\n n = n % 2 ? 3 * n + 1 : n / 2;\n steps++;\n }\n return steps;\n}\nint main() {\n long t = 0;\n for (long k = 2; k < 30; k++) t += spin(k);\n return t > 0 ? 0 : 1;\n}\n";+ let started = std::time::Instant::now();+ let Some(cases) = record_cpp(spin, "spin") else {+ eprintln!("no C++ compiler on PATH, skipping");+ return;+ };+ assert!(started.elapsed().as_secs() < 30, "the recording finished");+ let edges: Vec<&Value> = cases.iter().filter(|c| c["derived"] == "edge").collect();+ assert!(edges.iter().any(|c| c["args"] == json!([1]) && c["result"] == json!(0)), "{edges:?}");+ assert!(edges.iter().all(|c| c["args"] != json!([0]) && c["args"] != json!([-1])), "{edges:?}");+ // reads xs[0] whatever the size: crashes on an empty vector+ let first = "#include <vector>\nint first(const std::vector<int> &xs) {\n return ((volatile const int *) xs.data())[0] * 0 + (int) xs.size();\n}\nint main() {\n std::vector<int> xs(20, 1);\n int t = 0;\n for (int k = 0; k < 3; k++) t += first(xs);\n return t > 0 ? 0 : 1;\n}\n";+ let cases = record_cpp(first, "first").unwrap();+ let edges: Vec<&Value> = cases.iter().filter(|c| c["derived"] == "edge").collect();+ assert!(!edges.is_empty() && edges.iter().all(|c| c["args"] != json!([[]])), "{edges:?}");+ }+#[test]fn finds_c_and_cpp_functions() {let c = "#include <stdio.h>\n/* a { comment */\nstatic int lev(const char *a, const char *b) {\n return 0;\n}\n\nlong count(const int *xs, size_t n, int max)\n{\n if (n) { return 1; }\n printf(\"{\");\n return 0;\n}\nint main(void) { return lev(\"a\", \"b\"); }\n";diff --git a/src/cfamily/rec.hpp b/src/cfamily/rec.hppindex a809d95..e0b6c44 100644--- a/src/cfamily/rec.hpp+++ b/src/cfamily/rec.hpp@@ -16,6 +16,12 @@#include <unordered_map>#include <utility>#include <vector>+#ifndef _WIN32+#include <cerrno>+#include <sys/time.h>+#include <sys/wait.h>+#include <unistd.h>+#endifnamespace fa_rec {/*JSON*/@@ -177,6 +183,65 @@ template <class T, class Al> std::vector<std::vector<T, Al>> variants(const std:template <class F, class Tup, size_t... I> auto apply(F &f, Tup &t, std::index_sequence<I...>) -> decltype(f(std::get<I>(t)...)) {return f(std::get<I>(t)...);}+// Has the original answer one derived or edge case: run(out) calls it and writes its result as JSON.+// An input outside the function's domain may crash it or never return, not only throw, so on POSIX+// it runs in a child process, where a crash or a case still running after 250ms only skips it.+// False if it didn't answer; took is how long it took.+template <class Run> bool answer(Run run, std::string &out, long long &took) {+#ifdef _WIN32+ try {+ long long t = now();+ bool ok = run(out);+ took = now() - t;+ return ok;+ } catch (...) {+ return false; // outside the function's domain: not a fair test+ }+#else+ int fd[2];+ if (pipe(fd)) return false;+ std::fflush(nullptr);+ long long t = now();+ pid_t pid = fork();+ if (pid == 0) {+ close(fd[0]);+ struct itimerval timer = {{0, 0}, {0, 250000}};+ setitimer(ITIMER_REAL, &timer, nullptr);+ bool ok = false;+ std::string r;+ try {+ ok = run(r);+ } catch (...) {+ }+ ok = ok && write(fd[1], r.data(), r.size()) == (ssize_t) r.size();+ _exit(ok ? 0 : 1);+ }+ close(fd[1]);+ if (pid < 0) {+ close(fd[0]);+ return false;+ }+ out.clear();+ char chunk[256];+ ssize_t n;+ bool read_ok = true;+ while ((n = read(fd[0], chunk, sizeof chunk)) != 0) {+ if (n > 0) {+ out.append(chunk, (size_t) n);+ } else if (errno != EINTR) {+ read_ok = false;+ break;+ }+ }+ close(fd[0]);+ int status = 0;+ while (waitpid(pid, &status, 0) < 0) {+ if (errno != EINTR) return false;+ }+ took = now() - t;+ return read_ok && WIFEXITED(status) && WEXITSTATUS(status) == 0 && !out.empty();+#endif+}template <class Tup, size_t... I> bool encode_tuple(std::string &o, const Tup &t, std::index_sequence<I...>) { return enc_all(o, std::get<I>(t)...); }template <size_t I, class F, class Tup, class Seq> void derive_one(F &f, const Tup &args, Seq seq) {for (auto &smaller : variants(std::get<I>(args))) {@@ -186,13 +251,10 @@ template <size_t I, class F, class Tup, class Seq> void derive_one(F &f, const Tstd::string in = "[";if (!encode_tuple(in, next_args, seq)) continue;in += "]";- try {- auto r = apply(f, next_args, seq);- std::string out;- if (enc(out, r)) st().derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":true}");- } catch (...) {- // outside the function's domain: not a fair test- }+ std::string out;+ long long took;+ if (answer([&](std::string &o) { auto r = apply(f, next_args, seq); return enc(o, r); }, out, took))+ st().derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":true}");}}template <class F, class Tup, class Seq> long long edge_try(F &f, const Tup &next_args, Seq seq) {@@ -202,19 +264,12 @@ template <class F, class Tup, class Seq> long long edge_try(F &f, const Tup &nexauto &s = st();if (s.seen[in]) return -1;s.seen[in] = true;- try {- Tup copy = next_args;- long long t = now();- auto r = apply(f, copy, seq);- long long took = now() - t;- std::string out;- if (!enc(out, r)) return -1;- s.derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":\"edge\"}");- s.edges++;- return took;- } catch (...) {- return -1; // outside the function's domain: not a fair test- }+ std::string out;+ long long took;+ if (!answer([&](std::string &o) { Tup copy = next_args; auto r = apply(f, copy, seq); return enc(o, r); }, out, took)) return -1;+ s.derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":\"edge\"}");+ s.edges++;+ return took;}template <size_t I, class F, class Tup, class Seq> void edge_one(F &f, const Tup &args, Seq seq) {const Tup base = small_tuple(args, seq);@@ -230,14 +285,8 @@ template <size_t I, class F, class Tup, class Seq> void edge_one(F &f, const Tup// much bigger inputs, only while their time (assumed quadratic) fits the budgets.grown[I] = true;long long took;- try {- Tup copy = base;- long long t = now();- apply(f, copy, seq);- took = now() - t;- } catch (...) {- return;- }+ std::string ignored;+ if (!answer([&](std::string &o) { Tup copy = base; apply(f, copy, seq); o = "-"; return true; }, ignored, took)) return;// 4x bigger each step, from the short version of the input, up to 4096 itemsfor (int factor : {4, 16, 64, 256, 512}) {if (!edge_ok() || !bigger(std::get<I>(base), factor, big) || took * 16 > edge_left() / 2) return;