WebAssembly

[wip]

Para qué programar en JavaScript cuando podemos escribir assembler

¿Qué es WebAssembly?

Formato para la web 🌎

Binario 💯

Bajo nivel 🔬

¿Para qué es WebAssembly?

Cuando algo tiene que ser rápido

Cuando algo ya está hecho 

Cuando algo no lo quiero hacer en JavaScript

en C

¿Dónde está WebAssembly?

¿Cómo es WebAssembly?

WASM, pls

#[no_mangle]
pub fn sum(a: i32, b: i32) -> i32 {
    a + b
}
$ rustc +nightly sum.rs --crate-type=cdylib --target wasm32-unknown-unknown
fetch('./sum.wasm')
  .then(response => response.arrayBuffer())
  .then(bytes => WebAssembly.instantiate(bytes, {}))
  .then(results => {
    console.log(results.instance.exports.sum(1, 2));
  });

Webpack

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.rs$/,
        use: [
          {
            loader: 'wasm-loader'
          },
          {
            loader: 'rust-native-wasm-loader'
          }
        ]
      }
    ]
  }
}

// index.js
import loadWasm from './sum.rs';

loadWasm().then(result =>
  console.log(result.instance.exports.sum(1, 2))
);
// index.js
import { sum } from './sum.rs';
console.log(sum(1, 2));

Parcel

(ArrayBuffer)

const as8 = new Uint8Array(buffer);
as8.length; // 2
as8[0]; // 42
as8[1]; // 1
const as16 = new Uint16Array(buffer);
as16.length; // 1
as16[0]; // 298, o 0b0000000100101010

WASM, moar

const input = storeStringInBuffer('SOMETHING', memory, alloc);
const result = readStringFromBuffer(lowercase(input), memory);
function storeStringInBuffer(str, linearMemory, alloc) {
  const utf8Encoder = new TextEncoder("UTF-8");
  let stringBuffer = utf8Encoder.encode(str);
  let len = stringBuffer.length;
  let ptr = alloc(len+1);

  let memory = new Uint8Array(linearMemory.buffer, ptr);
  for (i = 0; i < len; i++) {
    memory[i] = stringBuffer[i];
  }
  memory[len] = 0;

  return ptr;
}




function readStringFromBuffer(ptr, linearMemory) {
  const u8Buffer = new Uint8Array(linearMemory.buffer, ptr);
  const buffer = Uint8Array.from(collectCString(u8Buffer));
  const utf8Decoder = new TextDecoder('UTF-8');
  return utf8Decoder.decode(buffer);
}

stdweb

#[macro_use]
extern crate stdweb;
extern crate sha1;

use sha1::Sha1;

fn hash(string: String) -> String {
    let mut hasher = Sha1::new();
    hasher.update(string.as_bytes());
    hasher.digest().to_string()
}

fn main() {
    stdweb::initialize();

    js! {
        Module.exports.sha1 = @{hash};
    }
}
#[derive(Serialize)]
struct Person {
    name: String,
    age: i32
}

js_serializable!(Person);

js! {
    var person = @{person};
    console.log(
      person.name +
      " is " +
      person.age +
      " years old."
    );
};

wasmBoy

WebDSP

Links

Hello, Rust!, de Jan-Erik Rediger

Made with Slides.com