Skip to content

Commit deb7344

Browse files
committed
feat: utf16fromString never returns pooled TypedArrays
1 parent 2ef8f54 commit deb7344

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

tests/utf16.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,3 +392,25 @@ test('large strings', { skip: skipLarge }, (t) => {
392392
t.assert.strictEqual(s, lib.utf16toString(lib.utf16fromString(s)))
393393
}
394394
})
395+
396+
test('utf16fromString / utf16fromStringLoose returns non-pooled TypedArray instances', (t) => {
397+
for (let i = 0; i < 256; i++) {
398+
t.assert.strictEqual(utf16.utf16fromString('a'.repeat(128)).buffer.byteLength, 128 * 2)
399+
t.assert.strictEqual(utf16.utf16fromStringLoose('a'.repeat(128)).buffer.byteLength, 128 * 2)
400+
}
401+
402+
for (let i = 0; i < 256; i++) {
403+
t.assert.strictEqual(utf16.utf16fromString('a'.repeat(64)).buffer.byteLength, 64 * 2)
404+
t.assert.strictEqual(utf16.utf16fromStringLoose('a'.repeat(64)).buffer.byteLength, 64 * 2)
405+
}
406+
407+
for (let i = 0; i < 512; i++) {
408+
t.assert.strictEqual(utf16.utf16fromString('a'.repeat(32)).buffer.byteLength, 32 * 2)
409+
t.assert.strictEqual(utf16.utf16fromStringLoose('a'.repeat(32)).buffer.byteLength, 32 * 2)
410+
}
411+
412+
for (let i = 0; i < 512; i++) {
413+
t.assert.strictEqual(utf16.utf16fromString('').buffer.byteLength, 0)
414+
t.assert.strictEqual(utf16.utf16fromStringLoose('').buffer.byteLength, 0)
415+
}
416+
})

utf16.node.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ function encode(str, loose = false, format = 'uint16') {
2121
throw new TypeError(E_STRICT_UNICODE)
2222
}
2323

24-
const ble = Buffer.from(str, 'utf-16le')
24+
let ble = Buffer.allocUnsafeSlow(str.length * 2) // non-pooled
25+
ble.ucs2Write(str)
2526

2627
if (format === 'uint8-le') return to8(ble)
2728
if (format === 'uint8-be') return to8(ble.swap16())

0 commit comments

Comments
 (0)