mirror of
https://github.com/vercel-labs/scriptc.git
synced 2026-10-21 05:50:55 +08:00
44 lines
2.2 KiB
JavaScript
44 lines
2.2 KiB
JavaScript
import { StringDecoder } from "node:string_decoder";
|
|
import { Buffer } from "node:buffer";
|
|
|
|
export function report() {
|
|
const bom = Buffer.from([0xef, 0xbb, 0xbf, 0x61]);
|
|
console.log('buffer-bom', JSON.stringify(bom.toString('utf8')), JSON.stringify(bom.toString('utf8', 0, 3)), JSON.stringify(bom.toString('utf8', 3)));
|
|
const inputs = [
|
|
[0xef, 0xbb, 0xbf, 0x61], [0xc2, 0xa2], [0xe2, 0x82, 0xac],
|
|
[0xf0, 0x9f, 0x98, 0x80], [0xe0, 0x80, 0x61], [0xed, 0xa0, 0x80],
|
|
[0xf4, 0x90, 0x80, 0x80], [0xc0, 0xaf], [0xff, 0x80, 0xe2, 0x82],
|
|
[0x61, 0, 0x3d, 0xd8, 0, 0xde, 0x62, 0], [0x3d, 0xd8], [0x61],
|
|
[0x3d, 0xd8, 0, 0xde, 0x3d, 0xd8, 0, 0xde],
|
|
];
|
|
for (const enc of ['utf8', 'utf16le', 'base64', 'base64url', 'latin1', 'ascii', 'hex']) {
|
|
for (const input of inputs) {
|
|
const bytes = Buffer.from(input);
|
|
for (let a = 0; a <= bytes.length; a++) {
|
|
for (let b = a; b <= bytes.length; b++) {
|
|
const d = new StringDecoder(enc);
|
|
console.log(enc, a, b, JSON.stringify([
|
|
d.write(bytes.subarray(0, a)), d.write(bytes.subarray(a, b)),
|
|
d.end(bytes.subarray(b)), d.end(), d.end(Buffer.from('ok')),
|
|
]));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const d = new StringDecoder();
|
|
console.log('strings', JSON.stringify([d.write(Buffer.from([0xe2])), d.write('middle'), d.end('last'), d.end()]));
|
|
console.log('empty', JSON.stringify([d.write(Buffer.from([0xe0])), d.write(Buffer.alloc(0)), d.write(Buffer.from([0x80])), d.end(undefined)]));
|
|
const backing = new Uint8Array([0, 0x68, 0x69, 0]);
|
|
console.log('views', d.end(new DataView(backing.buffer, 1, 2)), d.end(new Uint16Array([0x6968])), d.end(backing.subarray(1, 3)));
|
|
for (const encoding of [undefined, null, '', 'UTF-8', 'UCS-2', 'BINARY', 'nope', false, 0]) {
|
|
try { console.log('encoding', String(encoding), new StringDecoder(encoding).encoding); }
|
|
catch (e) { console.log('encoding-error', e.name, e.code, e.message); }
|
|
}
|
|
for (const input of [undefined, null, 1, {}, [], new ArrayBuffer(2)]) {
|
|
try { d.write(input); console.log('unexpected'); }
|
|
catch (e) { console.log('input-error', e.name, e.code, e.message); }
|
|
}
|
|
d.encoding = 'hex';
|
|
console.log('encoding-property', d.encoding, d.end(Buffer.from('hi')));
|
|
}
|