From ee0c28b712748d7368d295557b5dfc2dea96df24 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 28 Oct 2016 10:35:58 -0400 Subject: [PATCH] buffer: coerce offset using Math.trunc() This is a partial revert of 14d1a8a631a58408f1e85365a5f2aaa047cc0a5f, which coerced the offset of Buffer#slice() using the | operator. This causes some edge cases to be handled incorrectly. This commit restores the old behavior, but converts offsets to integers using Math.trunc(). This commit does not revert any tests, and adds an additional regression test. Refs: https://github.com/nodejs/node/issues/9096 Refs: https://github.com/nodejs/node/pull/9101 PR-URL: https://github.com/nodejs/node/pull/9341 Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell Reviewed-By: Brian White Reviewed-By: Trevor Norris --- lib/buffer.js | 6 ++++-- test/parallel/test-buffer-slice.js | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 942fc35071b451..3e745cde797aac 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -789,8 +789,10 @@ Buffer.prototype.toJSON = function() { function adjustOffset(offset, length) { - offset |= 0; - if (offset === 0) { + // Use Math.trunc() to convert offset to an integer value that can be larger + // than an Int32. Hence, don't use offset | 0 or similar techniques. + offset = Math.trunc(offset); + if (offset === 0 || Number.isNaN(offset)) { return 0; } else if (offset < 0) { offset += length; diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index e5b598e62519e7..076bf33fb07736 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -72,3 +72,30 @@ assert.strictEqual(0, Buffer.from('hello').slice(0, 0).length); 'bcd' ); } + +{ + const buf = Buffer.from('abcdefg'); + assert.strictEqual(buf.slice(-(-1 >>> 0) - 1).toString(), buf.toString()); +} + +{ + const buf = Buffer.from('abc'); + assert.strictEqual(buf.slice(-0.5).toString(), buf.toString()); +} + +{ + const buf = Buffer.from([ + 1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0, + 0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0 + ]); + const chunk1 = Buffer.from([ + 1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0 + ]); + const chunk2 = Buffer.from([ + 0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0 + ]); + const middle = buf.length / 2; + + assert.deepStrictEqual(buf.slice(0, middle), chunk1); + assert.deepStrictEqual(buf.slice(middle), chunk2); +}