Port your TypeScript to Rust and prove it still works: hands-on with rust-anything
rust-anything went from zero to 5,614 stars in four days by solving the part of a Rust rewrite nobody wants to do by hand: proving the new code behaves exactly like the old code. This tutorial runs the whole loop — profile, bridge, record 449 cases, port, diff, bench, gate — and reports the honest numbers, including the ones where Rust loses.
- The project: erkamyaman/rust-anything, 5,614 stars, 451 forks, 287 commits, MIT, created November 16, 2026 — about 3,900 stars gained in week 47, 15th on GitHub's weekly trending list. Version 2.1.0.
- The loop: analyze → bridge → record → build → diff → gate, plus shadow for side-by-side production rollout. Works with TypeScript, Python, C, Go, Ruby, Java, and Kotlin; PHP and C# whole-app only.
- Verified here: 449 recorded cases (231 fuzzyScore, 218 bestMatch), 100% line coverage, 449/449 matched on diff, gate passed 14/14. A deliberate one-point scoring change was caught by diff and reverted.
- The honest bench: single calls ran at 0.19x (fuzzyScore) and 0.15x (bestMatch) — the tool itself says not to ship that for speed. Batch medians: 1.24x at 10,000 items, 0.40x at 100,000, 1.72x at 500,000, totals identical at every size.
- The cost: free, MIT, no API key, no account, no GPU. Needs Node.js 22.18+ and a Rust toolchain with the rustfmt and clippy components installed.

Every team with a slow TypeScript service has had the same conversation: rewrite the hot path in Rust, keep everything else. The rewrite itself is not the hard part. The hard part is proving the new code does exactly what the old code did — on every input, not just the ones in the test suite. That is the job rust-anything takes on, and it is why the project went from zero to the GitHub weekly trending list in four days.
rust-anything (erkamyaman/rust-anything) was created on November 16, 2026. By November 20 it had 5,614 stars and 451 forks, had gained about 3,900 stars in a single week — 15th on GitHub's weekly trending list — and shipped version 2.1.0. It is MIT-licensed, works with TypeScript, Python, C, Go, Ruby, Java, and Kotlin, and it does not translate code for you. It records what your code does, scaffolds the Rust crate and its bindings, and then checks every piece of your hand-written Rust against the recording. Nothing ships until the recording agrees.
This tutorial runs the whole loop on a real example and reports what actually happened — including the parts where Rust lost. You will install rust-anything, profile a small TypeScript project, port a function to Rust, record 449 test cases from the original, replay them all against the port, benchmark both, and pass the project's own definition-of-done gate. No API key, no account, no cloud, no GPU.
What you will need#
- Node.js 22.18 or newer. This tutorial was run with Node v24.22.1. Node needs to run TypeScript sources directly — version 22.6 and up strips types natively, so no build step is required for the demo.
- A Rust toolchain. rustc 1.99.1 and cargo 1.99.1 were used here. Install from rustup.rs if you do not have one. You will also need the
rustfmtandclippycomponents for the final gate:rustup component add rustfmt clippy. - A C compiler (
cc) for linking the native module. Present by default on most Linux and macOS machines. - About 15 minutes and roughly 300 MB of disk for the toolchain components and the npm package. The demo itself is two files.
- No account and no API key. Everything runs locally. A coding agent (Claude Code, Codex, Cursor, Gemini CLI, OpenCode) is optional: the tool can register itself with one, but every command in this tutorial is run by hand.
The demo project is a fuzzy-match scorer — the kind of small string function that sits in the hot path of a search box, a command palette, or a file finder. It is small enough to port by hand in one sitting and real enough that the verification has something to check. The same loop applies unchanged to a whole CLI or server; the demo is the unit, not the limit.
Step 1 — Install it#
Install the prebuilt binary from npm. This avoids compiling the tool itself from source — cargo install rust-anything also exists, but the npm package ships the same binary and finishes in seconds:
npm install -g rust-anything
rust-anything --version
Expected output:
added 1 package in 4s
rust-anything 2.1.0
Then check your environment. doctor lists every runtime the tool can use, what is missing, and the exact command that fixes each gap:
rust-anything doctor
ok cargo cargo 1.99.1
ok node v24.22.1
ok python3 Python 3.12.3
ok cc cc (Ubuntu 13.3.0)
missing go `go` not found (optional)
missing ruby `ruby` not found (optional)
missing java `java` not found (optional)
ok mcp server `rust-anything mcp` answered with 16 tools
Go, Ruby, Java, and the rest are optional: each language is only needed if you port code written in it. For this TypeScript tutorial, cargo, Node, and cc are the whole requirement. Note the last line: the tool also serves all of its steps as 16 MCP tools over stdio, which is how a coding agent drives it — but you will not need that here.
Step 2 — Profile first: find what is actually hot#
Never pick the port target by feel. Set up the demo project first. Create a directory with two files. The scorer is a case-insensitive subsequence match: +10 per query character matched in order, +5 per consecutive run, +8 when a match lands on a word boundary, −1 per skipped character, +15 if the whole query matched consecutively, 0 when the query is not a subsequence at all.
/**
* fuzzyScore: case-insensitive subsequence match score.
* +10 per query char matched in order, +5 per consecutive run,
* +8 when a match lands on a word boundary, -1 per skipped char.
* Returns an integer; 0 means the query is not a subsequence.
*/
export function fuzzyScore(query: string, text: string): number {
const q = query.toLowerCase();
const c = text.toLowerCase();
if (q.length === 0) return 0;
let score = 0;
let ci = 0;
let run = 0;
for (let qi = 0; qi < q.length; qi++) {
let found = -1;
for (let j = ci; j < c.length; j++) {
if (c[j] === q[qi]) { found = j; break; }
}
if (found === -1) return 0;
score += 10;
if (found === ci) {
run += 1;
score += 5;
} else {
run = 0;
score -= (found - ci);
}
if (found === 0 || c[found - 1] === ' ' || c[found - 1] === '-' || c[found - 1] === '_') {
score += 8;
}
ci = found + 1;
}
if (run === q.length) score += 15;
return score;
}
export function bestMatch(query: string, texts: string[]): string {
let best = '';
let bestScore = -1;
for (const cand of texts) {
const s = fuzzyScore(query, cand);
if (s > bestScore) { bestScore = s; best = cand; }
}
return best;
}
Save that as src/fuzzy.ts, then add a workload that exercises it — bench.mjs in the project root:
import { fuzzyScore } from './src/fuzzy.ts';
const words = ['fuzzy-search', 'file-manager', 'fast-render', 'filter-list',
'find-replace', 'format-code', 'fetch-data', 'frame-buffer',
'function-call', 'feature-flag'];
let total = 0;
const t0 = Date.now();
for (let i = 0; i < 20000; i++) {
for (const w of words) total += fuzzyScore('fz', w) + fuzzyScore('fmt', w) + fuzzyScore('file', w);
}
console.log('total', total, 'ms', Date.now() - t0);
Check the demo runs before you touch the tool — 600,000 calls, and the total must be 5,340,000:
node bench.mjs
total 5340000 ms 66
Now profile it. profile runs a real workload under the language's profiler and tells you what to port:
rust-anything profile . -- node bench.mjs
224 ms in all; 28% of it in the repository's own code.
| Function | File | Total | Self | Calls | Unit |
| --- | --- | --- | ---: | ---: | --- |
| `(anonymous):1` | `bench.mjs:1` | 29% (64 ms) | 49 ms | - | `bench.mjs` |
| `fuzzyScore` | `src/fuzzy.ts:7` | 6% (14 ms) | 14 ms | - | `src/fuzzy.ts` |
## What to port
- **`fuzzyScore`** (6%): Hot and exported by `src/fuzzy.ts`: port it
(`rust-anything bridge /var/tmp/ra-verify/demo src/fuzzy.ts`),
then check `rust-anything bench`.
Two things matter here. First, the profiler names the function and the exact next command — you do not have to guess. Second, 6% is small: this demo is a teaching example, not a production bottleneck. In a real codebase you would run profile against your actual workload and port whatever it ranks first. There is also a bigger starting point, rust-anything analyze, which maps the whole repository into a ranked migration plan; it ranked this file first with priority 68 and readiness 97 out of 100, and noted that the napi bridge "runs with what Node already has". That note decides Step 3.
Step 3 — Bridge: scaffold the Rust crate#
bridge generates the Rust crate, the JavaScript bindings, and the manifest that ties the port to the original. Two choices matter, and the wrong defaults cost you a toolchain install:
- Bridge kind. The default is
wasm(wasm-bindgen), which needs thewasm32-unknown-unknowntarget and thewasm-bindgen-clibinary. Pass--kind napiinstead and the crate builds with plain cargo into a.nodemodule Node loads directly. Choose wasm if the port must also run in a browser; choose napi for a Node service or CLI. - Batching.
--batch fuzzyScore:textadds a batch class that keeps manytextvalues inside Rust and scores them all in one call, in parallel across cores. It is the difference between Step 7's two benchmark panels, so include it.
rust-anything bridge . src/fuzzy.ts --kind napi --batch fuzzyScore:text
Created /var/tmp/ra-verify/demo/rust/fuzzy-rs (Napi) for fuzzyScore, bestMatch
Cargo.toml
src/lib.rs
src/port.rs
index.cjs
.gitignore
README.md
rust-anything.json
build.rs
src/wire.rs
One gotcha, verified twice: pass the crate directory as an absolute path to the later commands (record, build, diff, gate). With a relative path, rust-anything build rust/fuzzy-rs fails with manifest path 'rust/fuzzy-rs/Cargo.toml' does not exist even though the file is there. The absolute path works every time.
Open the scaffold. Cargo.toml pulls in napi 3, rayon for the parallel batch, and mimalloc as the global allocator. src/port.rs holds two unimplemented!() stubs — that file is yours to write. src/lib.rs and index.cjs are generated bindings; you do not edit them. rust-anything.json records the mapping between the TypeScript exports and the crate, including the batch declaration.
Step 4 — Write the port#
rust-anything does not translate code: you — or your coding agent — write the Rust. What the tool gives you is everything an agent cannot guess reliably: where the time goes, what to port first, the bridge so callers keep the original API, the exact behavior the port must match, and the gate that says when it is done. Your job in this step is a faithful translation of the TypeScript, nothing more.
There is one subtlety that decides whether the port passes. JavaScript indexes strings by UTF-16 code unit: c[j] and q.length count 16-bit units, so an emoji is two positions. Rust's chars() counts Unicode code points, so an emoji is one. If you port the loop over chars(), ASCII inputs will match and non-ASCII inputs will silently diverge. Work on UTF-16 units instead — encode_utf16 after lowercasing — and the two implementations agree on every input. This is the complete port, exactly as verified:
//! The Rust port of `src/fuzzy.ts`.
//!
//! The TypeScript indexes strings by UTF-16 code unit (`c[j]`, `q.length`),
//! so this port works on UTF-16 units too — `encode_utf16` after lowercasing —
//! which keeps scores identical for non-ASCII input as well as ASCII.
#![forbid(unsafe_code)]
/// Port of `fuzzyScore` (`src/fuzzy.ts:7`).
pub fn fuzzy_score(query: String, text: String) -> Result<f64, String> {
let q: Vec<u16> = query.to_lowercase().encode_utf16().collect();
let c: Vec<u16> = text.to_lowercase().encode_utf16().collect();
if q.is_empty() {
return Ok(0.0);
}
let mut score: i64 = 0;
let mut ci: usize = 0;
let mut run: usize = 0;
for &qc in &q {
let mut found: Option<usize> = None;
for (j, &cc) in c.iter().enumerate().skip(ci) {
if cc == qc {
found = Some(j);
break;
}
}
let Some(found) = found else {
return Ok(0.0);
};
score += 10;
if found == ci {
run += 1;
score += 5;
} else {
run = 0;
score -= (found - ci) as i64;
}
if found == 0 || c[found - 1] == 0x20 || c[found - 1] == 0x2D || c[found - 1] == 0x5F {
score += 8;
}
ci = found + 1;
}
if run == q.len() {
score += 15;
}
Ok(score as f64)
}
/// Port of `bestMatch` (`src/fuzzy.ts:37`).
pub fn best_match(query: String, texts: Vec<String>) -> Result<String, String> {
let mut best = String::new();
let mut best_score: f64 = -1.0;
for cand in &texts {
let s = fuzzy_score(query.clone(), cand.clone())?;
if s > best_score {
best_score = s;
best = cand.clone();
}
}
Ok(best)
}
Two details worth copying. The stub signatures return Result<f64, String> and Result<String, String>: return Err where the source throws, and the caller sees an error there too. And #![forbid(unsafe_code)] sits at the top — the generated bindings need a little unsafe behind the scenes, but your port does not, and the gate checks that it stays that way.
Check the port against your own hand-picked cases before the tool's recording runs. A unit test in port.rs pins the arithmetic — and it caught a mistake in this tutorial's own first draft, where the expected value for fuzzyScore("fi", "file-manager") was written as 46 and the real answer is 53 (23 for the f, 15 for the i, plus the 15-point run bonus). The test failed, the arithmetic was rechecked by hand, and the expectation was fixed — that is the workflow working as intended:
cargo test --lib
running 1 test
test port::tests::scores_match_the_typescript ... ok
test result: ok. 1 passed; 0 failed
Step 5 — Record: let the original define "correct"#
This is the step that makes the whole approach different from a rewrite-and-hope. record runs the TypeScript original on generated inputs — edge cases, semantic traps, and your own inputs — and saves what each call returns. The recording is the specification. The port is correct when it reproduces the recording, not when it looks right:
rust-anything record /var/tmp/ra-verify/demo/rust/fuzzy-rs
Recorded 449 cases (0 threw) in /var/tmp/ra-verify/demo/rust/fuzzy-rs/cases.jsonl
bestMatch: 218
fuzzyScore: 231
Coverage: the recorded cases ran 44 of the original's 44 lines (100%)
449 cases, 200 generated per function by default plus extras, and they cover 100% of the original's lines. Look at what the generator actually produced — it is not polite ASCII:
{"fn":"fuzzyScore","args":["HELLO","src/a/b.ts"],"ok":0}
{"fn":"fuzzyScore","args":["étrailing."," padded "],"ok":0}
{"fn":"fuzzyScore","args":["tab separated","ΣΊΣΥΦΟΣ"],"ok":0}
Greek, combining accents, tabs, a byte-order mark, emoji in other cases. This is why Step 4's UTF-16 decision matters: a port over Rust chars() would have failed these cases, and you would have found out in Step 6 instead of in production. cases.jsonl is committed with the crate, so the recording travels with the port and any later change to the original shows up as a diff against it. You can add your own cases with --inputs (JSONL of {"fn": name, "args": [...]}), and --from-tests records every call the original's own test suite makes.

Step 6 — Build, then replay every case#
Build the native module, then replay the recording against it:
rust-anything build /var/tmp/ra-verify/demo/rust/fuzzy-rs
rust-anything diff /var/tmp/ra-verify/demo/rust/fuzzy-rs
Built /var/tmp/ra-verify/demo/rust/fuzzy-rs/fuzzy_rs.node
449/449 cases match
449 out of 449, including every unicode edge case. The build compiles the crate in release mode with link-time optimization and produces the .node module Node loads through the generated index.cjs.
Before trusting that number, break something on purpose. Change one constant in the port — the consecutive-match bonus from +5 to +4 — rebuild, and diff again. A check that cannot fail is not a check:
- fuzzyScore("ab", "a😀b😀c"): expected {"ok":31}, got {"ok":30}
- fuzzyScore("🏽 m", "emoji 👍🏽 mix"): expected {"ok":55}, got {"ok":52}
- fuzzyScore("İstanbul", ".leadingİstanbul"): expected {"ok":117}, got {"ok":110}
- fuzzyScore("tems{name} has {coun", "{name} has {count} items{name} has {count} items"): expected {"ok":286}, got {"ok":268}
- fuzzyScore(":", ":"): expected {"ok":38}, got {"ok":37}
The one-point change fails case after case, with the exact expected and actual values for each. Restore the constant, rebuild, and the count returns to 449/449. The recording catches a single-point scoring drift across ASCII, emoji, Turkish dotted capitals, and template strings alike — that is the whole point of recording behavior instead of asserting a handful of examples.
Step 7 — Bench it, honestly#
bench times the recorded cases on the TypeScript original and on the Rust port, crossing included, and gives a verdict:
rust-anything bench /var/tmp/ra-verify/demo/rust/fuzzy-rs
function cases orig ns/call Rust ns/call speedup
fuzzyScore 231 140 741 0.19x
bestMatch 218 254 1658 0.15x
Timed as callers call it, crossing included. Overall 0.17x (geometric mean);
0 of 2 functions at least 1.1x faster.
Do not ship this unit for speed: calling across costs more than the work
these functions do. Port a bigger unit (these functions together with their
callers), so one call does more work.
Read that again: the Rust port is five to six times slower per call. The function itself takes about 140 nanoseconds in TypeScript; crossing from JavaScript into the native module costs more than the work. This is not a bug in the tool — the project's own README says the same thing, in the same words: calling Rust once per small function is usually slower than a JIT, and the tool finds the loop worth moving and moves it. A tutorial that hid this number would be selling the tool short; the honest number is the reason the next paragraph exists.
The fix is the batch class from Step 3. One crossing carries thousands of items into Rust, where rayon scores them in parallel across cores. Measured on a 4-core Linux VM, five repetitions, warmed up, totals identical between the two implementations at every size:
| Items scored | TypeScript loop (median) | Rust batch (median) | Speedup |
|---|---|---|---|
| 10,000 | 3.0 ms | 2.4 ms | 1.24x |
| 100,000 | 26.5 ms | 66.8 ms | 0.40x |
| 500,000 | 163.9 ms | 95.6 ms | 1.72x |
The batch numbers are noisy — repeated runs on this shared machine ranged from roughly break-even to about 3x at the same sizes — so do not quote a single figure. The shape is what matters: single calls lose by a wide margin, small batches roughly tie, and large batches win by up to a few times. The same shape shows up in the project's own reported results at real scale: its Prettier port runs 19x faster with 15,837 of 17,224 recorded runs fully in Rust, and its json-server port answers 514 of 514 recorded HTTP cases from a single 5.3 MB binary. Speed comes from porting a unit that does real work per call, not from the language change alone. Use it from Node like this — the batch and the single-call functions live in the same module:
const { fuzzyScore, FuzzyScoreBatch } = require('./rust/fuzzy-rs/index.cjs');
const batch = new FuzzyScoreBatch(items); // items stay in Rust
const scores = batch.run('fmt'); // one crossing, all cores
const top = batch.rank('fmt', 30); // indexes scoring >= 30, best first
fuzzyScore('fmt', 'format-code'); // 40, same as the TypeScript

Step 8 — Pass the gate#
gate is the project's definition of done, run as one command: formatting, clippy, tests, unsafe audit, lockfile, no leftover stubs, size, error cases, panics, build, coverage, API, and behavior. It failed twice here before it passed, and both failures were instructive:
rust-anything gate /var/tmp/ra-verify/demo/rust/fuzzy-rs
First failure: the rustfmt and clippy components were not installed for the toolchain — the minimal rustup profile does not include them. The gate prints the fix, so run it:
rustup component add rustfmt clippy
Second failure: two clippy lints in the port, both needless_range_loop — the index loops for qi in 0..q.len() and for j in ci..c.len(). Rewriting them as iterators (for &qc in &q, for (j, &cc) in c.iter().enumerate().skip(ci)) cleared clippy, and cargo fmt cleaned up the generated lib.rs too — the scaffold itself ships one unformatted blank line, which the gate flags. After those fixes:
pass fmt formatted
pass clippy no warnings
pass cargo test passed
pass unsafe 3 unsafe uses, each with a `// SAFETY:` comment
pass lockfile Cargo.lock matches Cargo.toml
pass ported nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`
pass size 79 lines of Rust for 38 lines of TypeScript/JavaScript (2.1x)
pass error cases the original fails on purpose nowhere
pass panics no unwrap, expect or panic where the original returns an error
pass build built /var/tmp/ra-verify/demo/rust/fuzzy-rs/fuzzy_rs.node
pass coverage the recorded cases ran 44 of the original's 44 lines (100%)
pass api exports fuzzyScore, bestMatch
pass behavior 449/449 recorded cases match
Gate passed.
Fourteen checks, all green. The size line is worth noting for planning: 79 lines of Rust for 38 of TypeScript, about 2.1x. Porting is not free in code volume — the payoff is the proof, not brevity.
Step 9 — Ship it safely: shadow mode and the batch habit#
Passing the gate does not mean deploying blind. shadow generates a drop-in module that runs the TypeScript original and the Rust port side by side in your real application:
rust-anything shadow /var/tmp/ra-verify/demo/rust/fuzzy-rs
Wrote /var/tmp/ra-verify/demo/rust/fuzzy-rs/shadow/fuzzy.shadow.ts (fuzzyScore, bestMatch)
Import it in place of the original. RUST_ANYTHING_MODE=old|shadow|new switches at runtime.
Import the shadow module in place of the original. In the default shadow mode it returns the original's result, runs the Rust port alongside, and logs the first 10 mismatches. RUST_ANYTHING_MODE=new runs Rust only; old runs the original only. Verified here in new mode: fuzzyScore('fmt', 'format-code') returns 40 and bestMatch('fm', ['fast-render', 'file-manager']) returns 'file-manager' — identical to the TypeScript, through the drop-in module. The rollout is therefore: record, port, gate, shadow in production for a while, then switch the mode to new and delete the original. If a mismatch ever appears, the shadow log names the function, the arguments, and both answers.
Two habits to keep from this tutorial. First, always run analyze before you start — on a real repository it ranks every unit by readiness and priority and tells you which wave each port belongs to, so the first port is the easy one, not the impressive one. Second, port the loop, not the leaf: a single tiny function will lose to the crossing cost every time, so the unit worth porting is the function together with its callers, or the batch that keeps the work on the Rust side.
When to use this vs the alternatives#
- Versus rewriting by hand and testing as you go: use rust-anything. A hand rewrite checks the cases you thought of; the recording checks 449, including the ones the generator invented. The cost is learning one CLI.
- Versus calling napi-rs or wasm-bindgen directly: use rust-anything if the port is the hard part, napi or wasm-bindgen directly if the bindings are the hard part. The tool generates both bindings for you; it earns its keep on the verification, not the scaffolding.
- Versus an agent that rewrites the whole app (REA, Craft Anything): different job. Whole-app rewriters aim at a new codebase; rust-anything aims at one verified unit at a time, with a recording that survives the port. Use the whole-app tools for a greenfield rewrite and this one for the hot path you cannot afford to get wrong.
- Versus doing nothing: if the profiler says the function is 6% of a workload that runs in 224 ms, do nothing. Porting is justified by the profile, not by the language. The tool's own bench verdict will tell you the same thing.
Skip it when the code is I/O-bound, when the hot function is a single database call, or when no Rust toolchain can run where the code ships. It also cannot catch what the recording does not cover: the README is explicit that side effects need --effects recording, and that code which writes files, talks to a database, or calls the network does so once per recorded case — run recording on a copy of the project, with a test database and no production credentials in the environment.
The takeaway#
rust-anything does not make Rust faster. It makes a Rust rewrite checkable: record what the code does, write the port, replay the recording, and let a gate decide when it is done. On a toy scorer the speedup is negative for single calls and modest for batches — the tool says so itself, in its own output — and the value is the 449-case proof that the port behaves identically, including on inputs no human would have written. That proof is what a rewrite usually lacks, and it is the reason a four-day-old project with no marketing has 5,614 stars. Port the loop, not the leaf; record first; ship behind a shadow.
How this tutorial was verified#
Every command in this tutorial was run on a 4-core Linux VM on November 20, 2026, with rust-anything 2.1.0 (installed from npm as a prebuilt binary), cargo 1.99.1, Node v24.22.1, and Python 3.12.3. The demo project, the port, and the measurements are the author's own; the tool's demo directory was read for reference only. Results: profile identified fuzzyScore at 6% of a 224 ms workload; bridge --kind napi scaffolded the crate; record produced 449 cases at 100% line coverage; diff matched 449/449; a deliberate one-point scoring change was caught by diff with exact expected and actual values, then reverted; bench measured 140 ns vs 741 ns per call for fuzzyScore and 254 ns vs 1,658 ns for bestMatch; batch medians over five warmed-up runs were 3.0 ms vs 2.4 ms at 10,000 items, 26.5 ms vs 66.8 ms at 100,000, and 163.9 ms vs 95.6 ms at 500,000, with totals identical at every size; gate passed all 14 checks after installing the rustfmt and clippy components and fixing two clippy lints; shadow in new mode returned the same answers as the TypeScript. The only commands that did not run as documented were the relative-path forms of build, diff, and gate, which mis-resolve the manifest path — absolute paths work, and the tutorial uses them throughout. No API key or account was needed at any point.