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

Commit

Permalink
reclaim receive buffer space when more than maxFrameSize is free
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
vcabbage committed Nov 27, 2019
1 parent 0dbbfb4 commit 86a6a19
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
15 changes: 14 additions & 1 deletion buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ func (b *buffer) reset() {
b.i = 0
}

// reclaim shifts used buffer space to the beginning of the
// underlying slice.
func (b *buffer) reclaim() {
l := b.len()
copy(b.b[:l], b.b[b.i:])
b.b = b.b[:l]
b.i = 0
}

func (b *buffer) readCheck(n int64) bool {
return int64(b.i)+n > int64(len(b.b))
}
Expand Down Expand Up @@ -94,7 +103,11 @@ func (b *buffer) readFromOnce(r io.Reader) error {

l := len(b.b)
if cap(b.b)-l < minRead {
new := make([]byte, l, l+minRead)
total := l * 2
if total == 0 {
total = minRead
}
new := make([]byte, l, total)
copy(new, b.b)
b.b = new
}
Expand Down
8 changes: 7 additions & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,14 @@ func (c *conn) connReader() {
)

for {
if buf.len() == 0 {
switch {
// Cheaply reuse free buffer space when fully read.
case buf.len() == 0:
buf.reset()

// Prevent excessive/unbounded growth by shifting data to beginning of buffer.
case int64(buf.i) > int64(c.maxFrameSize):
buf.reclaim()
}

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

0 comments on commit 86a6a19

Please sign in to comment.