Wasm Builders

Cover image for A minigrep tool with Rust
Ngumih Fien
Ngumih Fien

Posted on

A minigrep tool with Rust

Welcome back guys. I built a minigrep tool with Rust. This tool goes through a file of text provided by you, and outputs the line(s) containing the piece of string you are searching for.
It accepts two Command line arguments; the string you want to search for, and the filename.
The file of text(a .txt file) is placed in the code directory and to search for a particular word(s), you run cargo run searchstring example-filename.txt
To demonstrate, I searched for the string "or" in my sample.txt file and it gave me the results.

Image description

To replicate this project with Rust, you should do the following;

  • run cargo new minigrep: This creates a binary(application) "minigrep" project.
  • run cd minigrep: Takes you to the minigrep directory you just created.
  • Open the project in your IDE. You will find a main.rs file inside the src folder. We need to edit this folder to accept its two command line arguments: the filename and a string to search for. That is, we want to be able to run our program with cargo run, a string to search for, and a path to a file to search in, like so: cargo run searchstring example-filename.txt .
  • You can get the code from https://github.com/enarx/outreachy/tree/main/Fienne/minigrep/src. I added a lib.rs file which contain tests that carry out error handling such as when the user provides no arguments.

To run the code using WebAssembly:

  • Install Rust .
  • Install Wasmtime
  • Install the WebAssembly toolchain: rustup target install wasm32-wasi

Navigate to the file you want to compile to WebAssembly and do:

  • Compile using cargo: cargo build cargo run
  • Compile to wasm : cargo build --target=wasm32-wasi *The wasm file created in release folder of wasi32 : file target/wasm32-wasi/release/demo.wasm
  • Wasm runtime: wasmtime target/wasm32-wasi/release/demo.wasm

Discussion (0)