Initial commit
[yaffs-website] / node_modules / glob-stream / node_modules / readable-stream / lib / _stream_transform.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
23 // a transform stream is a readable/writable stream where you do
24 // something with the data.  Sometimes it's called a "filter",
25 // but that's not a great name for it, since that implies a thing where
26 // some bits pass through, and others are simply ignored.  (That would
27 // be a valid example of a transform, of course.)
28 //
29 // While the output is causally related to the input, it's not a
30 // necessarily symmetric or synchronous transformation.  For example,
31 // a zlib stream might take multiple plain-text writes(), and then
32 // emit a single compressed chunk some time in the future.
33 //
34 // Here's how this works:
35 //
36 // The Transform stream has all the aspects of the readable and writable
37 // stream classes.  When you write(chunk), that calls _write(chunk,cb)
38 // internally, and returns false if there's a lot of pending writes
39 // buffered up.  When you call read(), that calls _read(n) until
40 // there's enough pending readable data buffered up.
41 //
42 // In a transform stream, the written data is placed in a buffer.  When
43 // _read(n) is called, it transforms the queued up data, calling the
44 // buffered _write cb's as it consumes chunks.  If consuming a single
45 // written chunk would result in multiple output chunks, then the first
46 // outputted bit calls the readcb, and subsequent chunks just go into
47 // the read buffer, and will cause it to emit 'readable' if necessary.
48 //
49 // This way, back-pressure is actually determined by the reading side,
50 // since _read has to be called to start processing a new chunk.  However,
51 // a pathological inflate type of transform can cause excessive buffering
52 // here.  For example, imagine a stream where every byte of input is
53 // interpreted as an integer from 0-255, and then results in that many
54 // bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
55 // 1kb of data being output.  In this case, you could write a very small
56 // amount of input, and end up with a very large amount of output.  In
57 // such a pathological inflating mechanism, there'd be no way to tell
58 // the system to stop doing the transform.  A single 4MB write could
59 // cause the system to run out of memory.
60 //
61 // However, even in such a pathological case, only a single written chunk
62 // would be consumed, and then the rest would wait (un-transformed) until
63 // the results of the previous transformed chunk were consumed.
64
65 module.exports = Transform;
66
67 var Duplex = require('./_stream_duplex');
68
69 /*<replacement>*/
70 var util = require('core-util-is');
71 util.inherits = require('inherits');
72 /*</replacement>*/
73
74 util.inherits(Transform, Duplex);
75
76
77 function TransformState(options, stream) {
78   this.afterTransform = function(er, data) {
79     return afterTransform(stream, er, data);
80   };
81
82   this.needTransform = false;
83   this.transforming = false;
84   this.writecb = null;
85   this.writechunk = null;
86 }
87
88 function afterTransform(stream, er, data) {
89   var ts = stream._transformState;
90   ts.transforming = false;
91
92   var cb = ts.writecb;
93
94   if (!cb)
95     return stream.emit('error', new Error('no writecb in Transform class'));
96
97   ts.writechunk = null;
98   ts.writecb = null;
99
100   if (data !== null && data !== undefined)
101     stream.push(data);
102
103   if (cb)
104     cb(er);
105
106   var rs = stream._readableState;
107   rs.reading = false;
108   if (rs.needReadable || rs.length < rs.highWaterMark) {
109     stream._read(rs.highWaterMark);
110   }
111 }
112
113
114 function Transform(options) {
115   if (!(this instanceof Transform))
116     return new Transform(options);
117
118   Duplex.call(this, options);
119
120   var ts = this._transformState = new TransformState(options, this);
121
122   // when the writable side finishes, then flush out anything remaining.
123   var stream = this;
124
125   // start out asking for a readable event once data is transformed.
126   this._readableState.needReadable = true;
127
128   // we have implemented the _read method, and done the other things
129   // that Readable wants before the first _read call, so unset the
130   // sync guard flag.
131   this._readableState.sync = false;
132
133   this.once('finish', function() {
134     if ('function' === typeof this._flush)
135       this._flush(function(er) {
136         done(stream, er);
137       });
138     else
139       done(stream);
140   });
141 }
142
143 Transform.prototype.push = function(chunk, encoding) {
144   this._transformState.needTransform = false;
145   return Duplex.prototype.push.call(this, chunk, encoding);
146 };
147
148 // This is the part where you do stuff!
149 // override this function in implementation classes.
150 // 'chunk' is an input chunk.
151 //
152 // Call `push(newChunk)` to pass along transformed output
153 // to the readable side.  You may call 'push' zero or more times.
154 //
155 // Call `cb(err)` when you are done with this chunk.  If you pass
156 // an error, then that'll put the hurt on the whole operation.  If you
157 // never call cb(), then you'll never get another chunk.
158 Transform.prototype._transform = function(chunk, encoding, cb) {
159   throw new Error('not implemented');
160 };
161
162 Transform.prototype._write = function(chunk, encoding, cb) {
163   var ts = this._transformState;
164   ts.writecb = cb;
165   ts.writechunk = chunk;
166   ts.writeencoding = encoding;
167   if (!ts.transforming) {
168     var rs = this._readableState;
169     if (ts.needTransform ||
170         rs.needReadable ||
171         rs.length < rs.highWaterMark)
172       this._read(rs.highWaterMark);
173   }
174 };
175
176 // Doesn't matter what the args are here.
177 // _transform does all the work.
178 // That we got here means that the readable side wants more data.
179 Transform.prototype._read = function(n) {
180   var ts = this._transformState;
181
182   if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
183     ts.transforming = true;
184     this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
185   } else {
186     // mark that we need a transform, so that any data that comes in
187     // will get processed, now that we've asked for it.
188     ts.needTransform = true;
189   }
190 };
191
192
193 function done(stream, er) {
194   if (er)
195     return stream.emit('error', er);
196
197   // if there's nothing in the write buffer, then that means
198   // that nothing more will ever be provided
199   var ws = stream._writableState;
200   var rs = stream._readableState;
201   var ts = stream._transformState;
202
203   if (ws.length)
204     throw new Error('calling transform done when ws.length != 0');
205
206   if (ts.transforming)
207     throw new Error('calling transform done when still transforming');
208
209   return stream.push(null);
210 }