-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes.go
75 lines (73 loc) · 1.57 KB
/
bytes.go
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package copier
import (
"database/sql/driver"
"encoding"
"fmt"
"reflect"
"unsafe"
)
func copyBytes(dst reflect.Value, src reflect.Value) (err error) {
if src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
return
}
switch src.Kind() {
case reflect.String:
v := src.String()
dst.SetBytes(unsafe.Slice(unsafe.StringData(v), len(v)))
break
case reflect.Struct:
// text
if src.Type().Implements(textMarshalerType) {
v := src.Interface().(encoding.TextMarshaler)
p, encodeErr := v.MarshalText()
if encodeErr != nil {
err = encodeErr
return
}
dst.SetBytes(p)
return
}
// sql
if src.Type().Implements(sqlValuerType) {
v := src.Interface().(driver.Valuer)
value, valueErr := v.Value()
if valueErr != nil {
err = valueErr
return
}
if value == nil {
return
}
err = copyBytes(dst, reflect.ValueOf(value))
return
}
err = fmt.Errorf("copier: bytes can not support %s source type", src.Type().String())
break
case reflect.Ptr:
// text
if src.Type().Implements(textMarshalerType) {
v := src.Interface().(encoding.TextMarshaler)
p, encodeErr := v.MarshalText()
if encodeErr != nil {
err = encodeErr
return
}
dst.SetBytes(p)
return
}
err = copyBytes(dst, src.Elem())
break
case reflect.Slice:
if src.Type().Elem().Kind() == reflect.Uint8 {
dst.Set(src)
break
}
err = fmt.Errorf("copier: bytes can not support %s source type", src.Type().String())
break
default:
err = fmt.Errorf("copier: bytes not support %s source type", src.Type().String())
return
}
return
}