buffer-util.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. /**
  3. * Merges an array of buffers into a new buffer.
  4. *
  5. * @param {Buffer[]} list The array of buffers to concat
  6. * @param {Number} totalLength The total length of buffers in the list
  7. * @return {Buffer} The resulting buffer
  8. * @public
  9. */
  10. function concat (list, totalLength) {
  11. const target = Buffer.allocUnsafe(totalLength);
  12. var offset = 0;
  13. for (var i = 0; i < list.length; i++) {
  14. const buf = list[i];
  15. buf.copy(target, offset);
  16. offset += buf.length;
  17. }
  18. return target;
  19. }
  20. /**
  21. * Masks a buffer using the given mask.
  22. *
  23. * @param {Buffer} source The buffer to mask
  24. * @param {Buffer} mask The mask to use
  25. * @param {Buffer} output The buffer where to store the result
  26. * @param {Number} offset The offset at which to start writing
  27. * @param {Number} length The number of bytes to mask.
  28. * @public
  29. */
  30. function _mask (source, mask, output, offset, length) {
  31. for (var i = 0; i < length; i++) {
  32. output[offset + i] = source[i] ^ mask[i & 3];
  33. }
  34. }
  35. /**
  36. * Unmasks a buffer using the given mask.
  37. *
  38. * @param {Buffer} buffer The buffer to unmask
  39. * @param {Buffer} mask The mask to use
  40. * @public
  41. */
  42. function _unmask (buffer, mask) {
  43. // Required until https://github.com/nodejs/node/issues/9006 is resolved.
  44. const length = buffer.length;
  45. for (var i = 0; i < length; i++) {
  46. buffer[i] ^= mask[i & 3];
  47. }
  48. }
  49. try {
  50. const bufferUtil = require('bufferutil');
  51. const bu = bufferUtil.BufferUtil || bufferUtil;
  52. module.exports = {
  53. mask (source, mask, output, offset, length) {
  54. if (length < 48) _mask(source, mask, output, offset, length);
  55. else bu.mask(source, mask, output, offset, length);
  56. },
  57. unmask (buffer, mask) {
  58. if (buffer.length < 32) _unmask(buffer, mask);
  59. else bu.unmask(buffer, mask);
  60. },
  61. concat
  62. };
  63. } catch (e) /* istanbul ignore next */ {
  64. module.exports = { concat, mask: _mask, unmask: _unmask };
  65. }