-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend_buffer.go
61 lines (51 loc) · 1.01 KB
/
send_buffer.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
package utp_go
type sendBuffer struct {
pending [][]byte
offset int
size int
}
func newSendBuffer(size int) *sendBuffer {
return &sendBuffer{
pending: make([][]byte, 0),
offset: 0,
size: size,
}
}
func (sb *sendBuffer) Available() int {
used := 0
for _, data := range sb.pending {
used += len(data)
}
return sb.size + sb.offset - used
}
func (sb *sendBuffer) IsEmpty() bool {
return len(sb.pending) == 0
}
func (sb *sendBuffer) Write(data []byte) int {
available := sb.Available()
if len(data) <= available {
sb.pending = append(sb.pending, data)
return len(data)
} else {
sb.pending = append(sb.pending, data[:available])
return available
}
}
func (sb *sendBuffer) Read(buf []byte) int {
if len(buf) == 0 {
return 0
}
if len(sb.pending) == 0 {
return 0
}
data := sb.pending[0]
n := minInt(len(data)-sb.offset, len(buf))
copy(buf, data[sb.offset:sb.offset+n])
if sb.offset+n == len(data) {
sb.offset = 0
sb.pending = sb.pending[1:]
} else {
sb.offset += n
}
return n
}