-
Notifications
You must be signed in to change notification settings - Fork 7
/
struct.go
65 lines (57 loc) · 1.24 KB
/
struct.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
package xunsafe
import (
"reflect"
)
type (
//Struct represents a struct
Struct struct {
Fields []Field
}
//Matcher represents a field matcher
Matcher struct {
keyFn func(string) string
index map[string]*Field
}
)
// Matcher creates a filed matched for supplied key Fn
func (s *Struct) Matcher(keyFn func(string) string) *Matcher {
var matcher = Matcher{
index: make(map[string]*Field, len(s.Fields)),
}
for i := range s.Fields {
field := &s.Fields[i]
matcher.index[keyFn(field.Name)] = field
}
return &matcher
}
// Match matches field with type
func (s *Struct) MatchByType(target reflect.Type) *Field {
for i := range s.Fields {
field := &s.Fields[i]
fType := field.Type
if fType.Kind() == reflect.Ptr {
fType = fType.Elem()
}
if fType == target {
return field
}
}
return nil
}
// NewStruct creates a unsafe struct wrapper
func NewStruct(sType reflect.Type) *Struct {
if sType.Kind() == reflect.Ptr {
sType = sType.Elem()
}
result := &Struct{
Fields: make([]Field, sType.NumField()),
}
for i := 0; i < sType.NumField(); i++ {
result.Fields[i] = *NewField(sType.Field(i))
}
return result
}
// Match matches field with name
func (s *Matcher) Match(name string) *Field {
return s.index[s.keyFn(name)]
}