Skip to content

Commit

Permalink
Do not reuse sql driver's buffer in scanner. Fixes #298.
Browse files Browse the repository at this point in the history
Signed-off-by: Howard Yeh <[email protected]>
  • Loading branch information
hayeah committed Nov 10, 2018
1 parent 2c441a6 commit fda9fd6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion types/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,20 @@ type ByteArray []uint8
func (a *ByteArray) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
*(*[]byte)(a) = src
dst := *(*[]byte)(a)

if a == nil || cap(dst) < len(src) {
// nil, or shorter destination than source. Create a new slice.
dst = make([]byte, len(src))
} else {
// Resize slice, but retain capacity
dst = dst[0:len(src)]
}

// Copy, do not retain reference to reference types.
copy(dst, src)

*(*[]byte)(a) = dst
return nil
case string:
*(*[]byte)(a) = []byte(src)
Expand Down
17 changes: 17 additions & 0 deletions types/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,23 @@ func TestSlice_Integration(t *testing.T) {
}
}

func TestByteArray_ScannerNoBufferReuse(t *testing.T) {
require := require.New(t)

var sharedbuf [32]byte

var ba ByteArray

err := ba.Scan(sharedbuf[:])
require.NoError(err)

// Modify the "driver" buffer src
sharedbuf[0] = 1

require.Equal(uint8(0), ba[0], "ByteBuffer should not share reference with scanned src")

}

func envOrDefault(key string, def string) string {
v := os.Getenv(key)
if v == "" {
Expand Down

0 comments on commit fda9fd6

Please sign in to comment.