Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/core/text/text-common.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { TextDecoder, TextEncoder } from './text-common';

describe('TextDecoder', () => {
const decoder = new TextDecoder();

it('decodes an ArrayBuffer', () => {
expect(decoder.decode(new Uint8Array([0x68, 0x69]).buffer)).toBe('hi');
});

it('decodes only the bytes inside a typed array view', () => {
const bytes = new Uint8Array([0x78, 0x78, 0x68, 0x69, 0x78]);
expect(decoder.decode(bytes.subarray(2, 4))).toBe('hi');
});

it('decodes only the bytes inside a DataView', () => {
const bytes = new Uint8Array([0x78, 0x68, 0x69, 0x78]);
expect(decoder.decode(new DataView(bytes.buffer, 1, 2))).toBe('hi');
});

it('round-trips multi-byte characters through TextEncoder', () => {
const encoded = new TextEncoder().encode('héllo ✓');
expect(decoder.decode(encoded)).toBe('héllo ✓');
});

it('rejects values that are not buffers', () => {
expect(() => decoder.decode('abc' as any)).toThrow();
});
});
2 changes: 1 addition & 1 deletion packages/core/text/text-common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class TextDecoder {
if (Object_prototype_toString.call(buffer) !== ArrayBufferString) {
throw Error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
const inputAs8 = new Uint8Array(buffer);
const inputAs8 = ArrayBuffer.isView(input) ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) : new Uint8Array(buffer);
let resultingString = '';
for (let index = 0, len = inputAs8.length | 0; index < len; index = (index + 32768) | 0) {
resultingString += String.fromCharCode.apply(0, inputAs8.slice(index, (index + 32768) | 0));
Expand Down
Loading