Skip to content

Commit 226f98a

Browse files
seanmonstartrevnorris
authored andcommitted
buffer: add compare and equals methods
compare() works like String.localeCompare such that: Buffer.compare(a, b) === a.compare(b); equals() does a native check to see if two buffers are equal. Signed-off-by: Trevor Norris <[email protected]>
1 parent 681fe59 commit 226f98a

6 files changed

Lines changed: 164 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright Joyent, Inc. and other Node contributors.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a
4+
// copy of this software and associated documentation files (the
5+
// "Software"), to deal in the Software without restriction, including
6+
// without limitation the rights to use, copy, modify, merge, publish,
7+
// distribute, sublicense, and/or sell copies of the Software, and to permit
8+
// persons to whom the Software is furnished to do so, subject to the
9+
// following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included
12+
// in all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16+
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17+
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18+
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20+
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21+
22+
var common = require('../common.js');
23+
24+
var bench = common.createBenchmark(main, {
25+
size: [16, 512, 1024, 4096, 16386],
26+
millions: [1]
27+
});
28+
29+
function main(conf) {
30+
var iter = (conf.millions >>> 0) * 1e6;
31+
var size = (conf.size >>> 0);
32+
var b0 = new Buffer(size).fill('a');
33+
var b1 = new Buffer(size).fill('a');
34+
35+
b1[size - 1] = 'b'.charCodeAt(0);
36+
37+
bench.start();
38+
for (var i = 0; i < iter; i++) {
39+
Buffer.compare(b0, b1);
40+
}
41+
bench.end(iter / 1e6);
42+
}

doc/api/buffer.markdown

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,18 @@ If totalLength is not provided, it is read from the buffers in the list.
115115
However, this adds an additional loop to the function, so it is faster
116116
to provide the length explicitly.
117117

118+
### Class Method: Buffer.compare(buf1, buf2)
119+
120+
* `buf1` {Buffer}
121+
* `buf2` {Buffer}
122+
123+
The same as [`buf1.compare(buf2)`](#buffer_buf_compare_otherbuffer). Useful
124+
for sorting an Array of Buffers:
125+
126+
var arr = [Buffer('1234'), Buffer('0123')];
127+
arr.sort(Buffer.compare);
128+
129+
118130
### buf.length
119131

120132
* Number
@@ -207,6 +219,21 @@ Example: copy an ASCII string into a buffer, one byte at a time:
207219

208220
// node.js
209221

222+
### buf.equals(otherBuffer)
223+
224+
* `otherBuffer` {Buffer}
225+
226+
Returns a boolean of whether `this` and `otherBuffer` have the same
227+
bytes.
228+
229+
### buf.compare(otherBuffer)
230+
231+
* `otherBuffer` {Buffer}
232+
233+
Returns a number indicating whether `this` comes before or after or is
234+
the same as the `otherBuffer` in sort order.
235+
236+
210237
### buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
211238

212239
* `targetBuffer` Buffer object - Buffer to copy into

lib/buffer.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,15 @@ Buffer.isBuffer = function isBuffer(b) {
130130
};
131131

132132

133+
Buffer.compare = function compare(a, b) {
134+
if (!(a instanceof Buffer) ||
135+
!(b instanceof Buffer))
136+
throw new TypeError('Arguments must be Buffers');
137+
138+
return internal.compare(b, a);
139+
};
140+
141+
133142
Buffer.isEncoding = function(encoding) {
134143
switch ((encoding + '').toLowerCase()) {
135144
case 'hex':
@@ -256,6 +265,14 @@ Buffer.prototype.toString = function(encoding, start, end) {
256265
};
257266

258267

268+
Buffer.prototype.equals = function equals(b) {
269+
if (!(b instanceof Buffer))
270+
throw new TypeError('Argument must be a Buffer');
271+
272+
return internal.compare(this, b) === 0;
273+
};
274+
275+
259276
// Inspect
260277
Buffer.prototype.inspect = function inspect() {
261278
var str = '';
@@ -269,6 +286,14 @@ Buffer.prototype.inspect = function inspect() {
269286
};
270287

271288

289+
Buffer.prototype.compare = function compare(b) {
290+
if (!(b instanceof Buffer))
291+
throw new TypeError('Argument must be a Buffer');
292+
293+
return internal.compare(this, b);
294+
};
295+
296+
272297
// XXX remove in v0.13
273298
Buffer.prototype.get = util.deprecate(function get(offset) {
274299
offset = ~~offset;

src/env.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ namespace node {
6969
V(change_string, "change") \
7070
V(close_string, "close") \
7171
V(code_string, "code") \
72+
V(compare_string, "compare") \
7273
V(ctime_string, "ctime") \
7374
V(cwd_string, "cwd") \
7475
V(debug_port_string, "debugPort") \

src/node_buffer.cc

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,27 @@ void ByteLength(const FunctionCallbackInfo<Value> &args) {
607607
}
608608

609609

610+
void Compare(const FunctionCallbackInfo<Value> &args) {
611+
Local<Object> obj_a = args[0].As<Object>();
612+
char* obj_a_data =
613+
static_cast<char*>(obj_a->GetIndexedPropertiesExternalArrayData());
614+
size_t obj_a_len = obj_a->GetIndexedPropertiesExternalArrayDataLength();
615+
616+
Local<Object> obj_b = args[1].As<Object>();
617+
char* obj_b_data =
618+
static_cast<char*>(obj_b->GetIndexedPropertiesExternalArrayData());
619+
size_t obj_b_len = obj_b->GetIndexedPropertiesExternalArrayDataLength();
620+
621+
size_t cmp_length = MIN(obj_a_len, obj_b_len);
622+
623+
int32_t val = memcmp(obj_a_data, obj_b_data, cmp_length);
624+
if (!val)
625+
val = obj_a_len - obj_b_len;
626+
627+
args.GetReturnValue().Set(val);
628+
}
629+
630+
610631
// pass Buffer object to load prototype methods
611632
void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
612633
Environment* env = Environment::GetCurrent(args.GetIsolate());
@@ -663,6 +684,9 @@ void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
663684
internal->Set(env->byte_length_string(),
664685
FunctionTemplate::New(
665686
env->isolate(), ByteLength)->GetFunction());
687+
internal->Set(env->compare_string(),
688+
FunctionTemplate::New(
689+
env->isolate(), Compare)->GetFunction());
666690
}
667691

668692

test/simple/test-buffer.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,3 +1037,48 @@ assert.equal(
10371037
crypto.createHash('sha1').update(b1).digest('hex'),
10381038
crypto.createHash('sha1').update(b2).digest('hex')
10391039
);
1040+
1041+
// Test Compare
1042+
var b = new Buffer(1).fill('a');
1043+
var c = new Buffer(1).fill('c');
1044+
var d = new Buffer(2).fill('aa');
1045+
1046+
assert.equal(b.compare(c), -2);
1047+
assert.equal(c.compare(d), 2);
1048+
assert.equal(d.compare(b), 1);
1049+
assert.equal(b.compare(d), -1);
1050+
1051+
assert.equal(Buffer.compare(b, c), 2);
1052+
assert.equal(Buffer.compare(c, d), -2);
1053+
assert.equal(Buffer.compare(d, b), -1);
1054+
assert.equal(Buffer.compare(b, d), 1);
1055+
1056+
assert.throws(function() {
1057+
var b = new Buffer(1);
1058+
Buffer.compare(b, 'abc');
1059+
});
1060+
1061+
assert.throws(function() {
1062+
var b = new Buffer(1);
1063+
Buffer.compare('abc', b);
1064+
});
1065+
1066+
assert.throws(function() {
1067+
var b = new Buffer(1);
1068+
b.compare('abc');
1069+
});
1070+
1071+
// Test Equals
1072+
var b = new Buffer(5).fill('abcdf');
1073+
var c = new Buffer(5).fill('abcdf');
1074+
var d = new Buffer(5).fill('abcde');
1075+
var e = new Buffer(6).fill('abcdef');
1076+
1077+
assert.ok(b.equals(c));
1078+
assert.ok(!c.equals(d));
1079+
assert.ok(!d.equals(e));
1080+
1081+
assert.throws(function() {
1082+
var b = new Buffer(1);
1083+
b.equals('abc');
1084+
});

0 commit comments

Comments
 (0)