forked from appgurueu/lustils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.js
107 lines (94 loc) · 1.96 KB
/
stream.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
class StringReader {
constructor(text) {
this.text = text;
this.cursor = 0;
}
read() {
return this.text.charAt(this.cursor++);
}
}
class BufferedReader {
constructor(input) {
this.buffer = new StringReader("");
this.input = input;
}
read() {
let c;
if (c = this.buffer.read()) {
return c;
}
this.buffer = new StringReader(this.input.read());
return this.read();
}
}
class StreamLocator {
constructor(stream) {
this.stream = stream;
this.row = 0;
this.col = 0;
}
read() {
let c = this.stream.read();
if (!c) {
return undefined;
}
if (c === "\n") {
this.row++;
this.col = 0;
} else {
this.col++;
}
return c;
}
skip(func) {
let c;
do {
c = this.read();
} while (c && func(c));
return c;
}
skipCounting(func) {
let count = 0;
let c;
do {
c = this.read();
count++;
} while (c && func(c));
return [count, c];
}
}
class StringBuilder {
constructor(text) {
this.text = text || "";
}
write(data) {
this.text += data;
}
}
class StringLengthCounter {
constructor() {
this.length = 0;
}
write(data) {
this.length += data.length;
}
}
function obtainInputStream(input) {
return new StreamLocator((typeof (input) === "string" && new StringReader(input)) || input);
}
function obtainOutputStream(output) {
return output || new StringBuilder();
}
function obtainStreams(input, output) {
return [obtainInputStream(input), obtainOutputStream(output)];
}
module.exports = {
StringReader,
StringBuilder,
BufferedReader,
StreamLocator,
StringLengthCounter,
obtainInputStream,
obtainOutputStream,
obtainStreams
};