Skip to content

Commit

Permalink
fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Oct 20, 2019
1 parent 7539c6f commit a51e404
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
2 changes: 1 addition & 1 deletion doc/api/stream.md
Expand Up @@ -1084,7 +1084,7 @@ buffer will be returned.
If the `size` argument is not specified, all of the data contained in the
internal buffer will be returned.

The `size` argument must be less than or equal to 2^31.
The `size` argument must be less than or equal to 2^30.

The `readable.read()` method should only be called on `Readable` streams
operating in paused mode. In flowing mode, `readable.read()` is called
Expand Down
38 changes: 23 additions & 15 deletions lib/_stream_readable.js
Expand Up @@ -41,12 +41,9 @@ const {
ERR_INVALID_ARG_TYPE,
ERR_STREAM_PUSH_AFTER_EOF,
ERR_METHOD_NOT_IMPLEMENTED,
ERR_STREAM_UNSHIFT_AFTER_END_EVENT,
ERR_VALUE_OUT_OF_RANGE
ERR_STREAM_UNSHIFT_AFTER_END_EVENT
} = require('internal/errors').codes;

const MAX_HWM = Math.pow(2, 31);

// Lazy loaded to improve the startup performance.
let StringDecoder;
let createReadableStreamAsyncIterator;
Expand Down Expand Up @@ -377,6 +374,26 @@ Readable.prototype.setEncoding = function(enc) {
return this;
};

// Don't raise the hwm > 1GB
const MAX_HWM = Math.pow(2, 30);
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
// TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
Expand Down Expand Up @@ -409,18 +426,9 @@ Readable.prototype.read = function(n) {
const state = this._readableState;
const nOrig = n;

if (n > MAX_HWM) {
throw new ERR_VALUE_OUT_OF_RANGE('n');
}

// If we're asking for more than the current hwm, then raise the hwm to
// the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts.
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark)
state.highWaterMark = Math.min(
MAX_HWM,
Math.pow(2, Math.ceil(Math.log(n) / Math.log(2)))
);
state.highWaterMark = computeNewHighWaterMark(n);

if (n !== 0)
state.emittedReadable = false;
Expand Down

0 comments on commit a51e404

Please sign in to comment.