buffer: normalize compare() output
Because of differences in memcmp() implementation, normalize output to return -1, 0 or 1 only. Signed-off-by: Timothy J Fontaine <tjfontaine@gmail.com>
This commit is contained in:
parent
3d3d48d4b7
commit
d1fe6857ba
@ -621,8 +621,20 @@ 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;
|
||||
|
||||
// Normalize val to be an integer in the range of [1, -1] since
|
||||
// implementations of memcmp() can vary by platform.
|
||||
if (val == 0) {
|
||||
if (obj_a_len > obj_b_len)
|
||||
val = 1;
|
||||
else if (obj_a_len < obj_b_len)
|
||||
val = -1;
|
||||
} else {
|
||||
if (val > 0)
|
||||
val = 1;
|
||||
else
|
||||
val = -1;
|
||||
}
|
||||
|
||||
args.GetReturnValue().Set(val);
|
||||
}
|
||||
|
@ -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);
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user