Skip to content

buffer: Improve len(buf)==cap(buf) consistency #892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ type buffer struct {
}

func newBuffer(nc net.Conn) buffer {
var b [defaultBufSize]byte
return buffer{
buf: b[:],
buf: make([]byte, defaultBufSize),
nc: nc,
}
}
Expand Down Expand Up @@ -114,8 +113,7 @@ func (b *buffer) takeBuffer(length int) []byte {
return nil
}

// test (cheap) general case first
if length <= defaultBufSize || length <= cap(b.buf) {
if length <= len(b.buf) {
return b.buf[:length]
}

Expand Down Expand Up @@ -145,3 +143,14 @@ func (b *buffer) takeCompleteBuffer() []byte {
}
return b.buf
}

// setGrownBuffer set buf as internal buffer if cap(buf) is larger
// than len(b.buf). It can be used when you took buffer by
// takeCompleteBuffer and append some data to it.
func (b *buffer) setGrownBuffer(buf []byte) {
// buf may be grown by `buf = append(buf, ...)`. So set len=cap explicitly.
buf = buf[:cap(buf)]
if len(buf) > len(b.buf) {
b.buf = buf
}
}
2 changes: 1 addition & 1 deletion packets.go
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
// In that case we must build the data packet with the new values buffer
if valuesCap != cap(paramValues) {
data = append(data[:pos], paramValues...)
mc.buf.buf = data
mc.buf.setGrownBuffer(data)
}

pos += len(paramValues)
Expand Down