-
Notifications
You must be signed in to change notification settings - Fork 220
/
scan.go
65 lines (60 loc) · 1.38 KB
/
scan.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
package core
import (
"bufio"
"context"
"io"
)
// CancelableScanner is a scanner which also listens for the context cancellations and optionally pumps data between channels
type CancelableScanner struct {
*bufio.Scanner
data chan string
err chan error
ctx context.Context
}
// NewCancelableScanner creates a new CancelableScanner
func NewCancelableScanner(ctx context.Context, r io.Reader) *CancelableScanner {
return &CancelableScanner{
bufio.NewScanner(r),
make(chan string),
make(chan error),
ctx,
}
}
// Start stats the goroutine on the CancelableScanner and returns itself
func (s *CancelableScanner) Start() *CancelableScanner {
go func() {
for s.Scan() {
s.data <- s.Text()
}
if err := s.Err(); err != nil {
s.err <- err
}
close(s.data)
close(s.err)
}()
return s
}
// ReadOne reads one line from the started CancelableScanner, as well as listening to ctx.Done messages and optionally/continuously pumping *Jobs from the from<- chan to the to<- chan
func (s *CancelableScanner) ReadOne(from <-chan *Job, to chan<- *Job) (string, error) {
for {
select {
//case to <- <-from:
case j, ok := <-from:
if ok {
to <- j
}
case <-s.ctx.Done():
return "", context.Canceled
case str, ok := <-s.data:
if !ok {
return "", io.EOF
}
return str, nil
case err, ok := <-s.err:
if !ok {
return "", io.EOF
}
return "", err
}
}
}