-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstdinBuffer.js
40 lines (36 loc) · 1.07 KB
/
stdinBuffer.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
import {parentPort} from "worker_threads"
class StdinBuffer {
constructor() {
this.sab = new SharedArrayBuffer(128 * Int32Array.BYTES_PER_ELEMENT)
this.buffer = new Int32Array(this.sab)
this.readIndex = 1;
this.numberOfCharacters = 0;
this.sentNull = true
}
prompt() {
this.readIndex = 1
Atomics.store(this.buffer, 0, -1)
parentPort.postMessage({
type: 'stdin',
buffer: this.sab
})
Atomics.wait(this.buffer, 0, -1)
this.numberOfCharacters = this.buffer[0]
}
stdin = () => {
if (this.numberOfCharacters + 1 === this.readIndex) {
if (!this.sentNull) {
// Must return null once to indicate we're done for now.
this.sentNull = true
return null
}
this.sentNull = false
this.prompt()
}
const char = this.buffer[this.readIndex]
this.readIndex += 1
// How do I send an EOF??
return char
}
}
export default StdinBuffer