@@ -61,6 +61,32 @@ export function createSinglebyteDecoder(encoding, loose = false) {
6161
6262const NON_LATIN = / [ ^ \x00 - \xFF ] / // eslint-disable-line no-control-regex
6363
64+ function encode ( s , m ) {
65+ const len = s . length
66+ let i = 0
67+ const b = Buffer . from ( s , 'utf-16le' ) // aligned
68+ if ( ! isLE ) b . swap16 ( )
69+ const x = new Uint16Array ( b . buffer , b . byteOffset , b . byteLength / 2 )
70+ for ( const len3 = len - 3 ; i < len3 ; i += 4 ) {
71+ const x0 = x [ i ] , x1 = x [ i + 1 ] , x2 = x [ i + 2 ] , x3 = x [ i + 3 ] // prettier-ignore
72+ const c0 = m [ x0 ] , c1 = m [ x1 ] , c2 = m [ x2 ] , c3 = m [ x3 ] // prettier-ignore
73+ if ( ! ( c0 && c1 && c2 && c3 ) && ( ( ! c0 && x0 ) || ( ! c1 && x1 ) || ( ! c2 && x2 ) || ( ! c3 && x3 ) ) ) return null // prettier-ignore
74+ x [ i ] = c0
75+ x [ i + 1 ] = c1
76+ x [ i + 2 ] = c2
77+ x [ i + 3 ] = c3
78+ }
79+
80+ for ( ; i < len ; i ++ ) {
81+ const x0 = x [ i ]
82+ const c0 = m [ x0 ]
83+ if ( ! c0 && x0 ) return null
84+ x [ i ] = c0
85+ }
86+
87+ return new Uint8Array ( x )
88+ }
89+
6490export function createSinglebyteEncoder ( encoding , { mode = 'fatal' } = { } ) {
6591 // TODO: replacement, truncate (replacement will need varying length)
6692 if ( mode !== 'fatal' ) throw new Error ( 'Unsupported mode' )
@@ -82,32 +108,9 @@ export function createSinglebyteEncoder(encoding, { mode = 'fatal' } = {}) {
82108 if ( b . length === s . length ) return new Uint8Array ( b . buffer , b . byteOffset , b . byteLength )
83109 }
84110
85- const len = s . length
86- let i = 0
87- const b = Buffer . from ( s , 'utf-16le' ) // aligned
88- if ( ! isLE ) b . swap16 ( )
89- const x = new Uint16Array ( b . buffer , b . byteOffset , b . byteLength / 2 )
90- for ( const len3 = len - 3 ; i < len3 ; i += 4 ) {
91- const x0 = x [ i ] , x1 = x [ i + 1 ] , x2 = x [ i + 2 ] , x3 = x [ i + 3 ] // prettier-ignore
92- const c0 = m [ x0 ] , c1 = m [ x1 ] , c2 = m [ x2 ] , c3 = m [ x3 ] // prettier-ignore
93- if ( ! ( c0 && c1 && c2 && c3 ) && ( ( ! c0 && x0 ) || ( ! c1 && x1 ) || ( ! c2 && x2 ) || ( ! c3 && x3 ) ) ) {
94- throw new TypeError ( E_STRICT )
95- }
96-
97- x [ i ] = c0
98- x [ i + 1 ] = c1
99- x [ i + 2 ] = c2
100- x [ i + 3 ] = c3
101- }
102-
103- for ( ; i < len ; i ++ ) {
104- const x0 = x [ i ]
105- const c0 = m [ x0 ]
106- if ( ! c0 && x0 ) throw new TypeError ( E_STRICT )
107- x [ i ] = c0
108- }
109-
110- return new Uint8Array ( x )
111+ const res = encode ( s , m )
112+ if ( ! res ) throw new TypeError ( E_STRICT )
113+ return res
111114 }
112115}
113116
0 commit comments