index.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*jshint node:true */
  2. 'use strict';
  3. var Buffer = require('buffer').Buffer; // browserify
  4. var SlowBuffer = require('buffer').SlowBuffer;
  5. module.exports = bufferEq;
  6. function bufferEq(a, b) {
  7. // shortcutting on type is necessary for correctness
  8. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  9. return false;
  10. }
  11. // buffer sizes should be well-known information, so despite this
  12. // shortcutting, it doesn't leak any information about the *contents* of the
  13. // buffers.
  14. if (a.length !== b.length) {
  15. return false;
  16. }
  17. var c = 0;
  18. for (var i = 0; i < a.length; i++) {
  19. /*jshint bitwise:false */
  20. c |= a[i] ^ b[i]; // XOR
  21. }
  22. return c === 0;
  23. }
  24. bufferEq.install = function() {
  25. Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
  26. return bufferEq(this, that);
  27. };
  28. };
  29. var origBufEqual = Buffer.prototype.equal;
  30. var origSlowBufEqual = SlowBuffer.prototype.equal;
  31. bufferEq.restore = function() {
  32. Buffer.prototype.equal = origBufEqual;
  33. SlowBuffer.prototype.equal = origSlowBufEqual;
  34. };