-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStringCodec.js
More file actions
46 lines (38 loc) · 1.04 KB
/
StringCodec.js
File metadata and controls
46 lines (38 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Codec from './Codec';
/**
* String codec (limited to 255 chars)
*/
export default class StringCodec extends Codec {
constructor() {
super();
this.encoder = new TextEncoder();
this.decoder = new TextDecoder(TextEncoder.encoding);
}
/**
* @type {Number}
*/
getByteLength(data) {
return 1 + this.encoder.encode(data || '').length;
}
/**
* {@inheritdoc}
*/
encode(buffer, offset, data) {
const bytes = this.encoder.encode(data || '');
const { length } = bytes;
const view = new DataView(buffer, offset, length + 1);
view.setUint8(0, length);
for (var index = 0; index < length; index++) {
view.setUint8(index + 1, bytes[index]);
}
}
/**
* {@inheritdoc}
*/
decode(buffer, offset) {
const view = new DataView(buffer, offset);
const length = view.getUint8(0);
const bytes = buffer.slice(offset + 1, offset + 1 + length);
return this.decoder.decode(bytes);
}
}