Skip to content

Commit 24c8311

Browse files
authored
fix(core): TextDecoder decodes only the bytes of a typed array view (#11578)
Closes #9941
1 parent 16d8ef1 commit 24c8311

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { describe, it, expect } from 'vitest';
2+
import { TextDecoder, TextEncoder } from './text-common';
3+
4+
describe('TextDecoder', () => {
5+
const decoder = new TextDecoder();
6+
7+
it('decodes an ArrayBuffer', () => {
8+
expect(decoder.decode(new Uint8Array([0x68, 0x69]).buffer)).toBe('hi');
9+
});
10+
11+
it('decodes only the bytes inside a typed array view', () => {
12+
const bytes = new Uint8Array([0x78, 0x78, 0x68, 0x69, 0x78]);
13+
expect(decoder.decode(bytes.subarray(2, 4))).toBe('hi');
14+
});
15+
16+
it('decodes only the bytes inside a DataView', () => {
17+
const bytes = new Uint8Array([0x78, 0x68, 0x69, 0x78]);
18+
expect(decoder.decode(new DataView(bytes.buffer, 1, 2))).toBe('hi');
19+
});
20+
21+
it('round-trips multi-byte characters through TextEncoder', () => {
22+
const encoded = new TextEncoder().encode('héllo ✓');
23+
expect(decoder.decode(encoded)).toBe('héllo ✓');
24+
});
25+
26+
it('rejects values that are not buffers', () => {
27+
expect(() => decoder.decode('abc' as any)).toThrow();
28+
});
29+
});

‎packages/core/text/text-common.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export class TextDecoder {
7171
if (Object_prototype_toString.call(buffer) !== ArrayBufferString) {
7272
throw Error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
7373
}
74-
const inputAs8 = new Uint8Array(buffer);
74+
const inputAs8 = ArrayBuffer.isView(input) ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) : new Uint8Array(buffer);
7575
let resultingString = '';
7676
for (let index = 0, len = inputAs8.length | 0; index < len; index = (index + 32768) | 0) {
7777
resultingString += String.fromCharCode.apply(0, inputAs8.slice(index, (index + 32768) | 0));

0 commit comments

Comments
 (0)