From eda3796d53f443219a43bfdab02ba592f52ee461 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 7 May 2014 15:20:39 -0700 Subject: [PATCH] add Buffer.compare, #compare, #equals --- index.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/index.js b/index.js index d687ce2..c108847 100644 --- a/index.js +++ b/index.js @@ -192,6 +192,24 @@ Buffer.concat = function (list, totalLength) { return buf } +Buffer.compare = function (a, b) { + assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers') + var x = a.length + var y = b.length + for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} + if (i !== len) { + x = a[i] + y = b[i] + } + if (x < y) { + return -1 + } + if (y < x) { + return 1 + } + return 0 +} + // BUFFER INSTANCE METHODS // ======================= @@ -358,6 +376,17 @@ Buffer.prototype.toJSON = function () { } } +Buffer.prototype.equals = function (b) { + assert(Buffer.isBuffer(b), 'Argument must be a Buffer') + console.log(this, b) + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.compare = function (b) { + assert(Buffer.isBuffer(b), 'Argument must be a Buffer') + return Buffer.compare(this, b) +} + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this @@ -944,6 +973,8 @@ Buffer._augment = function (arr) { arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 -- 2.34.1