Skip to content

Commit 0cffa3c

Browse files
cjihrigMylesBorins
authored andcommitted
buffer: coerce offset using Math.trunc()
This is a partial revert of 14d1a8a, 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: #9096 Refs: #9101 PR-URL: #9341 Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Brian White <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 0276e9e commit 0cffa3c

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/buffer.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -789,8 +789,10 @@ Buffer.prototype.toJSON = function() {
789789

790790

791791
function adjustOffset(offset, length) {
792-
offset |= 0;
793-
if (offset === 0) {
792+
// Use Math.trunc() to convert offset to an integer value that can be larger
793+
// than an Int32. Hence, don't use offset | 0 or similar techniques.
794+
offset = Math.trunc(offset);
795+
if (offset === 0 || Number.isNaN(offset)) {
794796
return 0;
795797
} else if (offset < 0) {
796798
offset += length;

test/parallel/test-buffer-slice.js

+27
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,30 @@ assert.strictEqual(0, Buffer.from('hello').slice(0, 0).length);
7272
'bcd'
7373
);
7474
}
75+
76+
{
77+
const buf = Buffer.from('abcdefg');
78+
assert.strictEqual(buf.slice(-(-1 >>> 0) - 1).toString(), buf.toString());
79+
}
80+
81+
{
82+
const buf = Buffer.from('abc');
83+
assert.strictEqual(buf.slice(-0.5).toString(), buf.toString());
84+
}
85+
86+
{
87+
const buf = Buffer.from([
88+
1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0,
89+
0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0
90+
]);
91+
const chunk1 = Buffer.from([
92+
1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0
93+
]);
94+
const chunk2 = Buffer.from([
95+
0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0
96+
]);
97+
const middle = buf.length / 2;
98+
99+
assert.deepStrictEqual(buf.slice(0, middle), chunk1);
100+
assert.deepStrictEqual(buf.slice(middle), chunk2);
101+
}

0 commit comments

Comments
 (0)