UNPKG

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