UNPKG

1.14 kBJavaScriptView Raw
1const writeToStream = require('./writeToStream')
2const EventEmitter = require('events')
3
4function generate (packet, opts) {
5 const stream = new Accumulator()
6 writeToStream(packet, stream, opts)
7 return stream.concat()
8}
9
10class Accumulator extends EventEmitter {
11 constructor () {
12 super()
13 this._array = new Array(20)
14 this._i = 0
15 }
16
17 write (chunk) {
18 this._array[this._i++] = chunk
19 return true
20 }
21
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
28
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])
32
33 length += lengths[i]
34 }
35
36 const result = Buffer.allocUnsafe(length)
37
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 }
46 }
47
48 return result
49 }
50}
51
52module.exports = generate