1 | const lodash = require('lodash');
|
2 | const { assert } = require('../util');
|
3 | const BytesCoder = require('./BytesCoder');
|
4 |
|
5 | class 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 |
|
20 |
|
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 |
|
35 |
|
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 |
|
54 | module.exports = StringCoder;
|