-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgob.go
61 lines (55 loc) · 1.29 KB
/
gob.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
package reflectricity
import (
"encoding/gob"
"reflect"
"sync"
)
var registeredNames sync.Map
// RegisterGob recursively registers a value.
// Useful when dealing with polymorphic values that need to be written across
// the wire.
//
// May need Jesus for this one
func RegisterGob(value any) {
registerRecursiveGob(value)
}
func registerRecursiveGob(i any) {
if i == nil {
return
}
t := reflect.ValueOf(i)
kind := t.Kind()
switch kind {
case reflect.Ptr:
if k := t.Elem().Kind(); k == reflect.Struct {
if _, ok := registeredNames.Load(t.Type()); !ok {
gob.Register(i)
registeredNames.Store(t.Type(), struct{}{})
}
}
registerStructFields(t.Elem().Interface())
case reflect.Map:
iter := t.MapRange()
for iter.Next() {
registerRecursiveGob(iter.Key().Interface())
registerRecursiveGob(iter.Value().Interface())
}
case reflect.Array, reflect.Slice:
for n := 0; n < t.Len(); n++ {
registerRecursiveGob(t.Index(n).Interface())
}
case reflect.Struct:
if _, ok := registeredNames.Load(t.Type()); !ok {
gob.Register(i)
registeredNames.Store(t.Type(), struct{}{})
}
registerStructFields(i)
}
}
func registerStructFields(i any) {
t := reflect.ValueOf(i)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
registerRecursiveGob(field.Interface())
}
}