Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Last active December 31, 2015 04:59
Show Gist options
  • Save piscisaureus/7938154 to your computer and use it in GitHub Desktop.
Save piscisaureus/7938154 to your computer and use it in GitHub Desktop.
w3streams.txt
class Stream {
// Resolves with an ArrayBuffer or null.
// If max_bytes is unspecified, the maximum amount is implementation-dependent.
Promise read([uint max_bytes]);
// Resolves with a number of bytes read or null.
Promise readInto(ArrayBufferView dest);
// Open for debate. I don't think it's necessary.
// Resolves whenever there is data available for reading.
Promise readPoll();
// Questionable. The obvious semantic would be equivalent to BSD-sockets
// `shutdown(fd, SHUT_RD)` but there are no existing protocols for which
// this has any purpose.
// Alternatively it could be similar to Dart's `drain()` function. E.g.
// consume and discard all incoming data until the producer signals that there
// is no more incoming data, which would allow for graceful close.
Promise readClose();
// Resolves with no value (or maybe the number of bytes written)
Promise write(ArrayBufferView data);
// Open for debate. I don't think it's necessary.
// Resolves whenever there is room in the write buffer, e.g.
// a write (of 1 byte) could complete immediately.
Promise writePoll();
// Resolves with no value. Signal that no more data will be written.
// In case of TCP this puts a FIN packet on the wire.
Promise writeClose();
// Resolves with no value. Gracefully close a stream, e.g. writeClose
// and readClose as needed.
Promise close();
// Unfallible. Possible reason phrases are implementation-defined.
void abort([reason]);
// State of the read end and write end.
// * connecting (or opening?)
// * open
// * closing
// * error
// * aborted (questionable, this is an error state)
// * closed
String readState;
String writeState;
}
@piscisaureus
Copy link
Author

I would argue that the .pipe() method could be specified to do this:

Stream.prototype.pipe = function(dest, close) {
  var src = this;
  spawn(function*() {
    var data;
    try {
      while (yield* data = src.read())
        dest.write(data);
      if (close === undefined || close)
        yield* dest.writeClose();
    } catch (e) {
      dest.abort(e);
    }
  });
  return dest;
};

@bajtos
Copy link

bajtos commented Apr 18, 2014

@piscisaureus your pipe implementation does not handle back pressure. It shouldn't be difficult to add though:

var data;
while (yield* data = src.read()) {
  dest.write(data);
  yield* dest.writePoll();
}

To make it even simpler for implementators, write can handle the back pressure by blocking when the buffer is full:

var data;
while (yield* data = src.read()) {
  yield* dest.write(data);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment