[whatwg/fetch] Allow pre-allocating array buffer for .arrayBuffer(), for WebAssembly based parsing with zero copy. (Issue #1615)

We have a binary format that we would like to parse with WebAssembly. But the problem is that we have to copy the file's contents to WebAssembly.Memory before doing anything. Which is slow.

So currently the code would look roughly like this:

```js
const response = await fetch("file.bin");
const fileBytes = new Uint8Array(await response.arrayBuffer());
const wasmMemory = new WebAssembly.Memory({
   initial: pagesCountRequredForWasmModule(fileBytes.length)
});
const wasmMemoryBytes = new Uint8Array(wasmMemory);
wasmMemoryBytes.set(fileBytes);

const {instance} = await WebAssembly.instantiateStreaming(fetch(wasmUrl), { env: { memory: wasmMemory } });
instance.exports.parse();
```

But it could be more like:

```js
const response = await fetch("file.bin");
const wasmMemory = new WebAssembly.Memory({
   initial: pagesCountRequredForWasmModule(response.headers.get('Content-Length'))
});
await response.preAllocatedArrayBuffer(wasmMemory.buffer, offset);

const {instance} = await WebAssembly.instantiateStreaming(fetch(wasmUrl), { env: { memory: wasmMemory } });
instance.exports.parse();
```

The same approach would probably help with WebGPU's mapped memory.


-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/1615
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/fetch/issues/1615@github.com>

Received on Monday, 6 March 2023 12:11:29 UTC