DEV Community

Tawhid
Tawhid

Posted on

Rust and web assembly Rust Tutorial:3

what is Rust?
Rust is a memeory safe compiled language,
It is used where memory is critical,where high level languages use garbage collector and low level languages give you pointers and allocations to shoot yourself
Rust takes a different approach.

What is WebAssembly?
WebAssembly (wasm) is a simple machine model and executable format with an extensive specification. It is designed to be portable, compact, and execute at or near native speeds.

As a programming language, WebAssembly is comprised of two formats that represent the same structures, albeit in different ways:

The .wat text format (called wat for "WebAssembly Text") uses S-expressions, and bears some resemblance to the Lisp family of languages like Scheme and Clojure.

The .wasm binary format is lower-level and intended for consumption directly by wasm virtual machines. It is conceptually similar to ELF and Mach-O.

Why Rust and WebAssembly?
Low-Level Control with High-Level Ergonomics
JavaScript Web applications struggle to attain and retain reliable performance. JavaScript's dynamic type system and garbage collection pauses don't help. Seemingly small code changes can result in drastic performance regressions if you accidentally wander off the JIT's happy path.

Rust gives programmers low-level control and reliable performance. It is free from the non-deterministic garbage collection pauses that plague JavaScript. Programmers have control over indirection, monomorphization, and memory layout.

Small .wasm Sizes
Code size is incredibly important since the .wasm must be downloaded over the network. Rust lacks a runtime, enabling small .wasm sizes because there is no extra bloat included like a garbage collector. You only pay (in code size) for the functions you actually use.

Do Not Rewrite Everything
Existing code bases don't need to be thrown away. You can start by porting your most performance-sensitive JavaScript functions to Rust to gain immediate benefits. And you can even stop there if you want to.

Plays Well With Others
Rust and WebAssembly integrates with existing JavaScript tooling. It supports ECMAScript modules and you can continue using the tooling you already love, like npm and Webpack.

Setup
This section describes how to set up the toolchain for compiling Rust programs to WebAssembly and integrate them into JavaScript.

The Rust Toolchain
You will need the standard Rust toolchain, including rustup, rustc, and cargo.

The Rust and WebAssembly experience is riding the Rust release trains to stable! That means we don't require any experimental feature flags. However, we do require Rust 1.30 or newer.

wasm-pack
wasm-pack is your one-stop shop for building, testing, and publishing Rust-generated WebAssembly.

Get wasm pack here!

cargo-generate
cargo-generate helps you get up and running quickly with a new Rust project by leveraging a pre-existing git repository as a template.

Install cargo-generate with this command:

cargo install cargo-generate

npm
npm is a package manager for JavaScript. We will use it to install and run a JavaScript bundler and development server. At the end of the tutorial, we will publish our compiled .wasm to the npm registry.

Follow these instructions to install npm.

If you already have npm installed, make sure it is up to date with this command:

npm install npm@latest -g

After you generated a package let's see the contents and what it means.
Let's take a look at a couple of these files in detail.

Project-name/Cargo.toml
The Cargo.toml file specifies dependencies and metadata for cargo, Rust's package manager and build tool. This one comes pre-configured with a wasm-bindgen dependency, a few optional dependencies we will dig into later, and the crate-type properly initialized for generating .wasm libraries.

Project-Name/src/lib.rs
The src/lib.rs file is the root of the Rust crate that we are compiling to WebAssembly. It uses wasm-bindgen to interface with JavaScript.

Project-Name/src/utils.rs
The src/utils.rs module provides common utilities to make working with Rust compiled to WebAssembly easier.

Build the Project
We use wasm-pack to orchestrate the following build steps:

Ensure that we have Rust 1.30 or newer and the wasm32-unknown-unknown target installed via rustup,
Compile our Rust sources into a WebAssembly .wasm binary via cargo,
Use wasm-bindgen to generate the JavaScript API for using our Rust-generated WebAssembly.
To do all of that, run this command inside the project directory:

wasm-pack build

When the build has completed, we can find its artifacts in the pkg directory, and it should have these contents:

pkg/
├── package.json
├── README.md
├── Package-Name.wasm
├── Package-Name.d.ts
└── Package-Name.js

Putting it into a Web Page
To take our wasm-game-of-life package and use it in a Web page, we use the create-wasm-app JavaScript project template.

Run this command within the Project directory:

npm init wasm-app www

Project-Name/www subdirectory contains:

Project-Name/www/
├── bootstrap.js
├── index.html
├── index.js
├── LICENSE-APACHE
├── LICENSE-MIT
├── package.json
├── README.md
└── webpack.config.js

/www/package.json
This package.json comes pre-configured with webpack and webpack-dev-server dependencies, as well as a dependency on hello-wasm-pack, which is a version of the initial wasm-pack-template package that has been published to npm.

/www/webpack.config.js
This file configures webpack and its local development server. It comes pre-configured, and you shouldn't have to tweak this at all to get webpack and its local development server working.

/www/index.html
This is the root HTML file for the Web page. It doesn't do much other than load bootstrap.js, which is a very thin wrapper around index.js.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello wasm-pack!</title>
</head>
<body>
<script src="./bootstrap.js"></script>
</body>
</html>

/www/index.js
The index.js is the main entry point for our Web page's JavaScript. It imports the hello-wasm-pack npm package, which contains the default wasm-pack-template's compiled WebAssembly and JavaScript glue, then it calls hello-wasm-pack's greet function.

import * as wasm from "hello-wasm-pack";

wasm.greet();

so I guess that's enough for today
If you liked it give it a heart It will encourage me and if you think something is wrong please let me know below in the comments.If you are new here make sure to check out other rust tutorials.

Oldest comments (0)