forked from scramjetorg/rereadable-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (87 loc) · 3.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const {Writable, Readable} = require("stream");
const {EventEmitter} = require("events");
class ReReadable extends Writable {
constructor(options) {
options = Object.assign({
length: 1048576,
highWaterMark: 32,
dropInterval: 1e3
}, options);
super(options);
this._readableOptions = options;
this._highWaterMark = options.highWaterMark;
this._bufArrLength = options.length;
this._reading = 0;
this._bufArr = [];
this.hiBufCr = 0;
this.loBufCr = 0;
this._waiting = null;
this._ended = new Promise((res) => this.on("finish", res));
}
_write(chunk, encoding, callback) {
this._bufArr.push([chunk, encoding]);
if (this._bufArr.length > this._bufArrLength) {
this._waiting = callback;
this.drop();
} else {
callback();
}
this.emit("wrote");
}
_writev(chunks, callback) {
this._bufArr.push(...chunks.map(({chunk, encoding}) => [chunk, encoding]));
if (this._bufArr.length > this._bufArrLength) {
this._waiting = callback;
this.drop();
} else {
callback();
}
this.emit("wrote");
}
updateBufPosition(bufCr) {
this.hiBufCr = bufCr > this.hiBufCr ? bufCr : this.hiBufCr;
this.loBufCr = bufCr > this.loBufCr ? bufCr : this.loBufCr;
if (this._waiting && this.hiBufCr >= this._bufArrLength - this._highWaterMark) {
const cb = this._waiting;
this._waiting = null;
cb();
}
}
drop() {
if (this._bufArr.length > this._bufArrLength)
this.emit("drop", this._bufArr.splice(0, this._bufArr.length - this._bufArrLength).length);
}
rewind() {
return this.tail(-1);
}
tail(count) {
let end = false;
this._ended.then(() => ret._read(end = true));
this.setMaxListeners(++this._reading + EventEmitter.defaultMaxListeners);
const ret = new Readable(Object.assign(this._readableOptions, {
read: () => {
if (ret.bufCr < this._bufArr.length) {
while(ret.bufCr < this._bufArr.length) { // while there's anything to read
const resp = ret.push(...this._bufArr[ret.bufCr++]); // push to readable
if (!resp && !end) break; // until there's not willing to read and we're not ended
}
this.updateBufPosition(ret.bufCr);
} else if (!end) {
this.once("wrote", ret._read);
}
if (end)
ret.push(null);
}
}));
ret.bufCr = count < this._bufArr.length && count > 0 ? this._bufArr.length - count : 0;
this.on("drop", (count) => {
ret.bufCr -= count;
if (ret.bufCr < 0) {
ret.emit("drop", -ret.bufCr);
ret.bufCr = 0;
}
});
return ret;
}
}
module.exports = {ReReadable};