diff --git a/buffer.go b/buffer.go index eb4748bf4..4d705a5a6 100644 --- a/buffer.go +++ b/buffer.go @@ -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, } } @@ -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] } @@ -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 + } +} diff --git a/packets.go b/packets.go index 9ed640850..527488319 100644 --- a/packets.go +++ b/packets.go @@ -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)