2
0
mirror of synced 2025-02-24 06:38:14 +00:00

util/CopyExact: Test copying from interfaces and nil

This commit is contained in:
Matt Joiner 2014-11-17 17:43:41 -06:00
parent cdf6bdefa9
commit 0668e33228
2 changed files with 25 additions and 3 deletions

View File

@ -17,6 +17,9 @@ func CopyExact(dest interface{}, src interface{}) {
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()))
}

View File

@ -2,6 +2,7 @@ package util
import (
"bytes"
"strings"
"testing"
)
@ -51,11 +52,29 @@ func TestCopySrcString(t *testing.T) {
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)
}