@@ -136,39 +136,12 @@ class Bytes {
136136 throw Error . OutsideBounds ;
137137 if (encoding == null )
138138 encoding = UTF8 ;
139- var s = " " ;
140- var b = b ;
141- var i = pos ;
142- var max = pos + len ;
143- switch (encoding ) {
144- case UTF8 :
145- var debug = pos > 0 ;
146- // utf8-decode and utf16-encode
147- while (i < max ) {
148- var c = b [i ++ ];
149- if (c < 0x80 ) {
150- if (c == 0 )
151- break ;
152- s + = String .fromCharCode (c );
153- } else if (c < 0xE0 )
154- s + = String .fromCharCode (((c & 0x3F ) << 6 ) | (b [i ++ ] & 0x7F ));
155- else if (c < 0xF0 ) {
156- var c2 = b [i ++ ];
157- s + = String .fromCharCode (((c & 0x1F ) << 12 ) | ((c2 & 0x7F ) << 6 ) | (b [i ++ ] & 0x7F ));
158- } else {
159- var c2 = b [i ++ ];
160- var c3 = b [i ++ ];
161- var u = ((c & 0x0F ) << 18 ) | ((c2 & 0x7F ) << 12 ) | ((c3 & 0x7F ) << 6 ) | (b [i ++ ] & 0x7F );
162- s + = String .fromCharCode (u );
163- }
164- }
165- case RawNative :
166- while (i < max ) {
167- var c = b [i ++ ] | (b [i ++ ] << 8 );
168- s + = String .fromCharCode (c );
169- }
170- }
171- return s ;
139+
140+ var dec = switch (encoding ) {
141+ case UTF8 : new js.html. TextDecoder (" utf-8" );
142+ case RawNative : new js.html. TextDecoder (" utf-16" );
143+ };
144+ return dec .decode (b .subarray (pos , pos + len ));
172145 }
173146
174147 @:deprecated (" readString is deprecated, use getString instead" )
@@ -212,32 +185,10 @@ class Bytes {
212185 buf [(i << 1 ) | 1 ] = c >> 8 ;
213186 }
214187 return new Bytes (buf .buffer );
188+ } else {
189+ var enc = new js.html. TextEncoder ();
190+ return new Bytes (enc .encode (s ).buffer );
215191 }
216- var a = new Array ();
217- // utf16-decode and utf8-encode
218- var i = 0 ;
219- while (i < s .length ) {
220- var c : Int = StringTools .fastCodeAt (s , i ++ );
221- // surrogate pair
222- if (0xD800 <= c && c <= 0xDBFF )
223- c = (c - 0xD7C0 << 10 ) | (StringTools .fastCodeAt (s , i ++ ) & 0x3FF );
224- if (c <= 0x7F )
225- a .push (c );
226- else if (c <= 0x7FF ) {
227- a .push (0xC0 | (c >> 6 ));
228- a .push (0x80 | (c & 63 ));
229- } else if (c <= 0xFFFF ) {
230- a .push (0xE0 | (c >> 12 ));
231- a .push (0x80 | ((c >> 6 ) & 63 ));
232- a .push (0x80 | (c & 63 ));
233- } else {
234- a .push (0xF0 | (c >> 18 ));
235- a .push (0x80 | ((c >> 12 ) & 63 ));
236- a .push (0x80 | ((c >> 6 ) & 63 ));
237- a .push (0x80 | (c & 63 ));
238- }
239- }
240- return new Bytes (new js.lib. Uint8Array (a ).buffer );
241192 }
242193
243194 public static function ofData (b : BytesData ): Bytes {
0 commit comments