stream.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* very simple input/output stream interface */
  2. var Stream = function() {
  3. };
  4. // input streams //////////////
  5. /** Returns the next byte, or -1 for EOF. */
  6. Stream.prototype.readByte = function() {
  7. throw new Error("abstract method readByte() not implemented");
  8. };
  9. /** Attempts to fill the buffer; returns number of bytes read, or
  10. * -1 for EOF. */
  11. Stream.prototype.read = function(buffer, bufOffset, length) {
  12. var bytesRead = 0;
  13. while (bytesRead < length) {
  14. var c = this.readByte();
  15. if (c < 0) { // EOF
  16. return (bytesRead===0) ? -1 : bytesRead;
  17. }
  18. buffer[bufOffset++] = c;
  19. bytesRead++;
  20. }
  21. return bytesRead;
  22. };
  23. Stream.prototype.seek = function(new_pos) {
  24. throw new Error("abstract method seek() not implemented");
  25. };
  26. // output streams ///////////
  27. Stream.prototype.writeByte = function(_byte) {
  28. throw new Error("abstract method readByte() not implemented");
  29. };
  30. Stream.prototype.write = function(buffer, bufOffset, length) {
  31. var i;
  32. for (i=0; i<length; i++) {
  33. this.writeByte(buffer[bufOffset++]);
  34. }
  35. return length;
  36. };
  37. Stream.prototype.flush = function() {
  38. };
  39. module.exports = Stream;