/
key.go
83 lines (72 loc) · 1.75 KB
/
key.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
package rumble
import (
"reflect"
"strings"
)
func getKey(v interface{}) []byte {
val := getReflectValue(reflect.ValueOf(v))
// return nil on invalid key reflect value
if !val.IsValid() {
return nil
}
switch val.Kind() {
case reflect.Slice: // TODO: correct way to detect byte slice?
return val.Bytes()
case reflect.Interface:
switch val.Elem().Kind() {
case reflect.Slice: // TODO: correct way to detect byte slice?
return val.Elem().Bytes()
}
case reflect.String:
return []byte(val.String())
}
return nil
}
func setKey(key []byte, v interface{}) {
// explicitly set _key for maps
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Map:
rv.SetMapIndex(reflect.ValueOf("_key"), reflect.ValueOf(key))
return
case reflect.Ptr:
elem := rv.Elem()
if elem.Kind() == reflect.Map {
elem.SetMapIndex(reflect.ValueOf("_key"), reflect.ValueOf(key))
return
}
}
// try to find a rumble key tag
val := getReflectValue(rv)
// return nil on invalkey reflect value
if !val.IsValid() || !val.CanSet() {
return
}
switch val.Kind() {
case reflect.Slice: // TODO: correct way to detect byte slice?
val.SetBytes(key)
case reflect.String:
val.SetString(string(key))
}
}
func getReflectValue(rv reflect.Value) reflect.Value {
switch rv.Kind() {
case reflect.Map:
for _, mk := range rv.MapKeys() {
if mk.Kind() == reflect.String && mk.String() == "_key" {
return rv.MapIndex(mk)
}
}
case reflect.Struct:
for i := 0; i < rv.NumField(); i++ {
tag := rv.Type().Field(i).Tag.Get("rumble")
if strings.Contains(strings.ToLower(tag), "key") {
return rv.Field(i)
}
}
case reflect.Ptr:
return getReflectValue(rv.Elem())
}
// return blank value struct, can use IsValkey() on it
return reflect.Value{}
}