Files
scriptc/tests/corpus/text-decoder-undefined-input.ts
T
Chris Tate 5f602ff3b8 Decode asserted optional typed arrays other than Uint8Array
`decoder.decode(view!)` on a `Uint16Array | undefined` (or another typed
array that may be undefined) was refused with SC2020: the assertion keeps
the undefined arm for decode, and the decode input only read the
undefined arm of `Uint8Array | undefined`. The undefined arm of any typed
array that may be undefined now reads as an empty array of the same type,
so a defined input decodes its bytes and an undefined one decodes no
bytes, as in Node.
2026-10-24 21:16:59 -05:00

39 lines
1.8 KiB
TypeScript

// TextDecoder.decode(undefined) decodes no bytes, as decode() does: it
// returns "" and, after streamed input, flushes the pending bytes.
const decoder = new TextDecoder();
const encoded = new TextEncoder().encode("bytes");
const inputs = new Map<string, Uint8Array | undefined>([
["present", encoded],
["absent", undefined],
]);
console.log(JSON.stringify(decoder.decode(undefined)));
console.log(JSON.stringify(decoder.decode(inputs.get("present"))), JSON.stringify(decoder.decode(inputs.get("absent"))));
console.log(JSON.stringify(decoder.decode(inputs.get("absent")!)), JSON.stringify(decoder.decode(inputs.get("missing")!)));
console.log(JSON.stringify(new TextDecoder("utf-8").decode(undefined)));
console.log(JSON.stringify(new TextDecoder("utf-8").decode(inputs.get("absent"))));
let calls = 0;
function nothing(): undefined {
calls++;
return undefined;
}
console.log(JSON.stringify(decoder.decode(nothing())), calls);
interface Chunk {
done: boolean;
value?: Uint8Array;
}
const chunks: Chunk[] = [{ done: false, value: new Uint8Array([0xe2, 0x82]) }, { done: true }];
const streaming = new TextDecoder();
let text = "";
for (const chunk of chunks) text += streaming.decode(chunk.value, { stream: !chunk.done });
console.log(JSON.stringify(text), text.length);
// Other typed arrays decode their bytes, with or without the assertion.
const wide = new Map<string, Uint16Array | undefined>([["present", new Uint16Array([0x6968])]]);
const asserted = wide.get("present")!;
console.log(JSON.stringify(decoder.decode(asserted)), JSON.stringify(decoder.decode(wide.get("present")!)));
console.log(JSON.stringify(decoder.decode(wide.get("present"))), JSON.stringify(decoder.decode(wide.get("absent"))));
console.log(JSON.stringify(new TextDecoder("utf-8").decode(wide.get("absent")!)));