-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathreflect_helpers.go
124 lines (103 loc) · 2.56 KB
/
reflect_helpers.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package goof
import (
"fmt"
"path"
"reflect"
"strings"
"unsafe"
)
func ifaces(values []reflect.Value) []interface{} {
out := make([]interface{}, 0, len(values))
for _, value := range values {
out = append(out, value.Interface())
}
return out
}
func reflectCanBeNil(rtyp reflect.Type) bool {
switch rtyp.Kind() {
case reflect.Interface,
reflect.Ptr,
reflect.Map,
reflect.Chan,
reflect.Slice:
return true
}
return false
}
func typesByString(types []reflect.Type) sortTypesByString {
cache := make([]string, 0, len(types))
for _, typ := range types {
cache = append(cache, typ.String())
}
return sortTypesByString{
types: types,
cache: cache,
}
}
type sortTypesByString struct {
types []reflect.Type
cache []string
}
func (s sortTypesByString) Len() int { return len(s.types) }
func (s sortTypesByString) Less(i, j int) bool {
return s.cache[i] < s.cache[j]
}
func (s sortTypesByString) Swap(i, j int) {
s.cache[i], s.cache[j] = s.cache[j], s.cache[i]
s.types[i], s.types[j] = s.types[j], s.types[i]
}
var (
unsafePointerType = reflect.TypeOf((*unsafe.Pointer)(nil)).Elem()
)
// dwarfName does a best effort to return the dwarf entry name for the reflect
// type so that we can map between them. here's hoping it doesn't do it wrong
func dwarfName(rtyp reflect.Type) (out string) {
pkg_path := rtyp.PkgPath()
name := rtyp.Name()
switch {
// this type's PkgPath returns "" instead of "unsafe". hah.
case rtyp == unsafePointerType:
return "unsafe.Pointer"
case pkg_path != "":
// this is crazy, but sometimes a dot is encoded as %2e, but only when
// it's in the last path component. i wonder if this is sufficient.
if strings.Contains(pkg_path, "/") {
dir := path.Dir(pkg_path)
base := strings.Replace(path.Base(pkg_path), ".", "%2e", -1)
pkg_path = dir + "/" + base
}
return pkg_path + "." + name
case name != "":
return name
default:
switch rtyp.Kind() {
case reflect.Ptr:
return "*" + dwarfName(rtyp.Elem())
case reflect.Slice:
return "[]" + dwarfName(rtyp.Elem())
case reflect.Array:
return fmt.Sprintf("[%d]%s",
rtyp.Len(),
dwarfName(rtyp.Elem()))
case reflect.Map:
return fmt.Sprintf("map[%s]%s",
dwarfName(rtyp.Key()),
dwarfName(rtyp.Elem()))
case reflect.Chan:
prefix := "chan"
switch rtyp.ChanDir() {
case reflect.SendDir:
prefix = "chan<-"
case reflect.RecvDir:
prefix = "<-chan"
}
return fmt.Sprintf("%s %s",
prefix,
dwarfName(rtyp.Elem()))
// TODO: func, struct
default:
// oh well. this sometimes works.
return rtyp.String()
}
}
}