Skip to content

buffer: buf.write(string, offset) with negative offset #27043

Closed
@vsemozhetbyt

Description

All other Node.js Buffer methods either support negative offsets or throw errors for all negative integers stating that offset must be >= 0.

However, buf.write(string, offset) does not check if an offset is negative, but just converts it to uint32:

offset = offset >>> 0;

This may cause some slightly confusing effects:

  1. If -offset is > -buffer.constants.MAX_LENGTH, this produces not so clear error:
'use strict';

const buf = Buffer.alloc(10);

try {
  const len = buf.write('a', -1);
  console.log(buf.indexOf('a'));
} catch (err) {
  console.error(err.toString());
}

// Prints: RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
  1. If -offset is < -buffer.constants.MAX_LENGTH, string can be written in an unexpected place:
'use strict';

const buf = Buffer.alloc(10);

try {
  const len = buf.write('a', -4294967296);
  console.log(buf.indexOf('a'));
} catch (err) {
  console.error(err);
}

// Prints: 0

So should the method check the sign before the converting?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    bufferIssues and PRs related to the buffer subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions