crypto: make randomBytes/pbkdf2 cbs domain aware
[platform/upstream/nodejs.git] / lib / _stream_readable.js
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 module.exports = Readable;
23 Readable.ReadableState = ReadableState;
24
25 var EE = require('events').EventEmitter;
26 var Stream = require('stream');
27 var util = require('util');
28 var StringDecoder;
29 var debug = util.debuglog('stream');
30
31 util.inherits(Readable, Stream);
32
33 function ReadableState(options, stream) {
34   options = options || {};
35
36   // the point at which it stops calling _read() to fill the buffer
37   // Note: 0 is a valid value, means "don't call _read preemptively ever"
38   var hwm = options.highWaterMark;
39   var defaultHwm = options.objectMode ? 16 : 16 * 1024;
40   this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
41
42   // cast to ints.
43   this.highWaterMark = ~~this.highWaterMark;
44
45   this.buffer = [];
46   this.length = 0;
47   this.pipes = null;
48   this.pipesCount = 0;
49   this.flowing = null;
50   this.ended = false;
51   this.endEmitted = false;
52   this.reading = false;
53
54   // a flag to be able to tell if the onwrite cb is called immediately,
55   // or on a later tick.  We set this to true at first, because any
56   // actions that shouldn't happen until "later" should generally also
57   // not happen before the first write call.
58   this.sync = true;
59
60   // whenever we return null, then we set a flag to say
61   // that we're awaiting a 'readable' event emission.
62   this.needReadable = false;
63   this.emittedReadable = false;
64   this.readableListening = false;
65
66
67   // object stream flag. Used to make read(n) ignore n and to
68   // make all the buffer merging and length checks go away
69   this.objectMode = !!options.objectMode;
70
71   // Crypto is kind of old and crusty.  Historically, its default string
72   // encoding is 'binary' so we have to make this configurable.
73   // Everything else in the universe uses 'utf8', though.
74   this.defaultEncoding = options.defaultEncoding || 'utf8';
75
76   // when piping, we only care about 'readable' events that happen
77   // after read()ing all the bytes and not getting any pushback.
78   this.ranOut = false;
79
80   // the number of writers that are awaiting a drain event in .pipe()s
81   this.awaitDrain = 0;
82
83   // if true, a maybeReadMore has been scheduled
84   this.readingMore = false;
85
86   this.decoder = null;
87   this.encoding = null;
88   if (options.encoding) {
89     if (!StringDecoder)
90       StringDecoder = require('string_decoder').StringDecoder;
91     this.decoder = new StringDecoder(options.encoding);
92     this.encoding = options.encoding;
93   }
94 }
95
96 function Readable(options) {
97   if (!(this instanceof Readable))
98     return new Readable(options);
99
100   this._readableState = new ReadableState(options, this);
101
102   // legacy
103   this.readable = true;
104
105   Stream.call(this);
106 }
107
108 // Manually shove something into the read() buffer.
109 // This returns true if the highWaterMark has not been hit yet,
110 // similar to how Writable.write() returns true if you should
111 // write() some more.
112 Readable.prototype.push = function(chunk, encoding) {
113   var state = this._readableState;
114
115   if (util.isString(chunk) && !state.objectMode) {
116     encoding = encoding || state.defaultEncoding;
117     if (encoding !== state.encoding) {
118       chunk = new Buffer(chunk, encoding);
119       encoding = '';
120     }
121   }
122
123   return readableAddChunk(this, state, chunk, encoding, false);
124 };
125
126 // Unshift should *always* be something directly out of read()
127 Readable.prototype.unshift = function(chunk) {
128   var state = this._readableState;
129   return readableAddChunk(this, state, chunk, '', true);
130 };
131
132 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
133   var er = chunkInvalid(state, chunk);
134   if (er) {
135     stream.emit('error', er);
136   } else if (util.isNullOrUndefined(chunk)) {
137     state.reading = false;
138     if (!state.ended)
139       onEofChunk(stream, state);
140   } else if (state.objectMode || chunk && chunk.length > 0) {
141     if (state.ended && !addToFront) {
142       var e = new Error('stream.push() after EOF');
143       stream.emit('error', e);
144     } else if (state.endEmitted && addToFront) {
145       var e = new Error('stream.unshift() after end event');
146       stream.emit('error', e);
147     } else {
148       if (state.decoder && !addToFront && !encoding)
149         chunk = state.decoder.write(chunk);
150
151       if (!addToFront)
152         state.reading = false;
153
154       // if we want the data now, just emit it.
155       if (state.flowing && state.length === 0 && !state.sync) {
156         stream.emit('data', chunk);
157         stream.read(0);
158       } else {
159         // update the buffer info.
160         state.length += state.objectMode ? 1 : chunk.length;
161         if (addToFront)
162           state.buffer.unshift(chunk);
163         else
164           state.buffer.push(chunk);
165
166         if (state.needReadable)
167           emitReadable(stream);
168       }
169
170       maybeReadMore(stream, state);
171     }
172   } else if (!addToFront) {
173     state.reading = false;
174   }
175
176   return needMoreData(state);
177 }
178
179
180
181 // if it's past the high water mark, we can push in some more.
182 // Also, if we have no data yet, we can stand some
183 // more bytes.  This is to work around cases where hwm=0,
184 // such as the repl.  Also, if the push() triggered a
185 // readable event, and the user called read(largeNumber) such that
186 // needReadable was set, then we ought to push more, so that another
187 // 'readable' event will be triggered.
188 function needMoreData(state) {
189   return !state.ended &&
190          (state.needReadable ||
191           state.length < state.highWaterMark ||
192           state.length === 0);
193 }
194
195 // backwards compatibility.
196 Readable.prototype.setEncoding = function(enc) {
197   if (!StringDecoder)
198     StringDecoder = require('string_decoder').StringDecoder;
199   this._readableState.decoder = new StringDecoder(enc);
200   this._readableState.encoding = enc;
201 };
202
203 // Don't raise the hwm > 128MB
204 var MAX_HWM = 0x800000;
205 function roundUpToNextPowerOf2(n) {
206   if (n >= MAX_HWM) {
207     n = MAX_HWM;
208   } else {
209     // Get the next highest power of 2
210     n--;
211     for (var p = 1; p < 32; p <<= 1) n |= n >> p;
212     n++;
213   }
214   return n;
215 }
216
217 function howMuchToRead(n, state) {
218   if (state.length === 0 && state.ended)
219     return 0;
220
221   if (state.objectMode)
222     return n === 0 ? 0 : 1;
223
224   if (isNaN(n) || util.isNull(n)) {
225     // only flow one buffer at a time
226     if (state.flowing && state.buffer.length)
227       return state.buffer[0].length;
228     else
229       return state.length;
230   }
231
232   if (n <= 0)
233     return 0;
234
235   // If we're asking for more than the target buffer level,
236   // then raise the water mark.  Bump up to the next highest
237   // power of 2, to prevent increasing it excessively in tiny
238   // amounts.
239   if (n > state.highWaterMark)
240     state.highWaterMark = roundUpToNextPowerOf2(n);
241
242   // don't have that much.  return null, unless we've ended.
243   if (n > state.length) {
244     if (!state.ended) {
245       state.needReadable = true;
246       return 0;
247     } else
248       return state.length;
249   }
250
251   return n;
252 }
253
254 // you can override either this method, or the async _read(n) below.
255 Readable.prototype.read = function(n) {
256   debug('read', n);
257   var state = this._readableState;
258   var nOrig = n;
259
260   if (!util.isNumber(n) || n > 0)
261     state.emittedReadable = false;
262
263   // if we're doing read(0) to trigger a readable event, but we
264   // already have a bunch of data in the buffer, then just trigger
265   // the 'readable' event and move on.
266   if (n === 0 &&
267       state.needReadable &&
268       (state.length >= state.highWaterMark || state.ended)) {
269     debug('read: emitReadable', state.length, state.ended);
270     if (state.length === 0 && state.ended)
271       endReadable(this);
272     else
273       emitReadable(this);
274     return null;
275   }
276
277   n = howMuchToRead(n, state);
278
279   // if we've ended, and we're now clear, then finish it up.
280   if (n === 0 && state.ended) {
281     if (state.length === 0)
282       endReadable(this);
283     return null;
284   }
285
286   // All the actual chunk generation logic needs to be
287   // *below* the call to _read.  The reason is that in certain
288   // synthetic stream cases, such as passthrough streams, _read
289   // may be a completely synchronous operation which may change
290   // the state of the read buffer, providing enough data when
291   // before there was *not* enough.
292   //
293   // So, the steps are:
294   // 1. Figure out what the state of things will be after we do
295   // a read from the buffer.
296   //
297   // 2. If that resulting state will trigger a _read, then call _read.
298   // Note that this may be asynchronous, or synchronous.  Yes, it is
299   // deeply ugly to write APIs this way, but that still doesn't mean
300   // that the Readable class should behave improperly, as streams are
301   // designed to be sync/async agnostic.
302   // Take note if the _read call is sync or async (ie, if the read call
303   // has returned yet), so that we know whether or not it's safe to emit
304   // 'readable' etc.
305   //
306   // 3. Actually pull the requested chunks out of the buffer and return.
307
308   // if we need a readable event, then we need to do some reading.
309   var doRead = state.needReadable;
310   debug('need readable', doRead);
311
312   // if we currently have less than the highWaterMark, then also read some
313   if (state.length === 0 || state.length - n < state.highWaterMark) {
314     doRead = true;
315     debug('length less than watermark', doRead);
316   }
317
318   // however, if we've ended, then there's no point, and if we're already
319   // reading, then it's unnecessary.
320   if (state.ended || state.reading) {
321     doRead = false;
322     debug('reading or ended', doRead);
323   }
324
325   if (doRead) {
326     debug('do read');
327     state.reading = true;
328     state.sync = true;
329     // if the length is currently zero, then we *need* a readable event.
330     if (state.length === 0)
331       state.needReadable = true;
332     // call internal read method
333     this._read(state.highWaterMark);
334     state.sync = false;
335   }
336
337   // If _read pushed data synchronously, then `reading` will be false,
338   // and we need to re-evaluate how much data we can return to the user.
339   if (doRead && !state.reading)
340     n = howMuchToRead(nOrig, state);
341
342   var ret;
343   if (n > 0)
344     ret = fromList(n, state);
345   else
346     ret = null;
347
348   if (util.isNull(ret)) {
349     state.needReadable = true;
350     n = 0;
351   }
352
353   state.length -= n;
354
355   // If we have nothing in the buffer, then we want to know
356   // as soon as we *do* get something into the buffer.
357   if (state.length === 0 && !state.ended)
358     state.needReadable = true;
359
360   // If we tried to read() past the EOF, then emit end on the next tick.
361   if (nOrig !== n && state.ended && state.length === 0)
362     endReadable(this);
363
364   if (!util.isNull(ret))
365     this.emit('data', ret);
366
367   return ret;
368 };
369
370 function chunkInvalid(state, chunk) {
371   var er = null;
372   if (!util.isBuffer(chunk) &&
373       !util.isString(chunk) &&
374       !util.isNullOrUndefined(chunk) &&
375       !state.objectMode &&
376       !er) {
377     er = new TypeError('Invalid non-string/buffer chunk');
378   }
379   return er;
380 }
381
382
383 function onEofChunk(stream, state) {
384   if (state.decoder && !state.ended) {
385     var chunk = state.decoder.end();
386     if (chunk && chunk.length) {
387       state.buffer.push(chunk);
388       state.length += state.objectMode ? 1 : chunk.length;
389     }
390   }
391   state.ended = true;
392
393   // emit 'readable' now to make sure it gets picked up.
394   emitReadable(stream);
395 }
396
397 // Don't emit readable right away in sync mode, because this can trigger
398 // another read() call => stack overflow.  This way, it might trigger
399 // a nextTick recursion warning, but that's not so bad.
400 function emitReadable(stream) {
401   var state = stream._readableState;
402   state.needReadable = false;
403   if (!state.emittedReadable) {
404     debug('emitReadable', state.flowing);
405     state.emittedReadable = true;
406     if (state.sync)
407       process.nextTick(function() {
408         emitReadable_(stream);
409       });
410     else
411       emitReadable_(stream);
412   }
413 }
414
415 function emitReadable_(stream) {
416   debug('emit readable');
417   stream.emit('readable');
418   flow(stream);
419 }
420
421
422 // at this point, the user has presumably seen the 'readable' event,
423 // and called read() to consume some data.  that may have triggered
424 // in turn another _read(n) call, in which case reading = true if
425 // it's in progress.
426 // However, if we're not ended, or reading, and the length < hwm,
427 // then go ahead and try to read some more preemptively.
428 function maybeReadMore(stream, state) {
429   if (!state.readingMore) {
430     state.readingMore = true;
431     process.nextTick(function() {
432       maybeReadMore_(stream, state);
433     });
434   }
435 }
436
437 function maybeReadMore_(stream, state) {
438   var len = state.length;
439   while (!state.reading && !state.flowing && !state.ended &&
440          state.length < state.highWaterMark) {
441     debug('maybeReadMore read 0');
442     stream.read(0);
443     if (len === state.length)
444       // didn't get any data, stop spinning.
445       break;
446     else
447       len = state.length;
448   }
449   state.readingMore = false;
450 }
451
452 // abstract method.  to be overridden in specific implementation classes.
453 // call cb(er, data) where data is <= n in length.
454 // for virtual (non-string, non-buffer) streams, "length" is somewhat
455 // arbitrary, and perhaps not very meaningful.
456 Readable.prototype._read = function(n) {
457   this.emit('error', new Error('not implemented'));
458 };
459
460 Readable.prototype.pipe = function(dest, pipeOpts) {
461   var src = this;
462   var state = this._readableState;
463
464   switch (state.pipesCount) {
465     case 0:
466       state.pipes = dest;
467       break;
468     case 1:
469       state.pipes = [state.pipes, dest];
470       break;
471     default:
472       state.pipes.push(dest);
473       break;
474   }
475   state.pipesCount += 1;
476   debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
477
478   var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
479               dest !== process.stdout &&
480               dest !== process.stderr;
481
482   var endFn = doEnd ? onend : cleanup;
483   if (state.endEmitted)
484     process.nextTick(endFn);
485   else
486     src.once('end', endFn);
487
488   dest.on('unpipe', onunpipe);
489   function onunpipe(readable) {
490     debug('onunpipe');
491     if (readable === src) {
492       cleanup();
493     }
494   }
495
496   function onend() {
497     debug('onend');
498     dest.end();
499   }
500
501   // when the dest drains, it reduces the awaitDrain counter
502   // on the source.  This would be more elegant with a .once()
503   // handler in flow(), but adding and removing repeatedly is
504   // too slow.
505   var ondrain = pipeOnDrain(src);
506   dest.on('drain', ondrain);
507
508   function cleanup() {
509     debug('cleanup');
510     // cleanup event handlers once the pipe is broken
511     dest.removeListener('close', onclose);
512     dest.removeListener('finish', onfinish);
513     dest.removeListener('drain', ondrain);
514     dest.removeListener('error', onerror);
515     dest.removeListener('unpipe', onunpipe);
516     src.removeListener('end', onend);
517     src.removeListener('end', cleanup);
518     src.removeListener('data', ondata);
519
520     // if the reader is waiting for a drain event from this
521     // specific writer, then it would cause it to never start
522     // flowing again.
523     // So, if this is awaiting a drain, then we just call it now.
524     // If we don't know, then assume that we are waiting for one.
525     if (state.awaitDrain &&
526         (!dest._writableState || dest._writableState.needDrain))
527       ondrain();
528   }
529
530   src.on('data', ondata);
531   function ondata(chunk) {
532     debug('ondata');
533     var ret = dest.write(chunk);
534     if (false === ret) {
535       debug('false write response, pause',
536             src._readableState.awaitDrain);
537       src._readableState.awaitDrain++;
538       src.pause();
539     }
540   }
541
542   // if the dest has an error, then stop piping into it.
543   // however, don't suppress the throwing behavior for this.
544   function onerror(er) {
545     debug('onerror', er);
546     unpipe();
547     dest.removeListener('error', onerror);
548     if (EE.listenerCount(dest, 'error') === 0)
549       dest.emit('error', er);
550   }
551   // This is a brutally ugly hack to make sure that our error handler
552   // is attached before any userland ones.  NEVER DO THIS.
553   if (!dest._events.error)
554     dest.on('error', onerror);
555   else if (Array.isArray(dest._events.error))
556     dest._events.error.unshift(onerror);
557   else
558     dest._events.error = [onerror, dest._events.error];
559
560
561
562   // Both close and finish should trigger unpipe, but only once.
563   function onclose() {
564     dest.removeListener('finish', onfinish);
565     unpipe();
566   }
567   dest.once('close', onclose);
568   function onfinish() {
569     debug('onfinish');
570     dest.removeListener('close', onclose);
571     unpipe();
572   }
573   dest.once('finish', onfinish);
574
575   function unpipe() {
576     debug('unpipe');
577     src.unpipe(dest);
578   }
579
580   // tell the dest that it's being piped to
581   dest.emit('pipe', src);
582
583   // start the flow if it hasn't been started already.
584   if (!state.flowing) {
585     debug('pipe resume');
586     src.resume();
587   }
588
589   return dest;
590 };
591
592 function pipeOnDrain(src) {
593   return function() {
594     var state = src._readableState;
595     debug('pipeOnDrain', state.awaitDrain);
596     if (state.awaitDrain)
597       state.awaitDrain--;
598     if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
599       state.flowing = true;
600       flow(src);
601     }
602   };
603 }
604
605
606 Readable.prototype.unpipe = function(dest) {
607   var state = this._readableState;
608
609   // if we're not piping anywhere, then do nothing.
610   if (state.pipesCount === 0)
611     return this;
612
613   // just one destination.  most common case.
614   if (state.pipesCount === 1) {
615     // passed in one, but it's not the right one.
616     if (dest && dest !== state.pipes)
617       return this;
618
619     if (!dest)
620       dest = state.pipes;
621
622     // got a match.
623     state.pipes = null;
624     state.pipesCount = 0;
625     state.flowing = false;
626     if (dest)
627       dest.emit('unpipe', this);
628     return this;
629   }
630
631   // slow case. multiple pipe destinations.
632
633   if (!dest) {
634     // remove all.
635     var dests = state.pipes;
636     var len = state.pipesCount;
637     state.pipes = null;
638     state.pipesCount = 0;
639     state.flowing = false;
640
641     for (var i = 0; i < len; i++)
642       dests[i].emit('unpipe', this);
643     return this;
644   }
645
646   // try to find the right one.
647   var i = state.pipes.indexOf(dest);
648   if (i === -1)
649     return this;
650
651   state.pipes.splice(i, 1);
652   state.pipesCount -= 1;
653   if (state.pipesCount === 1)
654     state.pipes = state.pipes[0];
655
656   dest.emit('unpipe', this);
657
658   return this;
659 };
660
661 // set up data events if they are asked for
662 // Ensure readable listeners eventually get something
663 Readable.prototype.on = function(ev, fn) {
664   var res = Stream.prototype.on.call(this, ev, fn);
665
666   // If listening to data, and it has not explicitly been paused,
667   // then call resume to start the flow of data on the next tick.
668   if (ev === 'data' && false !== this._readableState.flowing) {
669     this.resume();
670   }
671
672   if (ev === 'readable' && this.readable) {
673     var state = this._readableState;
674     if (!state.readableListening) {
675       state.readableListening = true;
676       state.emittedReadable = false;
677       state.needReadable = true;
678       if (!state.reading) {
679         var self = this;
680         process.nextTick(function() {
681           debug('readable nexttick read 0');
682           self.read(0);
683         });
684       } else if (state.length) {
685         emitReadable(this, state);
686       }
687     }
688   }
689
690   return res;
691 };
692 Readable.prototype.addListener = Readable.prototype.on;
693
694 // pause() and resume() are remnants of the legacy readable stream API
695 // If the user uses them, then switch into old mode.
696 Readable.prototype.resume = function() {
697   var state = this._readableState;
698   if (!state.flowing) {
699     debug('resume');
700     state.flowing = true;
701     if (!state.reading) {
702       debug('resume read 0');
703       this.read(0);
704     }
705     resume(this, state);
706   }
707 };
708
709 function resume(stream, state) {
710   if (!state.resumeScheduled) {
711     state.resumeScheduled = true;
712     process.nextTick(function() {
713       resume_(stream, state);
714     });
715   }
716 }
717
718 function resume_(stream, state) {
719   state.resumeScheduled = false;
720   stream.emit('resume');
721   flow(stream);
722   if (state.flowing && !state.reading)
723     stream.read(0);
724 }
725
726 Readable.prototype.pause = function() {
727   debug('call pause flowing=%j', this._readableState.flowing);
728   if (false !== this._readableState.flowing) {
729     debug('pause');
730     this._readableState.flowing = false;
731     this.emit('pause');
732   }
733 };
734
735 function flow(stream) {
736   var state = stream._readableState;
737   debug('flow', state.flowing);
738   if (state.flowing) {
739     do {
740       var chunk = stream.read();
741     } while (null !== chunk && state.flowing);
742   }
743 }
744
745 // wrap an old-style stream as the async data source.
746 // This is *not* part of the readable stream interface.
747 // It is an ugly unfortunate mess of history.
748 Readable.prototype.wrap = function(stream) {
749   var state = this._readableState;
750   var paused = false;
751
752   var self = this;
753   stream.on('end', function() {
754     debug('wrapped end');
755     if (state.decoder && !state.ended) {
756       var chunk = state.decoder.end();
757       if (chunk && chunk.length)
758         self.push(chunk);
759     }
760
761     self.push(null);
762   });
763
764   stream.on('data', function(chunk) {
765     debug('wrapped data');
766     if (state.decoder)
767       chunk = state.decoder.write(chunk);
768     if (!chunk || !state.objectMode && !chunk.length)
769       return;
770
771     var ret = self.push(chunk);
772     if (!ret) {
773       paused = true;
774       stream.pause();
775     }
776   });
777
778   // proxy all the other methods.
779   // important when wrapping filters and duplexes.
780   for (var i in stream) {
781     if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
782       this[i] = function(method) { return function() {
783         return stream[method].apply(stream, arguments);
784       }}(i);
785     }
786   }
787
788   // proxy certain important events.
789   var events = ['error', 'close', 'destroy', 'pause', 'resume'];
790   events.forEach(function(ev) {
791     stream.on(ev, self.emit.bind(self, ev));
792   });
793
794   // when we try to consume some more bytes, simply unpause the
795   // underlying stream.
796   self._read = function(n) {
797     debug('wrapped _read', n);
798     if (paused) {
799       paused = false;
800       stream.resume();
801     }
802   };
803
804   return self;
805 };
806
807
808
809 // exposed for testing purposes only.
810 Readable._fromList = fromList;
811
812 // Pluck off n bytes from an array of buffers.
813 // Length is the combined lengths of all the buffers in the list.
814 function fromList(n, state) {
815   var list = state.buffer;
816   var length = state.length;
817   var stringMode = !!state.decoder;
818   var objectMode = !!state.objectMode;
819   var ret;
820
821   // nothing in the list, definitely empty.
822   if (list.length === 0)
823     return null;
824
825   if (length === 0)
826     ret = null;
827   else if (objectMode)
828     ret = list.shift();
829   else if (!n || n >= length) {
830     // read it all, truncate the array.
831     if (stringMode)
832       ret = list.join('');
833     else
834       ret = Buffer.concat(list, length);
835     list.length = 0;
836   } else {
837     // read just some of it.
838     if (n < list[0].length) {
839       // just take a part of the first list item.
840       // slice is the same for buffers and strings.
841       var buf = list[0];
842       ret = buf.slice(0, n);
843       list[0] = buf.slice(n);
844     } else if (n === list[0].length) {
845       // first list is a perfect match
846       ret = list.shift();
847     } else {
848       // complex case.
849       // we have enough to cover it, but it spans past the first buffer.
850       if (stringMode)
851         ret = '';
852       else
853         ret = new Buffer(n);
854
855       var c = 0;
856       for (var i = 0, l = list.length; i < l && c < n; i++) {
857         var buf = list[0];
858         var cpy = Math.min(n - c, buf.length);
859
860         if (stringMode)
861           ret += buf.slice(0, cpy);
862         else
863           buf.copy(ret, c, 0, cpy);
864
865         if (cpy < buf.length)
866           list[0] = buf.slice(cpy);
867         else
868           list.shift();
869
870         c += cpy;
871       }
872     }
873   }
874
875   return ret;
876 }
877
878 function endReadable(stream) {
879   var state = stream._readableState;
880
881   // If we get here before consuming all the bytes, then that is a
882   // bug in node.  Should never happen.
883   if (state.length > 0)
884     throw new Error('endReadable called on non-empty stream');
885
886   if (!state.endEmitted) {
887     state.ended = true;
888     process.nextTick(function() {
889       // Check that we didn't get one last unshift.
890       if (!state.endEmitted && state.length === 0) {
891         state.endEmitted = true;
892         stream.readable = false;
893         stream.emit('end');
894       }
895     });
896   }
897 }