Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: coerce slice parameters consistenly #9101

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -807,11 +807,10 @@ Buffer.prototype.toJSON = function() {


function adjustOffset(offset, length) {
offset = +offset;
if (offset === 0 || Number.isNaN(offset)) {
offset |= 0;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want the floor then please use Math.floor(). Using | allows wrap around. One reason why + was used before.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thefourtheye

String's slice also works like this only

This fails edge cases. For example:

'abcdefg'.slice(-(-1 >>> 0) - 1) === 'abcdefg';

But as this currently stands offset will be coerced to 2 with the above example.

if (offset === 0) {
return 0;
}
if (offset < 0) {
} else if (offset < 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's where the problem lies. There's no range check before the int32 coercion. A large number could fail this.

offset += length;
return offset > 0 ? offset : 0;
} else {
Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-buffer-slice.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,13 @@ assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0);

// slice(0,0).length === 0
assert.strictEqual(0, Buffer.from('hello').slice(0, 0).length);

{
// Regression tests for https://github.com/nodejs/node/issues/9096
const buf = Buffer.from('abcd');
assert.strictEqual(buf.slice(buf.length / 3).toString(), 'bcd');
assert.strictEqual(
buf.slice(buf.length / 3, buf.length).toString(),
'bcd'
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're making the change to operate like String#slice() then edge case tests should be included. e.g.:

const b = Buffer.from('abcdefg');
assert.strictEqual(b.slice(-(-1 >>> 0) + 1).toString(), b.toString());

}