sync-reader.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. let 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. let read = this._reads[0];
  17. if (
  18. this._buffer.length &&
  19. (this._buffer.length >= read.length || read.allowLess)
  20. ) {
  21. // ok there is any data so that we can satisfy this request
  22. this._reads.shift(); // == read
  23. let buf = this._buffer;
  24. this._buffer = buf.slice(read.length);
  25. read.func.call(this, buf.slice(0, read.length));
  26. } else {
  27. break;
  28. }
  29. }
  30. if (this._reads.length > 0) {
  31. return new Error("There are some read requests waitng on finished stream");
  32. }
  33. if (this._buffer.length > 0) {
  34. return new Error("unrecognised content at end of stream");
  35. }
  36. };