generate.js 1.2 KB

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