Public
Edited
Dec 5, 2022
4 stars
Insert cell
Insert cell
leb = require("https://bundle.run/@webassemblyjs/leb128@1.9.0/lib/index.js")
Insert cell
leb.encodeI32(-64)
Insert cell

- LEB encoding
- memorize 1, 0, 2
Insert cell
leb.encodeI32(12)
Insert cell
reference: https://github.com/WebAssembly/design/blob/main/BinaryEncoding.md
reference: https://observablehq.com/@ballingt/advent-of-wasm-day-1?collection=@ballingt/advent-of-wasm
Insert cell
Insert cell
part1Code = (mass) => [
0x00, // there are no local variables (this is where we'd declare them if there were)
0x41, // constant integer
...leb.encodeI32(mass),
0x41, // constant integer
...leb.encodeI32(3),
0x6d, // division
0x41, // constant integer
...leb.encodeI32(2),
0x6b, // subtraction
0x0b // END opcode
]
Insert cell
Insert cell
[0x00, 0x61, 0x73, 0x6d].map((x) => [x, String.fromCharCode(x)])
Insert cell
String.fromCharCode(65 + 0x20)
Insert cell
typeSection = [0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f]
Insert cell
buildModule = (code) => {
return [
...[0x00, 0x61, 0x73, 0x6d], // magic number
...[0x01, 0x00, 0x00, 0x00], // version

0x01, // Type section
0x05, // this section has 5 more bytes
0x01, // There is 1 type
0x60, // it's a function
0x00, // it takes zero arguments
0x01, // it has one return value (I think that's what this means?)
0x7f, // which is an int

0x03, // Func section
0x02, // this section has 2 more bytes
0x01, // there's one function
0x00, // the first function uses type signature at index 0

0x07, // Export section
0x05, // this section has 5 more bytes
0x01, // there's one export
0x01, // the name of the function has one byte
"x".codePointAt(0), // let's call our exported function "x"
0x00, // it's a function
0x00, // it's the function at index 0

0x0a, // Code section
code.length + 2, // there are code.length + 2 more bytes in this section
0x01, // there's one function in here
code.length, // this function is code.length bytes long
...code
];
}
Insert cell
async function runModule(mass) {
const linear = buildModule(mass);
const linearBuffer = new Uint8Array(linear);
const module = await WebAssembly.compile(linearBuffer);
const instance = await WebAssembly.instantiate(module);
return await instance.exports.x();
}
Insert cell
runModule(part1Code(1123))
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more