Skip to content
This repository was archived by the owner on Dec 14, 2020. It is now read-only.

Commit 86a6a19

Browse files
committed
reclaim receive buffer space when more than maxFrameSize is free
* Prevents unbounded buffer growth when more than one frame is read into the buffer. * Change buffer to grow by 2x rather than 512 bytes. Updates #191
1 parent 0dbbfb4 commit 86a6a19

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

buffer.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@ func (b *buffer) reset() {
3232
b.i = 0
3333
}
3434

35+
// reclaim shifts used buffer space to the beginning of the
36+
// underlying slice.
37+
func (b *buffer) reclaim() {
38+
l := b.len()
39+
copy(b.b[:l], b.b[b.i:])
40+
b.b = b.b[:l]
41+
b.i = 0
42+
}
43+
3544
func (b *buffer) readCheck(n int64) bool {
3645
return int64(b.i)+n > int64(len(b.b))
3746
}
@@ -94,7 +103,11 @@ func (b *buffer) readFromOnce(r io.Reader) error {
94103

95104
l := len(b.b)
96105
if cap(b.b)-l < minRead {
97-
new := make([]byte, l, l+minRead)
106+
total := l * 2
107+
if total == 0 {
108+
total = minRead
109+
}
110+
new := make([]byte, l, total)
98111
copy(new, b.b)
99112
b.b = new
100113
}

conn.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,8 +446,14 @@ func (c *conn) connReader() {
446446
)
447447

448448
for {
449-
if buf.len() == 0 {
449+
switch {
450+
// Cheaply reuse free buffer space when fully read.
451+
case buf.len() == 0:
450452
buf.reset()
453+
454+
// Prevent excessive/unbounded growth by shifting data to beginning of buffer.
455+
case int64(buf.i) > int64(c.maxFrameSize):
456+
buf.reclaim()
451457
}
452458

453459
// need to read more if buf doesn't contain the complete frame

0 commit comments

Comments
 (0)