diff options
author | Trevor Norris <trev.norris@gmail.com> | 2014-04-29 14:46:58 -0700 |
---|---|---|
committer | Trevor Norris <trev.norris@gmail.com> | 2014-04-30 15:42:39 -0700 |
commit | 51f49ddb6615432b1a6437a8c932f9d2ce2a71cf (patch) | |
tree | 7e28a2be6d213e49be3939ddbe6fa640d891db4c | |
parent | d0fc5538d1ac769885c7e449b0d1f6759a7d4230 (diff) | |
download | node-buf-compare-normalize.tar.gz |
buffer: normalize compare() outputbuf-compare-normalize
Because of differences in memcmp() implementation, normalize output to
return -1, 0 or 1 only.
-rw-r--r-- | src/node_buffer.cc | 16 | ||||
-rw-r--r-- | test/simple/test-buffer.js | 8 |
2 files changed, 18 insertions, 6 deletions
diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 05d3566ae..64f077a68 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -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); } diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 60c7b7f44..095551b7d 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -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); |