util/copy.go | 3 +++ util/copy_test.go | 25 ++++++++++++++++++++++--- diff --git a/util/copy.go b/util/copy.go index 793a99cd951c832922dabd474a83e3c9080dd977..fda4cffc39906c68bf0881a076d33ae8f73a3faf 100644 --- a/util/copy.go +++ b/util/copy.go @@ -17,6 +17,9 @@ } if sV.Kind() == reflect.String { sV = sV.Convert(reflect.SliceOf(dV.Type().Elem())) } + if !sV.IsValid() { + panic("invalid source, probably nil") + } if dV.Len() != sV.Len() { panic(fmt.Sprintf("dest len (%d) != src len (%d)", dV.Len(), sV.Len())) } diff --git a/util/copy_test.go b/util/copy_test.go index 284840a3ad3982f7b45e69639e483ca698f95406..18c9e2d6b80da87d3c7ea8b326ad649c443fea4b 100644 --- a/util/copy_test.go +++ b/util/copy_test.go @@ -2,6 +2,7 @@ package util import ( "bytes" + "strings" "testing" ) @@ -51,11 +52,29 @@ CopyExact(dest, "lol") if string(dest) != "lol" { t.FailNow() } + func() { + defer func() { + r := recover() + if r == nil { + t.FailNow() + } + }() + CopyExact(dest, "rofl") + }() + var arr [5]byte + CopyExact(&arr, interface{}("hello")) + if string(arr[:]) != "hello" { + t.FailNow() + } +} + +func TestCopySrcNilInterface(t *testing.T) { + var arr [3]byte defer func() { - r := recover() - if r == nil { + r := recover().(string) + if !strings.Contains(r, "invalid source") { t.FailNow() } }() - CopyExact(dest, "rofl") + CopyExact(&arr, nil) }