1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const { Hex } = require('./type');
|
12 |
|
13 | const SHORT_RANGE = 55;
|
14 | const BUFFER_OFFSET = 0x80;
|
15 | const ARRAY_OFFSET = 0xc0;
|
16 |
|
17 | function concat(...args) {
|
18 | return Buffer.concat(args.map(value => {
|
19 | if (Buffer.isBuffer(value)) {
|
20 | return value;
|
21 | }
|
22 |
|
23 | if (Number.isInteger(value) && value >= 0) {
|
24 | return Hex.toBuffer(Hex(value));
|
25 | }
|
26 |
|
27 | throw new Error(`invalid value, expect unsigned integer or buffer, got ${value}`);
|
28 | }));
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | function encode(value) {
|
37 | if (Buffer.isBuffer(value)) {
|
38 | return encodeBuffer(value);
|
39 | }
|
40 |
|
41 | if (Array.isArray(value)) {
|
42 | return encodeArray(value);
|
43 | }
|
44 |
|
45 | throw new Error(`invalid value, expect buffer or array, got ${value}`);
|
46 | }
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | function encodeLength(length, offset) {
|
54 | if (length <= SHORT_RANGE) {
|
55 | return concat(length + offset);
|
56 | } else {
|
57 | const lengthBuffer = concat(length);
|
58 | return concat(offset + SHORT_RANGE + lengthBuffer.length, lengthBuffer);
|
59 | }
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | function encodeBuffer(buffer) {
|
67 | if (buffer.length === 1 && buffer[0] === 0) {
|
68 | buffer = Buffer.from('');
|
69 | }
|
70 |
|
71 | return buffer.length === 1 && buffer[0] < BUFFER_OFFSET
|
72 | ? buffer
|
73 | : concat(encodeLength(buffer.length, BUFFER_OFFSET), buffer);
|
74 | }
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | function encodeArray(array) {
|
81 | const buffer = concat(...array.map(encode));
|
82 | return concat(encodeLength(buffer.length, ARRAY_OFFSET), buffer);
|
83 | }
|
84 |
|
85 | module.exports = {
|
86 | encode,
|
87 | };
|