Skip to content

Commit

Permalink
feat: add __newArrayBuffer() to the loader (AssemblyScript#1965)
Browse files Browse the repository at this point in the history
  • Loading branch information
FGasper authored Jul 23, 2021
1 parent 3a33a25 commit 5df7318
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ under the licensing terms detailed in LICENSE:
* Ryan Pivovar <ryanpivovar@gmail.com>
* Roman F. <70765447+romdotdog@users.noreply.github.com>
* Joe Pea <trusktr@gmail.com>
* Felipe Gasper <FGasper@users.noreply.github.com>

Portions of this software are derived from third-party works licensed under
the following terms:
Expand Down
2 changes: 2 additions & 0 deletions lib/loader/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>): number;

Expand Down
12 changes: 12 additions & 0 deletions lib/loader/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions lib/loader/tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
Expand Down

0 comments on commit 5df7318

Please sign in to comment.