インラインでWebAssemblyが使えるinline-wastを試す
WebAssemblyを使う場合、wasmという拡張子のファイルをサーバ上に配置して、それを読み込むのが一般的です。しかし何もファイルが必ず必要な訳ではありません。
そんな試みで作られているのがinline-wastです。WebAssemblyのテキスト版であるWASTを使ってインラインでWebAssemblyを使えるようにするソフトウェアです。
inline-wastの使い方
コード例です。i32.constなどがWASTにあたるコードです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {wastInstructions} = require('inline-wast/lib/interpreter'); | |
function add(a, b) { | |
const fn = wastInstructions` | |
(i32.const ${a}) | |
(i32.const ${b}) | |
(i32.add) | |
`; | |
return fn(); | |
} | |
console.log(add(3, 1)); // 4 |
ここで定義されるwastInstructionsの実行結果として返ってくる関数はWebAssemblyなので高速に処理されるものです。興味深いのは文字列で関数を生成しているので、動的にその内容を変更できるということです。処理が長くなりそうな場合、動的にWebAssembly化することで高速化させられる可能性があります。
WebAssemblyはバイナリとテキスト版があります。テキスト版は慣れれば読めないことはない文字列です。面白い仕組みです。
コメントは受け付けていません。