Pre-requisites :
Please ensure that you have installed Rust and Cargo
Â
Tool Setup
We need to install WASM Pack
cargo install wasm-pack
Rust Code
First create a new binary crate using below command:
cargo new demo
You can use any IDE of your choice and open up this project folder.
On Cargo.toml we are going to add the next:
[package]
name = "demo"
version = "0.1.0"
authors = ["Shraddha Inamdar <shraddha.inamdar95@gmail.com>"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[[bin]]
path = "src/main.rs"
name = "main"
Â
Writing Rust code
Writing a code for reading from file and writing to file using Rust.
use std::env;
use std::fs;
use std::io::{Read, Write};
fn process(input_fname: &str, output_fname: &str) -> Result<(), String> {
let mut input_file =
fs::File::open(input_fname).map_err(|err| format!("Not Able To Open {}: {}", input_fname, err))?;
let mut contents = Vec::new();
input_file
.read_to_end(&mut contents)
.map_err(|err| format!("Not Able To Read: {}", err))?;
let mut output_file = fs::File::create(output_fname)
.map_err(|err| format!("Not Able To Open Output {}: {}", output_fname, err))?;
output_file
.write_all(&contents)
.map_err(|err| format!("write error: {}", err))
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
if args.len() < 3 {
eprintln!("usage: {} <from> <to>", program);
return;
}
if let Err(err) = process(&args[1], &args[2]) {
eprintln!("{}", err)
}
}
Compiling Rust Code
- Compile using cargo
cargo build --target=wasm32-wasi
- The wasm file created in debug folder of wasi32
file target/wasm32-wasi/debug/main.wasm
- Wasm runtime
wasmtime target/wasm32-wasi/debug/main.wasm
- Created test.txt and output.txt with test.txt containing input
echo "Hi there, You made it! Cheers :)" > test.txt
touch output.txt
- Run using wasmtime
wasmtime target/wasm32-wasi/debug/main.wasm test.txt output.txt
- Solving the above error using –dir
wasmtime --dir=. --dir=. target/wasm32-wasi/debug/main.wasm test.txt output.txt
- Displaying the output
cat output.txt
Top comments (0)