-
-
Notifications
You must be signed in to change notification settings - Fork 299
/
file_reader_unix.go
84 lines (75 loc) · 1.57 KB
/
file_reader_unix.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
//go:build unix
package term
import (
"io"
"os"
"sync"
"syscall"
"time"
"src.elv.sh/pkg/sys/eunix"
)
// A helper for reading from a file.
type fileReader interface {
byteReaderWithTimeout
// Stop stops any outstanding read call. It blocks until the read returns.
Stop() error
// Close releases new resources allocated for the fileReader. It does not
// close the underlying file.
Close()
}
func newFileReader(file *os.File) (fileReader, error) {
rStop, wStop, err := os.Pipe()
if err != nil {
return nil, err
}
return &bReader{file: file, rStop: rStop, wStop: wStop}, nil
}
type bReader struct {
file *os.File
rStop *os.File
wStop *os.File
// A mutex that is held when Read is in process.
mutex sync.Mutex
}
func (r *bReader) ReadByteWithTimeout(timeout time.Duration) (byte, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
for {
ready, err := eunix.WaitForRead(timeout, r.file, r.rStop)
if err != nil {
if err == syscall.EINTR {
continue
}
return 0, err
}
if ready[1] {
var b [1]byte
r.rStop.Read(b[:])
return 0, ErrStopped
}
if !ready[0] {
return 0, errTimeout
}
var b [1]byte
nr, err := r.file.Read(b[:])
if err != nil {
return 0, err
}
if nr != 1 {
return 0, io.ErrNoProgress
}
return b[0], nil
}
}
func (r *bReader) Stop() error {
_, err := r.wStop.Write([]byte{'q'})
r.mutex.Lock()
//lint:ignore SA2001 We only lock the mutex to make sure that
// ReadByteWithTimeout has exited, so we unlock it immediately.
r.mutex.Unlock()
return err
}
func (r *bReader) Close() {
r.rStop.Close()
r.wStop.Close()
}