react / wstein / node_modules / browserify / node_modules / module-deps / node_modules / stream-combiner2 / node_modules / through2 / node_modules / readable-stream / lib / _stream_readable.js
80580 views// Copyright Joyent, Inc. and other Node contributors.1//2// Permission is hereby granted, free of charge, to any person obtaining a3// copy of this software and associated documentation files (the4// "Software"), to deal in the Software without restriction, including5// without limitation the rights to use, copy, modify, merge, publish,6// distribute, sublicense, and/or sell copies of the Software, and to permit7// persons to whom the Software is furnished to do so, subject to the8// following conditions:9//10// The above copyright notice and this permission notice shall be included11// in all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF15// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN16// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,17// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR18// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE19// USE OR OTHER DEALINGS IN THE SOFTWARE.2021module.exports = Readable;2223/*<replacement>*/24var isArray = require('isarray');25/*</replacement>*/262728/*<replacement>*/29var Buffer = require('buffer').Buffer;30/*</replacement>*/3132Readable.ReadableState = ReadableState;3334var EE = require('events').EventEmitter;3536/*<replacement>*/37if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {38return emitter.listeners(type).length;39};40/*</replacement>*/4142var Stream = require('stream');4344/*<replacement>*/45var util = require('core-util-is');46util.inherits = require('inherits');47/*</replacement>*/4849var StringDecoder;5051util.inherits(Readable, Stream);5253function ReadableState(options, stream) {54options = options || {};5556// the point at which it stops calling _read() to fill the buffer57// Note: 0 is a valid value, means "don't call _read preemptively ever"58var hwm = options.highWaterMark;59this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;6061// cast to ints.62this.highWaterMark = ~~this.highWaterMark;6364this.buffer = [];65this.length = 0;66this.pipes = null;67this.pipesCount = 0;68this.flowing = false;69this.ended = false;70this.endEmitted = false;71this.reading = false;7273// In streams that never have any data, and do push(null) right away,74// the consumer can miss the 'end' event if they do some I/O before75// consuming the stream. So, we don't emit('end') until some reading76// happens.77this.calledRead = false;7879// a flag to be able to tell if the onwrite cb is called immediately,80// or on a later tick. We set this to true at first, becuase any81// actions that shouldn't happen until "later" should generally also82// not happen before the first write call.83this.sync = true;8485// whenever we return null, then we set a flag to say86// that we're awaiting a 'readable' event emission.87this.needReadable = false;88this.emittedReadable = false;89this.readableListening = false;909192// object stream flag. Used to make read(n) ignore n and to93// make all the buffer merging and length checks go away94this.objectMode = !!options.objectMode;9596// Crypto is kind of old and crusty. Historically, its default string97// encoding is 'binary' so we have to make this configurable.98// Everything else in the universe uses 'utf8', though.99this.defaultEncoding = options.defaultEncoding || 'utf8';100101// when piping, we only care about 'readable' events that happen102// after read()ing all the bytes and not getting any pushback.103this.ranOut = false;104105// the number of writers that are awaiting a drain event in .pipe()s106this.awaitDrain = 0;107108// if true, a maybeReadMore has been scheduled109this.readingMore = false;110111this.decoder = null;112this.encoding = null;113if (options.encoding) {114if (!StringDecoder)115StringDecoder = require('string_decoder/').StringDecoder;116this.decoder = new StringDecoder(options.encoding);117this.encoding = options.encoding;118}119}120121function Readable(options) {122if (!(this instanceof Readable))123return new Readable(options);124125this._readableState = new ReadableState(options, this);126127// legacy128this.readable = true;129130Stream.call(this);131}132133// Manually shove something into the read() buffer.134// This returns true if the highWaterMark has not been hit yet,135// similar to how Writable.write() returns true if you should136// write() some more.137Readable.prototype.push = function(chunk, encoding) {138var state = this._readableState;139140if (typeof chunk === 'string' && !state.objectMode) {141encoding = encoding || state.defaultEncoding;142if (encoding !== state.encoding) {143chunk = new Buffer(chunk, encoding);144encoding = '';145}146}147148return readableAddChunk(this, state, chunk, encoding, false);149};150151// Unshift should *always* be something directly out of read()152Readable.prototype.unshift = function(chunk) {153var state = this._readableState;154return readableAddChunk(this, state, chunk, '', true);155};156157function readableAddChunk(stream, state, chunk, encoding, addToFront) {158var er = chunkInvalid(state, chunk);159if (er) {160stream.emit('error', er);161} else if (chunk === null || chunk === undefined) {162state.reading = false;163if (!state.ended)164onEofChunk(stream, state);165} else if (state.objectMode || chunk && chunk.length > 0) {166if (state.ended && !addToFront) {167var e = new Error('stream.push() after EOF');168stream.emit('error', e);169} else if (state.endEmitted && addToFront) {170var e = new Error('stream.unshift() after end event');171stream.emit('error', e);172} else {173if (state.decoder && !addToFront && !encoding)174chunk = state.decoder.write(chunk);175176// update the buffer info.177state.length += state.objectMode ? 1 : chunk.length;178if (addToFront) {179state.buffer.unshift(chunk);180} else {181state.reading = false;182state.buffer.push(chunk);183}184185if (state.needReadable)186emitReadable(stream);187188maybeReadMore(stream, state);189}190} else if (!addToFront) {191state.reading = false;192}193194return needMoreData(state);195}196197198199// if it's past the high water mark, we can push in some more.200// Also, if we have no data yet, we can stand some201// more bytes. This is to work around cases where hwm=0,202// such as the repl. Also, if the push() triggered a203// readable event, and the user called read(largeNumber) such that204// needReadable was set, then we ought to push more, so that another205// 'readable' event will be triggered.206function needMoreData(state) {207return !state.ended &&208(state.needReadable ||209state.length < state.highWaterMark ||210state.length === 0);211}212213// backwards compatibility.214Readable.prototype.setEncoding = function(enc) {215if (!StringDecoder)216StringDecoder = require('string_decoder/').StringDecoder;217this._readableState.decoder = new StringDecoder(enc);218this._readableState.encoding = enc;219};220221// Don't raise the hwm > 128MB222var MAX_HWM = 0x800000;223function roundUpToNextPowerOf2(n) {224if (n >= MAX_HWM) {225n = MAX_HWM;226} else {227// Get the next highest power of 2228n--;229for (var p = 1; p < 32; p <<= 1) n |= n >> p;230n++;231}232return n;233}234235function howMuchToRead(n, state) {236if (state.length === 0 && state.ended)237return 0;238239if (state.objectMode)240return n === 0 ? 0 : 1;241242if (n === null || isNaN(n)) {243// only flow one buffer at a time244if (state.flowing && state.buffer.length)245return state.buffer[0].length;246else247return state.length;248}249250if (n <= 0)251return 0;252253// If we're asking for more than the target buffer level,254// then raise the water mark. Bump up to the next highest255// power of 2, to prevent increasing it excessively in tiny256// amounts.257if (n > state.highWaterMark)258state.highWaterMark = roundUpToNextPowerOf2(n);259260// don't have that much. return null, unless we've ended.261if (n > state.length) {262if (!state.ended) {263state.needReadable = true;264return 0;265} else266return state.length;267}268269return n;270}271272// you can override either this method, or the async _read(n) below.273Readable.prototype.read = function(n) {274var state = this._readableState;275state.calledRead = true;276var nOrig = n;277var ret;278279if (typeof n !== 'number' || n > 0)280state.emittedReadable = false;281282// if we're doing read(0) to trigger a readable event, but we283// already have a bunch of data in the buffer, then just trigger284// the 'readable' event and move on.285if (n === 0 &&286state.needReadable &&287(state.length >= state.highWaterMark || state.ended)) {288emitReadable(this);289return null;290}291292n = howMuchToRead(n, state);293294// if we've ended, and we're now clear, then finish it up.295if (n === 0 && state.ended) {296ret = null;297298// In cases where the decoder did not receive enough data299// to produce a full chunk, then immediately received an300// EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].301// howMuchToRead will see this and coerce the amount to302// read to zero (because it's looking at the length of the303// first <Buffer > in state.buffer), and we'll end up here.304//305// This can only happen via state.decoder -- no other venue306// exists for pushing a zero-length chunk into state.buffer307// and triggering this behavior. In this case, we return our308// remaining data and end the stream, if appropriate.309if (state.length > 0 && state.decoder) {310ret = fromList(n, state);311state.length -= ret.length;312}313314if (state.length === 0)315endReadable(this);316317return ret;318}319320// All the actual chunk generation logic needs to be321// *below* the call to _read. The reason is that in certain322// synthetic stream cases, such as passthrough streams, _read323// may be a completely synchronous operation which may change324// the state of the read buffer, providing enough data when325// before there was *not* enough.326//327// So, the steps are:328// 1. Figure out what the state of things will be after we do329// a read from the buffer.330//331// 2. If that resulting state will trigger a _read, then call _read.332// Note that this may be asynchronous, or synchronous. Yes, it is333// deeply ugly to write APIs this way, but that still doesn't mean334// that the Readable class should behave improperly, as streams are335// designed to be sync/async agnostic.336// Take note if the _read call is sync or async (ie, if the read call337// has returned yet), so that we know whether or not it's safe to emit338// 'readable' etc.339//340// 3. Actually pull the requested chunks out of the buffer and return.341342// if we need a readable event, then we need to do some reading.343var doRead = state.needReadable;344345// if we currently have less than the highWaterMark, then also read some346if (state.length - n <= state.highWaterMark)347doRead = true;348349// however, if we've ended, then there's no point, and if we're already350// reading, then it's unnecessary.351if (state.ended || state.reading)352doRead = false;353354if (doRead) {355state.reading = true;356state.sync = true;357// if the length is currently zero, then we *need* a readable event.358if (state.length === 0)359state.needReadable = true;360// call internal read method361this._read(state.highWaterMark);362state.sync = false;363}364365// If _read called its callback synchronously, then `reading`366// will be false, and we need to re-evaluate how much data we367// can return to the user.368if (doRead && !state.reading)369n = howMuchToRead(nOrig, state);370371if (n > 0)372ret = fromList(n, state);373else374ret = null;375376if (ret === null) {377state.needReadable = true;378n = 0;379}380381state.length -= n;382383// If we have nothing in the buffer, then we want to know384// as soon as we *do* get something into the buffer.385if (state.length === 0 && !state.ended)386state.needReadable = true;387388// If we happened to read() exactly the remaining amount in the389// buffer, and the EOF has been seen at this point, then make sure390// that we emit 'end' on the very next tick.391if (state.ended && !state.endEmitted && state.length === 0)392endReadable(this);393394return ret;395};396397function chunkInvalid(state, chunk) {398var er = null;399if (!Buffer.isBuffer(chunk) &&400'string' !== typeof chunk &&401chunk !== null &&402chunk !== undefined &&403!state.objectMode) {404er = new TypeError('Invalid non-string/buffer chunk');405}406return er;407}408409410function onEofChunk(stream, state) {411if (state.decoder && !state.ended) {412var chunk = state.decoder.end();413if (chunk && chunk.length) {414state.buffer.push(chunk);415state.length += state.objectMode ? 1 : chunk.length;416}417}418state.ended = true;419420// if we've ended and we have some data left, then emit421// 'readable' now to make sure it gets picked up.422if (state.length > 0)423emitReadable(stream);424else425endReadable(stream);426}427428// Don't emit readable right away in sync mode, because this can trigger429// another read() call => stack overflow. This way, it might trigger430// a nextTick recursion warning, but that's not so bad.431function emitReadable(stream) {432var state = stream._readableState;433state.needReadable = false;434if (state.emittedReadable)435return;436437state.emittedReadable = true;438if (state.sync)439process.nextTick(function() {440emitReadable_(stream);441});442else443emitReadable_(stream);444}445446function emitReadable_(stream) {447stream.emit('readable');448}449450451// at this point, the user has presumably seen the 'readable' event,452// and called read() to consume some data. that may have triggered453// in turn another _read(n) call, in which case reading = true if454// it's in progress.455// However, if we're not ended, or reading, and the length < hwm,456// then go ahead and try to read some more preemptively.457function maybeReadMore(stream, state) {458if (!state.readingMore) {459state.readingMore = true;460process.nextTick(function() {461maybeReadMore_(stream, state);462});463}464}465466function maybeReadMore_(stream, state) {467var len = state.length;468while (!state.reading && !state.flowing && !state.ended &&469state.length < state.highWaterMark) {470stream.read(0);471if (len === state.length)472// didn't get any data, stop spinning.473break;474else475len = state.length;476}477state.readingMore = false;478}479480// abstract method. to be overridden in specific implementation classes.481// call cb(er, data) where data is <= n in length.482// for virtual (non-string, non-buffer) streams, "length" is somewhat483// arbitrary, and perhaps not very meaningful.484Readable.prototype._read = function(n) {485this.emit('error', new Error('not implemented'));486};487488Readable.prototype.pipe = function(dest, pipeOpts) {489var src = this;490var state = this._readableState;491492switch (state.pipesCount) {493case 0:494state.pipes = dest;495break;496case 1:497state.pipes = [state.pipes, dest];498break;499default:500state.pipes.push(dest);501break;502}503state.pipesCount += 1;504505var doEnd = (!pipeOpts || pipeOpts.end !== false) &&506dest !== process.stdout &&507dest !== process.stderr;508509var endFn = doEnd ? onend : cleanup;510if (state.endEmitted)511process.nextTick(endFn);512else513src.once('end', endFn);514515dest.on('unpipe', onunpipe);516function onunpipe(readable) {517if (readable !== src) return;518cleanup();519}520521function onend() {522dest.end();523}524525// when the dest drains, it reduces the awaitDrain counter526// on the source. This would be more elegant with a .once()527// handler in flow(), but adding and removing repeatedly is528// too slow.529var ondrain = pipeOnDrain(src);530dest.on('drain', ondrain);531532function cleanup() {533// cleanup event handlers once the pipe is broken534dest.removeListener('close', onclose);535dest.removeListener('finish', onfinish);536dest.removeListener('drain', ondrain);537dest.removeListener('error', onerror);538dest.removeListener('unpipe', onunpipe);539src.removeListener('end', onend);540src.removeListener('end', cleanup);541542// if the reader is waiting for a drain event from this543// specific writer, then it would cause it to never start544// flowing again.545// So, if this is awaiting a drain, then we just call it now.546// If we don't know, then assume that we are waiting for one.547if (!dest._writableState || dest._writableState.needDrain)548ondrain();549}550551// if the dest has an error, then stop piping into it.552// however, don't suppress the throwing behavior for this.553function onerror(er) {554unpipe();555dest.removeListener('error', onerror);556if (EE.listenerCount(dest, 'error') === 0)557dest.emit('error', er);558}559// This is a brutally ugly hack to make sure that our error handler560// is attached before any userland ones. NEVER DO THIS.561if (!dest._events || !dest._events.error)562dest.on('error', onerror);563else if (isArray(dest._events.error))564dest._events.error.unshift(onerror);565else566dest._events.error = [onerror, dest._events.error];567568569570// Both close and finish should trigger unpipe, but only once.571function onclose() {572dest.removeListener('finish', onfinish);573unpipe();574}575dest.once('close', onclose);576function onfinish() {577dest.removeListener('close', onclose);578unpipe();579}580dest.once('finish', onfinish);581582function unpipe() {583src.unpipe(dest);584}585586// tell the dest that it's being piped to587dest.emit('pipe', src);588589// start the flow if it hasn't been started already.590if (!state.flowing) {591// the handler that waits for readable events after all592// the data gets sucked out in flow.593// This would be easier to follow with a .once() handler594// in flow(), but that is too slow.595this.on('readable', pipeOnReadable);596597state.flowing = true;598process.nextTick(function() {599flow(src);600});601}602603return dest;604};605606function pipeOnDrain(src) {607return function() {608var dest = this;609var state = src._readableState;610state.awaitDrain--;611if (state.awaitDrain === 0)612flow(src);613};614}615616function flow(src) {617var state = src._readableState;618var chunk;619state.awaitDrain = 0;620621function write(dest, i, list) {622var written = dest.write(chunk);623if (false === written) {624state.awaitDrain++;625}626}627628while (state.pipesCount && null !== (chunk = src.read())) {629630if (state.pipesCount === 1)631write(state.pipes, 0, null);632else633forEach(state.pipes, write);634635src.emit('data', chunk);636637// if anyone needs a drain, then we have to wait for that.638if (state.awaitDrain > 0)639return;640}641642// if every destination was unpiped, either before entering this643// function, or in the while loop, then stop flowing.644//645// NB: This is a pretty rare edge case.646if (state.pipesCount === 0) {647state.flowing = false;648649// if there were data event listeners added, then switch to old mode.650if (EE.listenerCount(src, 'data') > 0)651emitDataEvents(src);652return;653}654655// at this point, no one needed a drain, so we just ran out of data656// on the next readable event, start it over again.657state.ranOut = true;658}659660function pipeOnReadable() {661if (this._readableState.ranOut) {662this._readableState.ranOut = false;663flow(this);664}665}666667668Readable.prototype.unpipe = function(dest) {669var state = this._readableState;670671// if we're not piping anywhere, then do nothing.672if (state.pipesCount === 0)673return this;674675// just one destination. most common case.676if (state.pipesCount === 1) {677// passed in one, but it's not the right one.678if (dest && dest !== state.pipes)679return this;680681if (!dest)682dest = state.pipes;683684// got a match.685state.pipes = null;686state.pipesCount = 0;687this.removeListener('readable', pipeOnReadable);688state.flowing = false;689if (dest)690dest.emit('unpipe', this);691return this;692}693694// slow case. multiple pipe destinations.695696if (!dest) {697// remove all.698var dests = state.pipes;699var len = state.pipesCount;700state.pipes = null;701state.pipesCount = 0;702this.removeListener('readable', pipeOnReadable);703state.flowing = false;704705for (var i = 0; i < len; i++)706dests[i].emit('unpipe', this);707return this;708}709710// try to find the right one.711var i = indexOf(state.pipes, dest);712if (i === -1)713return this;714715state.pipes.splice(i, 1);716state.pipesCount -= 1;717if (state.pipesCount === 1)718state.pipes = state.pipes[0];719720dest.emit('unpipe', this);721722return this;723};724725// set up data events if they are asked for726// Ensure readable listeners eventually get something727Readable.prototype.on = function(ev, fn) {728var res = Stream.prototype.on.call(this, ev, fn);729730if (ev === 'data' && !this._readableState.flowing)731emitDataEvents(this);732733if (ev === 'readable' && this.readable) {734var state = this._readableState;735if (!state.readableListening) {736state.readableListening = true;737state.emittedReadable = false;738state.needReadable = true;739if (!state.reading) {740this.read(0);741} else if (state.length) {742emitReadable(this, state);743}744}745}746747return res;748};749Readable.prototype.addListener = Readable.prototype.on;750751// pause() and resume() are remnants of the legacy readable stream API752// If the user uses them, then switch into old mode.753Readable.prototype.resume = function() {754emitDataEvents(this);755this.read(0);756this.emit('resume');757};758759Readable.prototype.pause = function() {760emitDataEvents(this, true);761this.emit('pause');762};763764function emitDataEvents(stream, startPaused) {765var state = stream._readableState;766767if (state.flowing) {768// https://github.com/isaacs/readable-stream/issues/16769throw new Error('Cannot switch to old mode now.');770}771772var paused = startPaused || false;773var readable = false;774775// convert to an old-style stream.776stream.readable = true;777stream.pipe = Stream.prototype.pipe;778stream.on = stream.addListener = Stream.prototype.on;779780stream.on('readable', function() {781readable = true;782783var c;784while (!paused && (null !== (c = stream.read())))785stream.emit('data', c);786787if (c === null) {788readable = false;789stream._readableState.needReadable = true;790}791});792793stream.pause = function() {794paused = true;795this.emit('pause');796};797798stream.resume = function() {799paused = false;800if (readable)801process.nextTick(function() {802stream.emit('readable');803});804else805this.read(0);806this.emit('resume');807};808809// now make it start, just in case it hadn't already.810stream.emit('readable');811}812813// wrap an old-style stream as the async data source.814// This is *not* part of the readable stream interface.815// It is an ugly unfortunate mess of history.816Readable.prototype.wrap = function(stream) {817var state = this._readableState;818var paused = false;819820var self = this;821stream.on('end', function() {822if (state.decoder && !state.ended) {823var chunk = state.decoder.end();824if (chunk && chunk.length)825self.push(chunk);826}827828self.push(null);829});830831stream.on('data', function(chunk) {832if (state.decoder)833chunk = state.decoder.write(chunk);834835// don't skip over falsy values in objectMode836//if (state.objectMode && util.isNullOrUndefined(chunk))837if (state.objectMode && (chunk === null || chunk === undefined))838return;839else if (!state.objectMode && (!chunk || !chunk.length))840return;841842var ret = self.push(chunk);843if (!ret) {844paused = true;845stream.pause();846}847});848849// proxy all the other methods.850// important when wrapping filters and duplexes.851for (var i in stream) {852if (typeof stream[i] === 'function' &&853typeof this[i] === 'undefined') {854this[i] = function(method) { return function() {855return stream[method].apply(stream, arguments);856}}(i);857}858}859860// proxy certain important events.861var events = ['error', 'close', 'destroy', 'pause', 'resume'];862forEach(events, function(ev) {863stream.on(ev, self.emit.bind(self, ev));864});865866// when we try to consume some more bytes, simply unpause the867// underlying stream.868self._read = function(n) {869if (paused) {870paused = false;871stream.resume();872}873};874875return self;876};877878879880// exposed for testing purposes only.881Readable._fromList = fromList;882883// Pluck off n bytes from an array of buffers.884// Length is the combined lengths of all the buffers in the list.885function fromList(n, state) {886var list = state.buffer;887var length = state.length;888var stringMode = !!state.decoder;889var objectMode = !!state.objectMode;890var ret;891892// nothing in the list, definitely empty.893if (list.length === 0)894return null;895896if (length === 0)897ret = null;898else if (objectMode)899ret = list.shift();900else if (!n || n >= length) {901// read it all, truncate the array.902if (stringMode)903ret = list.join('');904else905ret = Buffer.concat(list, length);906list.length = 0;907} else {908// read just some of it.909if (n < list[0].length) {910// just take a part of the first list item.911// slice is the same for buffers and strings.912var buf = list[0];913ret = buf.slice(0, n);914list[0] = buf.slice(n);915} else if (n === list[0].length) {916// first list is a perfect match917ret = list.shift();918} else {919// complex case.920// we have enough to cover it, but it spans past the first buffer.921if (stringMode)922ret = '';923else924ret = new Buffer(n);925926var c = 0;927for (var i = 0, l = list.length; i < l && c < n; i++) {928var buf = list[0];929var cpy = Math.min(n - c, buf.length);930931if (stringMode)932ret += buf.slice(0, cpy);933else934buf.copy(ret, c, 0, cpy);935936if (cpy < buf.length)937list[0] = buf.slice(cpy);938else939list.shift();940941c += cpy;942}943}944}945946return ret;947}948949function endReadable(stream) {950var state = stream._readableState;951952// If we get here before consuming all the bytes, then that is a953// bug in node. Should never happen.954if (state.length > 0)955throw new Error('endReadable called on non-empty stream');956957if (!state.endEmitted && state.calledRead) {958state.ended = true;959process.nextTick(function() {960// Check that we didn't get one last unshift.961if (!state.endEmitted && state.length === 0) {962state.endEmitted = true;963stream.readable = false;964stream.emit('end');965}966});967}968}969970function forEach (xs, f) {971for (var i = 0, l = xs.length; i < l; i++) {972f(xs[i], i);973}974}975976function indexOf (xs, x) {977for (var i = 0, l = xs.length; i < l; i++) {978if (xs[i] === x) return i;979}980return -1;981}982983984