This project demonstrates how to integrate Rust code, with TypeScript for web applications using bun:ffi module. It showcases how Rust's performance and safety, combined with TypeScript's ease of development, provide a powerful combination for modern web development.
-
Performance: Rust provides low-level control and performance optimizations, ideal for compute-intensive tasks in web applications.
-
Safety: Rust's strong type system and ownership model prevent common bugs such as null pointer dereferences and data races.
-
Developer Experience: TypeScript offers a productive environment with type checking and modern JavaScript features, enhancing code quality and maintainability.
-
Compilation: Rust code compiles into native executable binaries tailored for the target platform.
-
Integration: TypeScript imports and interacts with these compiled binaries using bun:ffi module, facilitating seamless functionality within web applications.
The project includes a benchmark comparing JavaScript and Rust sorting capabilities:
const bigArray = new Int32Array(Array.from({ length: 1000000 }, () => Math.floor(Math.random() * 1000000)))
console.time("Rust Sort time");
lib.symbols.sort_array(bigArray.slice(), bigArray.length);
console.timeEnd("Rust Sort time");
console.time("JS Sort time");
bigArray.sort((a, b) => a - b);
console.timeEnd("JS Sort time");
output:
[Rust Sort time]: 56.76ms
[JS Sort time]: 301.31ms
To run the project:
- Navigate to the bun project folder:
cd src/bun_project
- Execute the following command to build and run the project:
bun run dev