File: copy.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (34 lines) | stat: -rw-r--r-- 775 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package missinggo

import (
	"fmt"
	"reflect"
)

// Copy elements from src to dst. Panics if the length of src and dst are
// different.
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")
	}
}