forked from OpenEngineer/go-repl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdinreader.go
91 lines (70 loc) · 1.53 KB
/
stdinreader.go
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
package repl
import (
"bufio"
"os"
"sync"
"time"
)
// This is a cut-off time for grouping auto-generated escape sequences.
const MACHINE_INTERVAL = time.Millisecond
// _StdinReader collects inputs and keeps sequences of auto-generated bytes together as a group (eg. ansi escape sequences)
type _StdinReader struct {
reader *bufio.Reader
lastTime time.Time
buffer []byte
lock *sync.Mutex
bytes chan []byte
}
func newStdinReader() *_StdinReader {
return &_StdinReader{
reader: nil,
lastTime: time.Time{},
buffer: make([]byte, 0),
lock: &sync.Mutex{},
bytes: make(chan []byte),
}
}
func (r *_StdinReader) start() {
go func() {
for {
<-time.After(MACHINE_INTERVAL)
r.lock.Lock()
if len(r.buffer) > 0 {
if time.Now().After(r.lastTime.Add(MACHINE_INTERVAL)) {
msg := r.buffer
r.buffer = make([]byte, 0)
r.bytes <- msg
}
}
r.lock.Unlock()
}
}()
}
func (r *_StdinReader) read() {
if r.reader != nil {
return
}
r.reader = bufio.NewReader(os.Stdin)
r.lastTime = time.Now()
go func() {
for {
b, err := r.reader.ReadByte()
if err != nil {
panic(err)
}
stopNow := false
if b == 13 && time.Now().After(r.lastTime.Add(MACHINE_INTERVAL)) {
// it is unlikely that a carriage return followed by some text is pasted into the terminal, so we can use this as a queu to quit
stopNow = true
}
r.lastTime = time.Now()
r.lock.Lock()
r.buffer = append(r.buffer, b)
r.lock.Unlock()
if stopNow {
r.reader = nil
return
}
}
}()
}