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