sync-reader.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. var SyncReader = module.exports = function(buffer) {
  3. this._buffer = buffer;
  4. this._reads = [];
  5. };
  6. SyncReader.prototype.read = function(length, callback) {
  7. this._reads.push({
  8. length: Math.abs(length), // if length < 0 then at most this length
  9. allowLess: length < 0,
  10. func: callback
  11. });
  12. };
  13. SyncReader.prototype.process = function() {
  14. // as long as there is any data and read requests
  15. while (this._reads.length > 0 && this._buffer.length) {
  16. var read = this._reads[0];
  17. if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
  18. // ok there is any data so that we can satisfy this request
  19. this._reads.shift(); // == read
  20. var buf = this._buffer;
  21. this._buffer = buf.slice(read.length);
  22. read.func.call(this, buf.slice(0, read.length));
  23. }
  24. else {
  25. break;
  26. }
  27. }
  28. if (this._reads.length > 0) {
  29. return new Error('There are some read requests waitng on finished stream');
  30. }
  31. if (this._buffer.length > 0) {
  32. return new Error('unrecognised content at end of stream');
  33. }
  34. };