Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
buffer: normalize compare() output
Browse files Browse the repository at this point in the history
Because of differences in memcmp() implementation, normalize output to
return -1, 0 or 1 only.
  • Loading branch information
trevnorris committed Apr 29, 2014
1 parent 26a1b71 commit 113764f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
10 changes: 7 additions & 3 deletions src/node_buffer.cc
Expand Up @@ -621,10 +621,14 @@ void Compare(const FunctionCallbackInfo<Value> &args) {
size_t cmp_length = MIN(obj_a_len, obj_b_len);

int32_t val = memcmp(obj_a_data, obj_b_data, cmp_length);
if (!val)
val = obj_a_len - obj_b_len;

args.GetReturnValue().Set(val);
if (val == 0 && obj_a_len != obj_b_len)
val = obj_a_len > obj_b_len ? 1 : -1;

if (val == 0)
args.GetReturnValue().Set(val);
else
args.GetReturnValue().Set(val > 0 ? 1 : -1);
}


Expand Down
8 changes: 4 additions & 4 deletions test/simple/test-buffer.js
Expand Up @@ -1043,13 +1043,13 @@ var b = new Buffer(1).fill('a');
var c = new Buffer(1).fill('c');
var d = new Buffer(2).fill('aa');

assert.equal(b.compare(c), -2);
assert.equal(c.compare(d), 2);
assert.equal(b.compare(c), -1);
assert.equal(c.compare(d), 1);
assert.equal(d.compare(b), 1);
assert.equal(b.compare(d), -1);

assert.equal(Buffer.compare(b, c), 2);
assert.equal(Buffer.compare(c, d), -2);
assert.equal(Buffer.compare(b, c), 1);
assert.equal(Buffer.compare(c, d), -1);
assert.equal(Buffer.compare(d, b), -1);
assert.equal(Buffer.compare(b, d), 1);

Expand Down

0 comments on commit 113764f

Please sign in to comment.