diff --git a/NOTICE b/NOTICE index 7eb4e46b07..6b4450d592 100644 --- a/NOTICE +++ b/NOTICE @@ -41,6 +41,7 @@ under the licensing terms detailed in LICENSE: * Ryan Pivovar * Roman F. <70765447+romdotdog@users.noreply.github.com> * Joe Pea +* Felipe Gasper Portions of this software are derived from third-party works licensed under the following terms: diff --git a/lib/loader/index.d.ts b/lib/loader/index.d.ts index 3098da6002..ce2dc2ef3a 100644 --- a/lib/loader/index.d.ts +++ b/lib/loader/index.d.ts @@ -86,6 +86,8 @@ export interface ASUtil { __instanceof(ptr: number, baseId: number): boolean; /** Allocates a new string in the module's memory and returns a reference (pointer) to it. */ __newString(str: string): number; + /** Allocates a new ArrayBuffer in the module's memory and returns a reference (pointer) to it. */ + __newArrayBuffer(buf: ArrayBuffer): number; /** Allocates a new array in the module's memory and returns a reference (pointer) to it. */ __newArray(id: number, values: ArrayLike): number; diff --git a/lib/loader/index.js b/lib/loader/index.js index e7b24f74a9..f0bfca90fa 100644 --- a/lib/loader/index.js +++ b/lib/loader/index.js @@ -150,6 +150,18 @@ function postInstantiate(extendedExports, instance) { extendedExports.__newString = __newString; + /** Allocates a new ArrayBuffer in the module's memory and returns its pointer. */ + function __newArrayBuffer(buf) { + if (buf == null) return 0; + const bufview = new Uint8Array(buf); + const ptr = __new(bufview.length, ARRAYBUFFER_ID); + const U8 = new Uint8Array(memory.buffer); + U8.set(bufview, ptr); + return ptr; + } + + extendedExports.__newArrayBuffer = __newArrayBuffer; + /** Reads a string from the module's memory by its pointer. */ function __getString(ptr) { if (!ptr) return null; diff --git a/lib/loader/tests/index.js b/lib/loader/tests/index.js index aac09f91ae..1f59445aa6 100644 --- a/lib/loader/tests/index.js +++ b/lib/loader/tests/index.js @@ -36,6 +36,15 @@ function test(file) { assert.strictEqual(exports.strlen(ref), str.length); } + // should be able to allocate and work with a new small ArrayBuffer + { + let input = new Uint8Array([1, 2, 3, 4]); + let bufPtr = exports.__newArrayBuffer(input.buffer); + let output = new Uint8Array(exports.__getArrayBuffer(bufPtr)); + + assert.deepStrictEqual(output, input); + } + // should be able to allocate and work with a new big string { let str = `