|
1 |
| -const Buffer = require('safe-buffer').Buffer |
2 | 1 | const writeToStream = require('./writeToStream')
|
3 |
| -const EE = require('events').EventEmitter |
4 |
| -const inherits = require('inherits') |
| 2 | +const EventEmitter = require('events') |
5 | 3 |
|
6 | 4 | function generate (packet, opts) {
|
7 | 5 | const stream = new Accumulator()
|
8 | 6 | writeToStream(packet, stream, opts)
|
9 | 7 | return stream.concat()
|
10 | 8 | }
|
11 | 9 |
|
12 |
| -function Accumulator () { |
13 |
| - this._array = new Array(20) |
14 |
| - this._i = 0 |
15 |
| -} |
16 |
| - |
17 |
| -inherits(Accumulator, EE) |
| 10 | +class Accumulator extends EventEmitter { |
| 11 | + constructor () { |
| 12 | + super() |
| 13 | + this._array = new Array(20) |
| 14 | + this._i = 0 |
| 15 | + } |
18 | 16 |
|
19 |
| -Accumulator.prototype.write = function (chunk) { |
20 |
| - this._array[this._i++] = chunk |
21 |
| - return true |
22 |
| -} |
| 17 | + write (chunk) { |
| 18 | + this._array[this._i++] = chunk |
| 19 | + return true |
| 20 | + } |
23 | 21 |
|
24 |
| -Accumulator.prototype.concat = function () { |
25 |
| - let length = 0 |
26 |
| - const lengths = new Array(this._array.length) |
27 |
| - const list = this._array |
28 |
| - let pos = 0 |
29 |
| - let i |
| 22 | + concat () { |
| 23 | + let length = 0 |
| 24 | + const lengths = new Array(this._array.length) |
| 25 | + const list = this._array |
| 26 | + let pos = 0 |
| 27 | + let i |
30 | 28 |
|
31 |
| - for (i = 0; i < list.length && list[i] !== undefined; i++) { |
32 |
| - if (typeof list[i] !== 'string') lengths[i] = list[i].length |
33 |
| - else lengths[i] = Buffer.byteLength(list[i]) |
| 29 | + for (i = 0; i < list.length && list[i] !== undefined; i++) { |
| 30 | + if (typeof list[i] !== 'string') lengths[i] = list[i].length |
| 31 | + else lengths[i] = Buffer.byteLength(list[i]) |
34 | 32 |
|
35 |
| - length += lengths[i] |
36 |
| - } |
| 33 | + length += lengths[i] |
| 34 | + } |
37 | 35 |
|
38 |
| - const result = Buffer.allocUnsafe(length) |
| 36 | + const result = Buffer.allocUnsafe(length) |
39 | 37 |
|
40 |
| - for (i = 0; i < list.length && list[i] !== undefined; i++) { |
41 |
| - if (typeof list[i] !== 'string') { |
42 |
| - list[i].copy(result, pos) |
43 |
| - pos += lengths[i] |
44 |
| - } else { |
45 |
| - result.write(list[i], pos) |
46 |
| - pos += lengths[i] |
| 38 | + for (i = 0; i < list.length && list[i] !== undefined; i++) { |
| 39 | + if (typeof list[i] !== 'string') { |
| 40 | + list[i].copy(result, pos) |
| 41 | + pos += lengths[i] |
| 42 | + } else { |
| 43 | + result.write(list[i], pos) |
| 44 | + pos += lengths[i] |
| 45 | + } |
47 | 46 | }
|
48 |
| - } |
49 | 47 |
|
50 |
| - return result |
| 48 | + return result |
| 49 | + } |
51 | 50 | }
|
52 | 51 |
|
53 | 52 | module.exports = generate
|
0 commit comments