Skip to content

Commit c70c96a

Browse files
cjihrigevanlucas
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 <thechargingvolcano@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Brian White <mscdex@mscdex.net> Reviewed-By: Trevor Norris <trev.norris@gmail.com>
1 parent f1f00df commit c70c96a

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
@@ -807,8 +807,10 @@ Buffer.prototype.toJSON = function() {
807807

808808

809809
function adjustOffset(offset, length) {
810-
offset |= 0;
811-
if (offset === 0) {
810+
// Use Math.trunc() to convert offset to an integer value that can be larger
811+
// than an Int32. Hence, don't use offset | 0 or similar techniques.
812+
offset = Math.trunc(offset);
813+
if (offset === 0 || Number.isNaN(offset)) {
812814
return 0;
813815
} else if (offset < 0) {
814816
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)