Skip to content

Commit

Permalink
Use DataView to access WebAssembly memory (#37)
Browse files Browse the repository at this point in the history
Accompanying mdn/content#33960

---------

Co-authored-by: Hamish Willee <[email protected]>
  • Loading branch information
Josh-Cena and hamishwillee authored Jun 7, 2024
1 parent cf86061 commit 1b53615
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
12 changes: 6 additions & 6 deletions js-api-examples/memory.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
<script>
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100
maximum: 100,
});

WebAssembly.instantiateStreaming(fetch("memory.wasm"), { js: { mem: memory } })
.then(obj => {
const summands = new Uint32Array(memory.buffer);
WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((obj) => {
const summands = new DataView(memory.buffer);
for (let i = 0; i < 10; i++) {
summands[i] = i;
summands.setUint32(i * 4, i, true); // WebAssembly is little endian
}
const sum = obj.instance.exports.accumulate(0, 10);
console.log(sum);
Expand Down
9 changes: 5 additions & 4 deletions understanding-text-format/memory-export.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
<script>
WebAssembly.instantiateStreaming(fetch("memory-export.wasm")).then(
(object) => {
const values = new Uint32Array(object.instance.exports.memory.buffer);
const values = new DataView(object.instance.exports.memory.buffer);
let sum = 0;
// views only the first ten elements of the Wasm memory
const summands = values.subarray(0, 10);
// sums the first ten elements
const sum = summands.reduce((sum, summand) => sum + summand);
for (let i = 0 ; i < 10; i++) {
sum += values.getUint32(i * 4, true);
}
console.log(sum);
}
);
Expand Down

0 comments on commit 1b53615

Please sign in to comment.