1- import { nativeDecoder , isDeno , isLE } from './fallback/_utils.js'
1+ import { isDeno , isLE } from './fallback/_utils.js'
22import { E_STRICT , E_STRICT_UNICODE } from './fallback/utf16.js'
33
44if ( Buffer . TYPED_ARRAY_SUPPORT ) throw new Error ( 'Unexpected Buffer polyfill' )
55
6- const { isWellFormed } = String . prototype
6+ const { isWellFormed, toWellFormed } = String . prototype
77const 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
5960function decodeDecoder ( input , loose = false , format = 'uint16' ) {
0 commit comments