-
Notifications
You must be signed in to change notification settings - Fork 12
Importing a rust file
Let's see a step by step guide on how you can import a rust file. The same guide can be followed to load a zig file too.
-
Create a new project with
bun init. -
Install
hyperimportin your project.bun i hyperimport -
Create a new file called
bunfig.tomland add the preload script.preload = ["./node_modules/hyperimport/preload.ts"]
-
Add the rust loader to the config below that.
[hyperimport] loaders = ["rs"]
-
Create a new file called
math.rs. -
We'll write a simple function to add two numbers.
#[no_mangle] pub extern "C" fn math(a: isize, b: isize) -> isize { a + b }
-
Inside the index.ts file, call this math function.
import { math } from "./math.rs"; console.log(math(10, 5));
You'll find the typescript error
Cannot find module, don't worry, it will get fixed in the next steps. -
Run
bun .to run index.ts. -
You'll see something like this in your console output,
[HYPERIMPORT]: Rust Loader No configuration was found for "/hypertest/math.rs" Enter the build command and output directory to configure it. Press enter to use the default values. build command: (default) -
Press enter and go with the defaults.
-
You'll see something like this now,
Config file has been generated at "/hypertest/@types/math.rs/config.ts" Edit the config.ts and set the argument and return types, then rerun the script. -
Navigate to the newly created file
@types/math.rs/config.ts. -
Inside you'll find the configuration to load math.rs. Add the argument and return types for the math function.
math: { args: [T.int, T.int], returns: T.int }
This tells FFI that, the
mathfunction takes twoints as arguments and returns anintas a result. -
At this step, you'll notice the typescript error we got earlier is now resolved and if you hover over the
mathfunction, you'll find it is now properly typed. -
For the final step, run
bun .again to rerun the script. -
15is successfully logged into the console as it should. -
To check auto reloading, go back to math.rs.
-
Change the
+to-. -
Run
bun .again. -
Hyperimport automatically rebuilds the changed code and logs
5into the console.