@@ -15,13 +15,15 @@ export default class StringCodec extends Codec {
1515 * {@inheritdoc }
1616 */
1717 encode ( buffer , offset , data ) {
18- const view = new DataView ( buffer , offset , this . getByteLength ( data ) ) ;
19- const { length } = ( data || '' ) ;
18+ const encoder = new TextEncoder ( ) ;
19+ const bytes = encoder . encode ( data || '' ) ;
20+ const length = bytes . length ;
21+ const view = new DataView ( buffer , offset , length + 1 ) ;
2022
2123 view . setUint8 ( 0 , length ) ;
2224
2325 for ( var index = 0 ; index < length ; index ++ ) {
24- view . setUint16 ( 1 + ( index * 2 ) , data [ index ] . charCodeAt ( 0 ) ) ;
26+ view . setUint8 ( index + 1 , bytes [ index ] ) ;
2527 }
2628 }
2729
@@ -31,12 +33,9 @@ export default class StringCodec extends Codec {
3133 decode ( buffer , offset ) {
3234 const view = new DataView ( buffer , offset ) ;
3335 const length = view . getUint8 ( 0 ) ;
34- const chars = new Array ( length ) ;
36+ const bytes = buffer . slice ( offset + 1 , offset + 1 + length ) ;
37+ const decoder = new TextDecoder ( 'utf-8' ) ;
3538
36- for ( var index = 0 ; index < length ; index ++ ) {
37- chars [ index ] = view . getUint16 ( 1 + index * 2 ) ;
38- }
39-
40- return String . fromCharCode ( ...chars ) ;
39+ return decoder . decode ( bytes ) ;
4140 }
4241}
0 commit comments