-
Notifications
You must be signed in to change notification settings - Fork 7
/
field_cacher.go
45 lines (34 loc) · 1.05 KB
/
field_cacher.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
package filter
import "reflect"
// pathByField stores reflectPath by field name.
type pathByField map[string]reflectPath
// fieldByType stores pathByField by struct type.
type fieldByType map[string]pathByField
// fieldCache caches reflectPath by type and field.
type fieldCache struct {
cache fieldByType
}
// Get return the reflectPath from the cache for a field given its type and path, and true if it's found.
// Returns (nil, false) if not found.
func (c *fieldCache) Get(t reflect.Type, fieldPath string) (reflectPath, bool) {
fields := c.getFieldsMap(t)
path, ok := fields[fieldPath]
return path, ok
}
// Set stores a reflectPath in the cache by its type and path.
func (c *fieldCache) Set(t reflect.Type, fieldPath string, path reflectPath) {
fields := c.getFieldsMap(t)
fields[fieldPath] = path
}
func (c *fieldCache) getFieldsMap(t reflect.Type) pathByField {
if c.cache == nil {
c.cache = make(fieldByType)
}
tKey := t.String()
fields, ok := c.cache[tKey]
if !ok {
fields = make(pathByField)
c.cache[tKey] = fields
}
return fields
}