UNPKG

1.2 kBJavaScriptView Raw
1const lodash = require('lodash');
2const { assert } = require('../util');
3const BytesCoder = require('./BytesCoder');
4
5class StringCoder extends BytesCoder {
6 static from({ type, name }) {
7 if (type !== 'string') {
8 return undefined;
9 }
10 return new this({ type, name });
11 }
12
13 constructor({ type, name }) {
14 super({ name, size: undefined });
15 this.type = type;
16 }
17
18 /**
19 * @param value {string} - string in utf8
20 * @return {Buffer}
21 */
22 encode(value) {
23 assert(lodash.isString(value), {
24 message: 'value type error',
25 expect: 'string',
26 got: value.constructor.name,
27 coder: this,
28 });
29
30 return super.encode(Buffer.from(value, 'utf8'));
31 }
32
33 /**
34 * @param stream {HexStream}
35 * @return {string}
36 */
37 decode(stream) {
38 const bytes = super.decode(stream);
39 return bytes.toString('utf8');
40 }
41
42 encodeIndex(value) {
43 assert(lodash.isString(value), {
44 message: 'value type error',
45 expect: 'string',
46 got: value.constructor.name,
47 coder: this,
48 });
49
50 return super.encodeIndex(Buffer.from(value, 'utf8'));
51 }
52}
53
54module.exports = StringCoder;