1- import { typedView } from './array.js'
2- import { assertU8 , E_STRING , E_STRICT_UNICODE } from './fallback/_utils.js'
1+ import { assertU8 , fromBuffer , E_STRING , E_STRICT_UNICODE } from './fallback/_utils.js'
32import { E_STRICT } from './fallback/utf8.js'
43import { isAscii } from 'node:buffer'
54
@@ -16,26 +15,27 @@ try {
1615 // Without ICU, Node.js doesn't support fatal option for utf-8
1716}
1817
19- function encode ( str , loose = false ) {
18+ function encode ( str , loose , format ) {
2019 if ( typeof str !== 'string' ) throw new TypeError ( E_STRING )
2120 const strLength = str . length
2221 if ( strLength === 0 ) return new Uint8Array ( ) // faster than Uint8Array.of
2322 let res
2423 if ( strLength > 0x4_00 && ! isDeno ) {
2524 // Faster for large strings
2625 const byteLength = Buffer . byteLength ( str )
27- res = Buffer . allocUnsafe ( byteLength )
28- const ascii = byteLength === strLength
29- const written = ascii ? res . latin1Write ( str ) : res . utf8Write ( str )
26+ res = format === 'buffer' ? Buffer . allocUnsafe ( byteLength ) : Buffer . allocUnsafeSlow ( byteLength )
27+ const written = byteLength === strLength ? res . latin1Write ( str ) : res . utf8Write ( str )
3028 if ( written !== byteLength ) throw new Error ( 'Failed to write all bytes' ) // safeguard just in case
31- if ( ascii || loose ) return res // no further checks needed
3229 } else {
3330 res = Buffer . from ( str )
34- if ( res . length === strLength || loose ) return res
3531 }
3632
37- if ( ! isWellFormed . call ( str ) ) throw new TypeError ( E_STRICT_UNICODE )
38- return res
33+ // Loose and ascii do not need the check
34+ if ( ! loose && res . length !== strLength && ! isWellFormed . call ( str ) ) {
35+ throw new TypeError ( E_STRICT_UNICODE )
36+ }
37+
38+ return fromBuffer ( res , format )
3939}
4040
4141function decode ( arr , loose = false ) {
@@ -61,7 +61,7 @@ function decode(arr, loose = false) {
6161 return str
6262}
6363
64- export const utf8fromString = ( str , format = 'uint8' ) => typedView ( encode ( str , false ) , format )
65- export const utf8fromStringLoose = ( str , format = 'uint8' ) => typedView ( encode ( str , true ) , format )
64+ export const utf8fromString = ( str , format = 'uint8' ) => encode ( str , false , format )
65+ export const utf8fromStringLoose = ( str , format = 'uint8' ) => encode ( str , true , format )
6666export const utf8toString = ( arr ) => decode ( arr , false )
6767export const utf8toStringLoose = ( arr ) => decode ( arr , true )
0 commit comments