WebAssembly (WASM) and Rust | wranto

0
WebAssembly (WASM) has revolutionized web development by enabling high-performance applications to run on the browser. With the help of programming languages like Rust, developers can harness the power of WASM to create efficient and portable web applications. In this article, we will explore the fundamentals of WebAssembly, its advantages, and how WebAssembly can be effectively implemented using Rust, along with some code samples.

WebAssembly and Rust
 

Understanding WebAssembly (WASM):

WebAssembly is a binary instruction format designed to execute code at near-native speed in a web browser. WebAssembly serves as a portable target for the compilation of high-level languages like C, C++, and Rust. Unlike JavaScript, which is an interpreted language, WebAssembly is compiled ahead of time (AOT), resulting in better performance.

Benefits of WebAssembly:

PerformanceWebAssembly runs at near-native speed, enabling web applications to perform complex calculations and computations efficiently. This performance boost opens up opportunities for building gaming applications, multimedia processing, and other computationally intensive tasks.

Portability: With WebAssembly, developers can write code in any language that supports it and run it across different platforms and browsers. This portability eliminates the need for rewriting code in different languages for specific platforms, reducing development time and effort.

Security: WebAssembly runs in a sandboxed environment, providing an additional layer of security for web applications. It prevents malicious code from accessing sensitive information or causing damage to the user's system.

Implementing WebAssembly with Rust:

Rust is a systems programming language known for its focus on safety, performance, and concurrency. It provides strong static typing, memory safety, and modern language features. Rust is an ideal language for wasm due to its low-level control and ability to generate efficient code.

Here's a step-by-step guide to implementing Rust wasm:

Step 1 : Install Rust and WebAssembly Target:

To get started, you'll need to have Rust installed on your system. Visit the official Rust website (https://www.rust-lang.org/) for installation instructions. Once Rust is installed, you can add the WebAssembly target by executing the following command in your terminal:
$ rustup target add wasm32-unknown-unknown

Step 2 : Set up a New Rust Project:

Create a new Rust project using Cargo, the Rust package manager. Open your terminal and run the following command:

$ cargo new wasm-project
$ cd wasm-project

Step 3: Add Dependencies and Configuration:

Open the `Cargo.toml` file in your project directory and add the following lines:

Cargo.toml

[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.87"

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index.js',
    },
    plugins: [
        new HtmlWebpackPlugin(),
        new WasmPackPlugin({
            crateDirectory: path.resolve(__dirname, ".")
        }),
        // Have this example work in Edge which doesn't ship `TextEncoder` or
        // `TextDecoder` at this time.
        new webpack.ProvidePlugin({
          TextDecoder: ['text-encoding', 'TextDecoder'],
          TextEncoder: ['text-encoding', 'TextEncoder']
        })
    ],
    mode: 'development',
    experiments: {
        asyncWebAssembly: true
   }
};

package.json

{
  "scripts": {
    "build": "webpack",
    "serve": "webpack serve"
  },
  "devDependencies": {
    "@wasm-tool/wasm-pack-plugin": "1.5.0",
    "html-webpack-plugin": "^5.3.2",
    "text-encoding": "^0.7.0",
    "webpack": "^5.49.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^4.15.1"
  }
}

Step 4: Write Rust Code:

In the `src/lib.rs` file, you can write your Rust code that will be compiled into WebAssembly. Here's a simple example that exports a function to calculate the sum of two numbers:
rust
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

Step 5: Compile to WebAssembly:

To compile your Rust code to WebAssembly, run the following command:
$ cargo build --target wasm32-unknown-unknown

Step 6: Generate JavaScript Bindings with webpack and Node:

Since we have configured the webpack bundler and the wasm-bindgen dependency in package.json, it easy to build and run the project.

you can install the dependencies  and build the project using below command:
$ npm install
$ npm run build
This command generates the wasm javascript bindings in  ./pkg folder.

Generated WASM bindings

Step 7: Use WebAssembly in JavaScript:

Finally, you can use the generated JavaScript bindings to interact with your WebAssembly module. Here's an example:
import("./pkg");
import { add } from "./pkg";
console.log("using webassembly add function: ", add(4, 5));

Step 8: Run the project:

Finally, you can simply run the project using node and webpack as below:
$ npm run serve

WASM function output

Conclusion:

WebAssembly, combined with the power of Rust, opens up new possibilities for high-performance web applications. Its performance, portability, and security benefits make it an excellent choice for developers looking to optimize their web projects. By following the steps outlined in this article, you can seamlessly integrate WebAssembly into your Rust projects and unlock a world of performance gains.

Remember to experiment, explore the vast capabilities of WebAssembly, and leverage the Rust ecosystem to create efficient and robust web applications that run seamlessly across browsers and platforms. 
Happy coding!

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*

Cookies Consent

This website uses cookies to offer you a better Browsing Experience. By using our website, You agree to the use of Cookies

Privacy Policy