Skip to content

Importing a rust file

Aritra Karak edited this page Oct 15, 2023 · 3 revisions

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.

  1. Create a new project with bun init.

  2. Install hyperimport in your project.

    bun i hyperimport
    
  3. Create a new file called bunfig.toml and add the preload script.

    preload = ["./node_modules/hyperimport/preload.ts"]
  4. Add the rust loader to the config below that.

    [hyperimport]
    loaders = ["rs"]
  5. Create a new file called math.rs.

  6. We'll write a simple function to add two numbers.

    #[no_mangle]
    pub extern "C" fn math(a: isize, b: isize) -> isize {
        a + b
    }
  7. 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.

  8. Run bun . to run index.ts.

  9. 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)
    
  10. Press enter and go with the defaults.

  11. 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.
    
  12. Navigate to the newly created file @types/math.rs/config.ts.

  13. 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 math function takes two ints as arguments and returns an int as a result.

  14. At this step, you'll notice the typescript error we got earlier is now resolved and if you hover over the math function, you'll find it is now properly typed.

  15. For the final step, run bun . again to rerun the script.

  16. 15 is successfully logged into the console as it should.

  17. To check auto reloading, go back to math.rs.

  18. Change the + to -.

  19. Run bun . again.

  20. Hyperimport automatically rebuilds the changed code and logs 5 into the console.