Skip to content

Commit 14d1a8a

Browse files
thefourtheyejasnell
authored andcommitted
buffer: coerce slice parameters consistently
As shown in #9096, the offset and end value of the `slice` call are coerced to numbers and then passed to `FastBuffer`, which internally truncates the mantissa part if the number is actually a floating point number. This actually affects the new length of the slice calculation. For example, > const original = Buffer.from('abcd'); undefined > original.slice(original.length / 3).toString() 'bc' This happens because, starting value of the slice is 4 / 3, which is 1.33 (approximately). Now, the length of the slice is calculated as the difference between the actual length of the buffer and the starting offset. So, it becomes 2.67 (4 - 1.33). Now, a new `FastBuffer` is constructed, with the following values as parameters, 1. actual buffer object, 2. starting value, which is 1.33 and 3. the length 2.67. The underlying C++ code truncates the numbers and they become 1 and 2. That is why the result is just `bc`. This patch makes sure that all the offsets are coerced to integers before any calculations are done. Fixes: #9096 PR-URL: #9101 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Franziska Hinkelmann <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Brian White <[email protected]>
1 parent 8788d00 commit 14d1a8a

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

lib/buffer.js

+3-4
Original file line numberDiff line numberDiff line change
@@ -807,11 +807,10 @@ Buffer.prototype.toJSON = function() {
807807

808808

809809
function adjustOffset(offset, length) {
810-
offset = +offset;
811-
if (offset === 0 || Number.isNaN(offset)) {
810+
offset |= 0;
811+
if (offset === 0) {
812812
return 0;
813-
}
814-
if (offset < 0) {
813+
} else if (offset < 0) {
815814
offset += length;
816815
return offset > 0 ? offset : 0;
817816
} else {

test/parallel/test-buffer-slice.js

+10
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,13 @@ assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0);
6262

6363
// slice(0,0).length === 0
6464
assert.strictEqual(0, Buffer.from('hello').slice(0, 0).length);
65+
66+
{
67+
// Regression tests for https://github.com/nodejs/node/issues/9096
68+
const buf = Buffer.from('abcd');
69+
assert.strictEqual(buf.slice(buf.length / 3).toString(), 'bcd');
70+
assert.strictEqual(
71+
buf.slice(buf.length / 3, buf.length).toString(),
72+
'bcd'
73+
);
74+
}

0 commit comments

Comments
 (0)