@@ -28,27 +28,22 @@ const { E_STRICT } = js
2828
2929// Unlike utf8, operates on Uint16Arrays by default
3030
31- const to8 = ( a ) => new Uint8Array ( a . buffer , a . byteOffset , a . byteLength )
32-
3331function encode ( str , loose = false , format = 'uint16' ) {
3432 if ( typeof str !== 'string' ) throw new TypeError ( E_STRING )
3533 if ( format !== 'uint16' && format !== 'uint8-le' && format !== 'uint8-be' ) {
3634 throw new TypeError ( 'Unknown format' )
3735 }
3836
39- const shouldSwap = ( isLE && format === 'uint8-be' ) || ( ! isLE && format === 'uint8-le' )
40-
4137 // On v8 and SpiderMonkey, check via isWellFormed is faster than js
4238 // On JSC, check during loop is faster than isWellFormed
4339 // If isWellFormed is available, we skip check during decoding and recheck after
4440 // If isWellFormed is unavailable, we check in js during decoding
4541 if ( ! loose && isWellFormed && ! isWellFormed . call ( str ) ) throw new TypeError ( E_STRICT_UNICODE )
42+ const shouldSwap = ( isLE && format === 'uint8-be' ) || ( ! isLE && format === 'uint8-le' )
4643 const u16 = js . encode ( str , loose , ! loose && isWellFormed , shouldSwap )
4744
48- if ( format === 'uint8-le' || format === 'uint8-be' ) return to8 ( u16 ) // Already swapped
49- if ( format === 'uint16' ) return u16
50- /* c8 ignore next */
51- throw new Error ( 'Unreachable' )
45+ // Bytes are already swapped and format is already checked, we need to just cast the view
46+ return format === 'uint16' ? u16 : new Uint8Array ( u16 . buffer , u16 . byteOffset , u16 . byteLength )
5247}
5348
5449function decode ( input , loose = false , format = 'uint16' ) {
0 commit comments