-
Notifications
You must be signed in to change notification settings - Fork 1
/
implmap.go
72 lines (66 loc) · 1.19 KB
/
implmap.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
package implmap
import (
"fmt"
"reflect"
"sync"
)
var (
m = make(map[string][]reflect.Type)
l = &sync.RWMutex{}
)
//accept struct pointer only
func Add(n string, t reflect.Type) {
if t == nil || n == "" || !isStructPtr(t) {
return
}
l.Lock()
defer l.Unlock()
a, ok := m[n]
if !ok || a == nil {
a = []reflect.Type{}
}
l := len(a)
if l > 0 {
fmt.Println(fmt.Sprintf("implmap append new type(%v) impl to name(%v) at index(%v), old array=%v", t, n, l, a))
}
a = append(a, t)
m[n] = a
}
func Get(n string) []reflect.Type {
if n == "" {
return []reflect.Type{}
}
l.RLock()
defer l.RUnlock()
types := m[n]
if types == nil {
return []reflect.Type{}
}
ret := []reflect.Type{}
for _, t := range types {
if t == nil {
continue
}
ret = append(ret, t)
}
return ret
}
func GetAll() map[string][]reflect.Type {
l.RLock()
defer l.RUnlock()
mCopy := make(map[string][]reflect.Type)
for key := range m {
ret := []reflect.Type{}
for _, t := range m[key] {
if t == nil {
continue
}
ret = append(ret, t)
mCopy[key] = ret
}
}
return mCopy
}
func isStructPtr(t reflect.Type) bool {
return t != nil && t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}