UNPKG

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