-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_caches.go
More file actions
62 lines (51 loc) · 1.61 KB
/
Copy pathgenerate_caches.go
File metadata and controls
62 lines (51 loc) · 1.61 KB
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
package enum
import (
"reflect"
"strings"
)
func noTransmute[T comparable](in T) T {
return in
}
func generateCaches[Enum any, Interim any, Result comparable](transmuter func(Interim) Result) (nvCache map[string]Result, vnCache map[Result]string) {
// Make our maps first
vnCache = make(map[Result]string)
nvCache = make(map[string]Result)
// Collect reflected types of our enum and value, enumRaw and vValue
var enum Enum
var enumPtr = &enum
var valueRaw Interim
vType := reflect.TypeOf(valueRaw)
type todo struct {
Target reflect.Value
Type reflect.Type
}
todos := []todo{
{reflect.ValueOf(enum), reflect.TypeOf(enum)},
{reflect.ValueOf(enumPtr), reflect.TypeOf(enumPtr)},
}
for _, v := range todos {
// Step through the available methods on our enumeration type,
// and find all that match our target function signature
nMethods := v.Type.NumMethod()
for i := 0; i < nMethods; i++ {
// Get method[i] and it's type
method := v.Type.Method(i)
t := method.Type
// Match our signature
if !(t.NumIn() == 1 && t.NumOut() == 1 &&
t.In(0).AssignableTo(v.Type) && t.Out(0).AssignableTo(vType)) {
continue // One in (enum), one out (value
}
// put the name into our maps
n := method.Name
interim := method.Func.Call([]reflect.Value{v.Target})[0].Interface().(Interim)
result := transmuter(interim)
vnCache[result] = n
// Case-sensitivity for enum/bitflag stringification/parsing makes sense in zero scenarios.
// Golang has some rules about capitalization already, and these ants aren't worth fucking.
n = strings.ToLower(n)
nvCache[n] = result
}
}
return
}