@@ -4,24 +4,32 @@ import Codec from './Codec';
44 * String codec (limited to 255 chars)
55 */
66export default class StringCodec extends Codec {
7+ constructor ( ) {
8+ super ( ) ;
9+
10+ this . encoder = new TextEncoder ( ) ;
11+ this . decoder = new TextDecoder ( TextEncoder . encoding ) ;
12+ }
13+
714 /**
815 * @type {Number }
916 */
1017 getByteLength ( data ) {
11- return 1 + ( data || '' ) . length * 2 ;
18+ return 1 + this . encoder . encode ( data || '' ) . length ;
1219 }
1320
1421 /**
1522 * {@inheritdoc }
1623 */
1724 encode ( buffer , offset , data ) {
18- const view = new DataView ( buffer , offset , this . getByteLength ( data ) ) ;
19- const { length } = ( data || '' ) ;
25+ const bytes = this . encoder . encode ( data || '' ) ;
26+ const { length } = bytes ;
27+ const view = new DataView ( buffer , offset , length + 1 ) ;
2028
2129 view . setUint8 ( 0 , length ) ;
2230
2331 for ( var index = 0 ; index < length ; index ++ ) {
24- view . setUint16 ( 1 + ( index * 2 ) , data [ index ] . charCodeAt ( 0 ) ) ;
32+ view . setUint8 ( index + 1 , bytes [ index ] ) ;
2533 }
2634 }
2735
@@ -31,12 +39,8 @@ export default class StringCodec extends Codec {
3139 decode ( buffer , offset ) {
3240 const view = new DataView ( buffer , offset ) ;
3341 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- }
42+ const bytes = buffer . slice ( offset + 1 , offset + 1 + length ) ;
3943
40- return String . fromCharCode ( ... chars ) ;
44+ return this . decoder . decode ( bytes ) ;
4145 }
4246}
0 commit comments