1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 05:57:44 +00:00

LibJS: Use ArrayBuffer for typed array data

This is how the spec describes it, and it allows sharing data between
multiple typed arrays.
Typed arrays now support constructing from an existing ArrayBuffer,
and has been prepared for constructing from another typed array or
iterator as well.
This commit is contained in:
Linus Groh 2020-12-02 21:55:20 +00:00 committed by Andreas Kling
parent 32571dfa53
commit cc5be96724
5 changed files with 235 additions and 81 deletions

View file

@ -45,6 +45,70 @@ test("typed arrays inherit from TypedArray", () => {
});
});
test("typed array can share the same ArrayBuffer", () => {
const arrayBuffer = new ArrayBuffer(2);
const uint8Array = new Uint8Array(arrayBuffer);
const uint16Array = new Uint16Array(arrayBuffer);
expect(uint8Array[0]).toBe(0);
expect(uint8Array[1]).toBe(0);
expect(uint16Array[0]).toBe(0);
expect(uint16Array[1]).toBeUndefined();
uint16Array[0] = 54321;
expect(uint8Array[0]).toBe(0x31);
expect(uint8Array[1]).toBe(0xd4);
expect(uint16Array[0]).toBe(54321);
expect(uint16Array[1]).toBeUndefined();
});
test("typed array from ArrayBuffer with custom length and offset", () => {
const arrayBuffer = new ArrayBuffer(10);
const uint8ArrayAll = new Uint8Array(arrayBuffer);
const uint16ArrayPartial = new Uint16Array(arrayBuffer, 2, 4);
// Affects two bytes of the buffer, beginning at offset
uint16ArrayPartial[0] = 52651
// Out of relative bounds, doesn't affect buffer
uint16ArrayPartial[4] = 123
expect(uint8ArrayAll[0]).toBe(0);
expect(uint8ArrayAll[1]).toBe(0);
expect(uint8ArrayAll[2]).toBe(0xab);
expect(uint8ArrayAll[3]).toBe(0xcd);
expect(uint8ArrayAll[5]).toBe(0);
expect(uint8ArrayAll[6]).toBe(0);
expect(uint8ArrayAll[7]).toBe(0);
expect(uint8ArrayAll[8]).toBe(0);
expect(uint8ArrayAll[9]).toBe(0);
});
test("typed array from ArrayBuffer errors", () => {
expect(() => {
new Uint16Array(new ArrayBuffer(1));
}).toThrowWithMessage(
RangeError,
"Invalid buffer length for Uint16Array: must be a multiple of 2, got 1"
);
expect(() => {
new Uint16Array(new ArrayBuffer(), 1);
}).toThrowWithMessage(
RangeError,
"Invalid byte offset for Uint16Array: must be a multiple of 2, got 1"
);
expect(() => {
new Uint16Array(new ArrayBuffer(), 2);
}).toThrowWithMessage(
RangeError,
"Typed array byte offset 2 is out of range for buffer with length 0"
);
expect(() => {
new Uint16Array(new ArrayBuffer(7), 2, 3);
}).toThrowWithMessage(
RangeError,
"Typed array range 2:8 is out of range for buffer with length 7"
);
});
test("TypedArray is not exposed on the global object", () => {
expect(globalThis.TypedArray).toBeUndefined();
});