Book Image

Practical WebAssembly

By : Sendil Kumar Nellaiyapen
Book Image

Practical WebAssembly

By: Sendil Kumar Nellaiyapen

Overview of this book

Rust is an open source language tuned toward safety, concurrency, and performance. WebAssembly brings all the capabilities of the native world into the JavaScript world. Together, Rust and WebAssembly provide a way to create robust and performant web applications. They help make your web applications blazingly fast and have small binaries. Developers working with JavaScript will be able to put their knowledge to work with this practical guide to developing faster and maintainable code. Complete with step-by-step explanations of essential concepts, examples, and self-assessment questions, you’ll begin by exploring WebAssembly, using the various tools provided by the ecosystem, and understanding how to use WebAssembly and JavaScript together to build a high-performing application. You’ll then learn binary code to work with a variety of tools that help you to convert native code into WebAssembly. The book will introduce you to the world of Rust and the ecosystem that makes it easy to build/ship WebAssembly-based applications. By the end of this WebAssembly Rust book, you’ll be able to create and ship your own WebAssembly applications using Rust and JavaScript, understand how to debug, and use the right tools to optimize and deliver high-performing applications.
Table of Contents (15 chapters)
1
Section 1: Introduction to WebAssembly
5
Section 2: WebAssembly Tools
9
Section 3: Rust and WebAssembly

Sharing classes from JavaScript with Rust

Sharing JavaScript classes with Rust is also made easy with #[wasm_bindgen]. Let's look at how to achieve it.

JavaScript classes are objects with some methods. Rust is a strictly typed language. This means the Rust compiler needs to have concrete bindings. Without them, the compiler complains, because it needs to know about the lifetime of an object. We need a way to ensure the compiler has this API available at runtime.

The extern C function block helps out here. The extern C makes a function name available in Rust.

In this example, let's see how to share a class from JavaScript with Rust:

  1. Let's create a new project:
    $ cargo new --lib class_from_js_world
    Created library `class_from_js_world` package
  2. Define the wasm-bindgen dependency for the project. Open the cargo.toml file and add the following content:
    [package]
    name = "class_from_js_world"
    version = "0.1.0"
    authors = ["Sendil...