forked from pubnative/mysqlproto-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.go
119 lines (96 loc) · 2.06 KB
/
stream.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
114
115
116
117
118
119
package mysqlproto
import (
"bytes"
"io"
)
const PACKET_BUFFER_SIZE = 1500 // default MTU
type Stream struct {
stream io.ReadWriteCloser
buffer []byte
read int
left int
syscalls int
}
func NewStream(stream io.ReadWriteCloser) *Stream {
return &Stream{stream, nil, 0, 0, 0}
}
func (s *Stream) Write(data []byte) (int, error) {
return s.stream.Write(data)
}
func (s *Stream) Close() error {
return s.stream.Close()
}
func (s *Stream) NextPacket() (Packet, error) {
scale := func(size int) {
if size < PACKET_BUFFER_SIZE {
size = PACKET_BUFFER_SIZE
}
buf := make([]byte, size)
copy(buf, s.buffer[s.read:s.read+s.left])
s.buffer = buf
s.read = 0
}
if len(s.buffer)-s.read < 3 { // size of the packet
scale(PACKET_BUFFER_SIZE)
}
if s.left < 3 {
read, err := s.readAtLeast(s.buffer[s.read+s.left:], 3-s.left)
if err != nil {
return Packet{}, err
}
s.left += read
}
length := int(uint32(s.buffer[s.read]) | uint32(s.buffer[s.read+1])<<8 | uint32(s.buffer[s.read+2])<<16)
total := length + 4
if total > len(s.buffer)-s.read {
scale(total)
}
if total > s.left {
read, err := s.readAtLeast(s.buffer[s.read+s.left:], total-s.left)
if err != nil {
return Packet{}, err
}
s.left += read
}
packet := Packet{
SequenceID: s.buffer[s.read+3],
Payload: s.buffer[s.read+4 : s.read+total],
}
s.left -= total
s.read += total
return packet, nil
}
func (s *Stream) Syscalls() int {
return s.syscalls
}
func (s *Stream) ResetStats() {
s.syscalls = 0
}
func (s *Stream) readAtLeast(buf []byte, min int) (n int, err error) {
for n < min && err == nil {
var nn int
nn, err = s.stream.Read(buf[n:])
s.syscalls += 1
n += nn
}
return
}
// For testing
type buffer struct {
*bytes.Buffer
closed bool
writeFn func([]byte) (int, error)
}
func newBuffer(data []byte) *buffer {
return &buffer{bytes.NewBuffer(data), false, nil}
}
func (b *buffer) Close() error {
b.closed = true
return nil
}
func (b *buffer) Write(data []byte) (int, error) {
if b.writeFn == nil {
return 0, nil
}
return b.writeFn(data)
}