2
0
mirror of synced 2025-02-24 06:38:14 +00:00
torrent/util/copy.go
Matt Joiner 0f7c4c5bda util: Support CopyExact with pointer source
Nice to avoid copying large value types.
2015-03-18 18:09:54 +11:00

33 lines
682 B
Go

package util
import (
"fmt"
"reflect"
)
func CopyExact(dest interface{}, src interface{}) {
dV := reflect.ValueOf(dest)
sV := reflect.ValueOf(src)
if dV.Kind() == reflect.Ptr {
dV = dV.Elem()
}
if dV.Kind() == reflect.Array && !dV.CanAddr() {
panic(fmt.Sprintf("dest not addressable: %T", dest))
}
if sV.Kind() == reflect.Ptr {
sV = sV.Elem()
}
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()))
}
if dV.Len() != reflect.Copy(dV, sV) {
panic("dammit")
}
}