You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

  1. /*!
  2. * ws: a node.js websocket client
  3. * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
  4. * MIT Licensed
  5. */
  6. module.exports.BufferUtil = {
  7. merge: function(mergedBuffer, buffers) {
  8. var offset = 0;
  9. for (var i = 0, l = buffers.length; i < l; ++i) {
  10. var buf = buffers[i];
  11. buf.copy(mergedBuffer, offset);
  12. offset += buf.length;
  13. }
  14. },
  15. mask: function(source, mask, output, offset, length) {
  16. var maskNum = mask.readUInt32LE(0, true);
  17. var i = 0;
  18. for (; i < length - 3; i += 4) {
  19. var num = maskNum ^ source.readUInt32LE(i, true);
  20. if (num < 0) num = 4294967296 + num;
  21. output.writeUInt32LE(num, offset + i, true);
  22. }
  23. switch (length % 4) {
  24. case 3: output[offset + i + 2] = source[i + 2] ^ mask[2];
  25. case 2: output[offset + i + 1] = source[i + 1] ^ mask[1];
  26. case 1: output[offset + i] = source[i] ^ mask[0];
  27. case 0:;
  28. }
  29. },
  30. unmask: function(data, mask) {
  31. var maskNum = mask.readUInt32LE(0, true);
  32. var length = data.length;
  33. var i = 0;
  34. for (; i < length - 3; i += 4) {
  35. var num = maskNum ^ data.readUInt32LE(i, true);
  36. if (num < 0) num = 4294967296 + num;
  37. data.writeUInt32LE(num, i, true);
  38. }
  39. switch (length % 4) {
  40. case 3: data[i + 2] = data[i + 2] ^ mask[2];
  41. case 2: data[i + 1] = data[i + 1] ^ mask[1];
  42. case 1: data[i] = data[i] ^ mask[0];
  43. case 0:;
  44. }
  45. }
  46. }