-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcancel_reader.go
77 lines (67 loc) · 1.51 KB
/
cancel_reader.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
package ioutil
import (
"context"
"fmt"
"io"
"strconv"
)
// CancelableReader позволяет читать данные с контекстом
type CancelableReader struct {
ctx context.Context
data chan []byte
// размер сообщения, которое мы хотим получить. пока в sizeWant не пошлется длина, ридер не будет читать
sizeWant chan int
err error
r io.Reader
}
func (c *CancelableReader) begin() {
for {
sizewant := <-c.sizeWant
buf := make([]byte, sizewant)
// readFull, cause some readers like net.TCPConn returns size smaller than buf size
n, err := io.ReadFull(c.r, buf)
if err != nil {
c.err = err
close(c.data)
return
}
if n != sizewant {
panic("read " + strconv.Itoa(n) + ", want " + strconv.Itoa(sizewant))
}
c.data <- buf
}
}
func (c *CancelableReader) Read(p []byte) (int, error) {
c.sizeWant <- len(p)
select {
case <-c.ctx.Done():
return 0, c.ctx.Err()
case d, ok := <-c.data:
if !ok {
return 0, c.err
}
copy(p, d)
return len(d), nil
}
}
func (c *CancelableReader) ReadByte() (byte, error) {
b := make([]byte, 1)
n, err := c.Read(b)
if err != nil {
return 0x0, err
}
if n != 1 {
panic(fmt.Errorf("read more than 1 byte, got %v", n))
}
return b[0], nil
}
func NewCancelableReader(ctx context.Context, r io.Reader) *CancelableReader {
c := &CancelableReader{
r: r,
ctx: ctx,
data: make(chan []byte),
sizeWant: make(chan int),
}
go c.begin()
return c
}