-
Notifications
You must be signed in to change notification settings - Fork 61
/
reader.go
113 lines (96 loc) · 2.24 KB
/
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package qrpc
import (
"bufio"
"context"
"encoding/binary"
"io"
"net"
"sync"
"time"
)
// Reader read data from socket
type Reader struct {
conn net.Conn
reader *bufio.Reader
timeout int
ctx context.Context
}
const (
// ReadNoTimeout will never timeout
ReadNoTimeout = -1
// ReadBufSize for read buf
ReadBufSize = 1024
)
// NewReader creates a StreamReader instance
func NewReader(ctx context.Context, conn net.Conn) *Reader {
return NewReaderWithTimeout(ctx, conn, ReadNoTimeout)
}
var bufPool = sync.Pool{New: func() interface{} {
return bufio.NewReaderSize(nil, ReadBufSize)
}}
// NewReaderWithTimeout allows specify timeout
func NewReaderWithTimeout(ctx context.Context, conn net.Conn, timeout int) *Reader {
if ctx == nil {
ctx = context.Background()
}
bufReader := bufPool.Get().(*bufio.Reader)
bufReader.Reset(conn)
return &Reader{ctx: ctx, conn: conn, reader: bufReader, timeout: timeout}
}
// Finalize is called when no longer used
func (r *Reader) Finalize() {
r.reader.Reset(nil)
bufPool.Put(r.reader)
r.reader = nil
}
// SetReadTimeout allows modify timeout for read
func (r *Reader) SetReadTimeout(timeout int) {
r.timeout = timeout
}
// ReadUint32 read uint32 from socket
func (r *Reader) ReadUint32() (uint32, error) {
bytes := make([]byte, 4)
err := r.ReadBytes(bytes)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(bytes), nil
}
// ReadBytes read bytes with configured read timeout
func (r *Reader) ReadBytes(bytes []byte) error {
return r.ReadBytesWithMaxTimeout(bytes, 0)
}
// ReadBytesWithMaxTimeout read bytes honouring maxTimeoutSecond
func (r *Reader) ReadBytesWithMaxTimeout(bytes []byte, maxTimeoutSecond int) (err error) {
var (
endTime time.Time
offset int
n int
)
timeout := r.timeout
if maxTimeoutSecond > 0 && timeout > maxTimeoutSecond {
timeout = maxTimeoutSecond
}
if timeout > 0 {
endTime = time.Now().Add(time.Duration(timeout) * time.Second)
} else {
endTime = time.Time{}
}
size := len(bytes)
for {
r.conn.SetReadDeadline(endTime)
n, err = io.ReadFull(r.reader, bytes[offset:])
offset += n
if err != nil {
return err
}
if offset >= size {
return nil
}
select {
case <-r.ctx.Done():
return r.ctx.Err()
default:
}
}
}