Skip to content

Commit 75f9dea

Browse files
committed
perf: use toWellFormed on Node.js utf16
1 parent 62d6c16 commit 75f9dea

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

utf16.node.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import { nativeDecoder, isDeno, isLE } from './fallback/_utils.js'
1+
import { isDeno, isLE } from './fallback/_utils.js'
22
import { E_STRICT, E_STRICT_UNICODE } from './fallback/utf16.js'
33

44
if (Buffer.TYPED_ARRAY_SUPPORT) throw new Error('Unexpected Buffer polyfill')
55

6-
const { isWellFormed } = String.prototype
6+
const { isWellFormed, toWellFormed } = String.prototype
77
const to8 = (a) => new Uint8Array(a.buffer, a.byteOffset, a.byteLength)
88

99
// Unlike utf8, operates on Uint16Arrays by default
@@ -14,9 +14,10 @@ function encode(str, loose = false, format = 'uint16') {
1414
throw new TypeError('Unknown format')
1515
}
1616

17-
if (!isWellFormed.call(str)) {
18-
if (!loose) throw new TypeError(E_STRICT_UNICODE)
19-
str = nativeDecoder.decode(Buffer.from(str)) // well, let's fix up (Buffer doesn't do this with utf16 encoding)
17+
if (loose) {
18+
str = toWellFormed.call(str) // Buffer doesn't do this with utf16 encoding
19+
} else if (!isWellFormed.call(str)) {
20+
throw new TypeError(E_STRICT_UNICODE)
2021
}
2122

2223
const ble = Buffer.from(str, 'utf-16le')
@@ -51,9 +52,9 @@ function decodeNode(input, loose = false, format = 'uint16') {
5152
}
5253

5354
const str = ble.ucs2Slice(0, ble.byteLength)
55+
if (loose) return toWellFormed.call(str)
5456
if (isWellFormed.call(str)) return str
55-
if (!loose) throw new TypeError(E_STRICT)
56-
return nativeDecoder.decode(Buffer.from(str)) // fixup (see above)
57+
throw new TypeError(E_STRICT)
5758
}
5859

5960
function decodeDecoder(input, loose = false, format = 'uint16') {

0 commit comments

Comments
 (0)