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