Skip to content

Commit 5df7318

Browse files
authored
feat: add __newArrayBuffer() to the loader (#1965)
1 parent 3a33a25 commit 5df7318

File tree

4 files changed

+24
-0
lines changed

4 files changed

+24
-0
lines changed

NOTICE

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ under the licensing terms detailed in LICENSE:
4141
* Ryan Pivovar <ryanpivovar@gmail.com>
4242
* Roman F. <70765447+romdotdog@users.noreply.github.com>
4343
* Joe Pea <trusktr@gmail.com>
44+
* Felipe Gasper <FGasper@users.noreply.github.com>
4445

4546
Portions of this software are derived from third-party works licensed under
4647
the following terms:

lib/loader/index.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ export interface ASUtil {
8686
__instanceof(ptr: number, baseId: number): boolean;
8787
/** Allocates a new string in the module's memory and returns a reference (pointer) to it. */
8888
__newString(str: string): number;
89+
/** Allocates a new ArrayBuffer in the module's memory and returns a reference (pointer) to it. */
90+
__newArrayBuffer(buf: ArrayBuffer): number;
8991
/** Allocates a new array in the module's memory and returns a reference (pointer) to it. */
9092
__newArray(id: number, values: ArrayLike<number>): number;
9193

lib/loader/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,18 @@ function postInstantiate(extendedExports, instance) {
150150

151151
extendedExports.__newString = __newString;
152152

153+
/** Allocates a new ArrayBuffer in the module's memory and returns its pointer. */
154+
function __newArrayBuffer(buf) {
155+
if (buf == null) return 0;
156+
const bufview = new Uint8Array(buf);
157+
const ptr = __new(bufview.length, ARRAYBUFFER_ID);
158+
const U8 = new Uint8Array(memory.buffer);
159+
U8.set(bufview, ptr);
160+
return ptr;
161+
}
162+
163+
extendedExports.__newArrayBuffer = __newArrayBuffer;
164+
153165
/** Reads a string from the module's memory by its pointer. */
154166
function __getString(ptr) {
155167
if (!ptr) return null;

lib/loader/tests/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ function test(file) {
3636
assert.strictEqual(exports.strlen(ref), str.length);
3737
}
3838

39+
// should be able to allocate and work with a new small ArrayBuffer
40+
{
41+
let input = new Uint8Array([1, 2, 3, 4]);
42+
let bufPtr = exports.__newArrayBuffer(input.buffer);
43+
let output = new Uint8Array(exports.__getArrayBuffer(bufPtr));
44+
45+
assert.deepStrictEqual(output, input);
46+
}
47+
3948
// should be able to allocate and work with a new big string
4049
{
4150
let str = `

0 commit comments

Comments
 (0)