1 | "use strict";
|
2 |
|
3 | let SyncReader = (module.exports = function (buffer) {
|
4 | this._buffer = buffer;
|
5 | this._reads = [];
|
6 | });
|
7 |
|
8 | SyncReader.prototype.read = function (length, callback) {
|
9 | this._reads.push({
|
10 | length: Math.abs(length),
|
11 | allowLess: length < 0,
|
12 | func: callback,
|
13 | });
|
14 | };
|
15 |
|
16 | SyncReader.prototype.process = function () {
|
17 |
|
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 |
|
26 | this._reads.shift();
|
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 | };
|