@@ -4,24 +4,30 @@ import Codec from './Codec';
44 * String codec (limited to 255 chars)
55 */
66export default class StringCodec extends Codec {
7+ constructor ( ) {
8+ this . encoder = new TextEncoder ( ) ;
9+ this . decoder = new TextDecoder ( TextEncoder . encoding ) ;
10+ }
11+
712 /**
813 * @type {Number }
914 */
1015 getByteLength ( data ) {
11- return 1 + ( data || '' ) . length * 2 ;
16+ return 1 + this . encoder . encode ( data || '' ) . length ;
1217 }
1318
1419 /**
1520 * {@inheritdoc }
1621 */
1722 encode ( buffer , offset , data ) {
18- const view = new DataView ( buffer , offset , this . getByteLength ( data ) ) ;
19- const { length } = ( data || '' ) ;
23+ const bytes = this . encoder . encode ( data || '' ) ;
24+ const { length } = bytes ;
25+ const view = new DataView ( buffer , offset , length + 1 ) ;
2026
2127 view . setUint8 ( 0 , length ) ;
2228
2329 for ( var index = 0 ; index < length ; index ++ ) {
24- view . setUint16 ( 1 + ( index * 2 ) , data [ index ] . charCodeAt ( 0 ) ) ;
30+ view . setUint8 ( index + 1 , bytes [ index ] ) ;
2531 }
2632 }
2733
@@ -31,12 +37,8 @@ export default class StringCodec extends Codec {
3137 decode ( buffer , offset ) {
3238 const view = new DataView ( buffer , offset ) ;
3339 const length = view . getUint8 ( 0 ) ;
34- const chars = new Array ( length ) ;
35-
36- for ( var index = 0 ; index < length ; index ++ ) {
37- chars [ index ] = view . getUint16 ( 1 + index * 2 ) ;
38- }
40+ const bytes = buffer . slice ( offset + 1 , offset + 1 + length ) ;
3941
40- return String . fromCharCode ( ... chars ) ;
42+ return this . decoder . decode ( bytes ) ;
4143 }
4244}
0 commit comments