Skip to content

Commit fce1640

Browse files
committed
Fix fixUint8Array for cases where view is not the whole buffer
1 parent 7e4d6cb commit fce1640

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

packages/encoding/src/uint8array.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,34 @@ describe("fixUint8Array", () => {
99
expect(fixed.buffer).toBe(input.buffer); // no copy must be performed in this case
1010
});
1111

12+
it("works for Uint8Array<ArrayBuffer> where data is not using all of the buffer", () => {
13+
const buffer = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a]).buffer;
14+
expect(buffer.byteLength).toEqual(11);
15+
const original = new Uint8Array(buffer, 1, 5);
16+
17+
const fixed = fixUint8Array(original);
18+
expect(fixed.length).toEqual(5);
19+
expect(fixed).toEqual(new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05]));
20+
expect(fixed.buffer).toBe(buffer); // no copy must be performed in this case
21+
});
22+
1223
it("works for Uint8Array<SharedArrayBuffer>", () => {
1324
const sharedBuffer = new SharedArrayBuffer(8);
1425
const input: Uint8Array<SharedArrayBuffer> = new Uint8Array(sharedBuffer);
1526
const fixed = fixUint8Array(input);
1627
expect(fixed).toEqual(input);
1728
expect(fixed.buffer).toBeInstanceOf(ArrayBuffer);
1829
});
30+
31+
it("works for Uint8Array<SharedArrayBuffer> where data is not using all of the buffer", () => {
32+
const sharedBuffer = new SharedArrayBuffer(8);
33+
const input: Uint8Array<SharedArrayBuffer> = new Uint8Array(sharedBuffer, 0, 3);
34+
input[0] = 0xaa;
35+
input[1] = 0xbb;
36+
input[2] = 0xcc;
37+
const fixed = fixUint8Array(input);
38+
expect(fixed.buffer).toBeInstanceOf(ArrayBuffer);
39+
expect(fixed.length).toEqual(3);
40+
expect(fixed).toEqual(new Uint8Array([0xaa, 0xbb, 0xcc]));
41+
});
1942
});

packages/encoding/src/uint8array.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
export function fixUint8Array<T extends ArrayBufferLike>(source: Uint8Array<T>): Uint8Array<ArrayBuffer> {
88
const buffer = source.buffer;
99
if (buffer instanceof ArrayBuffer) {
10-
return new Uint8Array(buffer); // new instance just to make TS happy without unsafe cast
10+
return new Uint8Array(buffer, source.byteOffset, source.length); // new instance just to make TS happy without unsafe cast
1111
}
1212

13-
const copy = new ArrayBuffer(buffer.byteLength);
14-
new Uint8Array(copy).set(new Uint8Array(buffer));
15-
return new Uint8Array(copy);
13+
const copy = new ArrayBuffer(source.byteLength); // allocate memory
14+
const out = new Uint8Array(copy);
15+
out.set(source); // copy data
16+
return out;
1617
}

0 commit comments

Comments
 (0)