copy.go 775 B

12345678910111213141516171819202122232425262728293031323334
  1. package missinggo
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. // Copy elements from src to dst. Panics if the length of src and dst are
  7. // different.
  8. func CopyExact(dest interface{}, src interface{}) {
  9. dV := reflect.ValueOf(dest)
  10. sV := reflect.ValueOf(src)
  11. if dV.Kind() == reflect.Ptr {
  12. dV = dV.Elem()
  13. }
  14. if dV.Kind() == reflect.Array && !dV.CanAddr() {
  15. panic(fmt.Sprintf("dest not addressable: %T", dest))
  16. }
  17. if sV.Kind() == reflect.Ptr {
  18. sV = sV.Elem()
  19. }
  20. if sV.Kind() == reflect.String {
  21. sV = sV.Convert(reflect.SliceOf(dV.Type().Elem()))
  22. }
  23. if !sV.IsValid() {
  24. panic("invalid source, probably nil")
  25. }
  26. if dV.Len() != sV.Len() {
  27. panic(fmt.Sprintf("dest len (%d) != src len (%d)", dV.Len(), sV.Len()))
  28. }
  29. if dV.Len() != reflect.Copy(dV, sV) {
  30. panic("dammit")
  31. }
  32. }