internal/fields: use sync.Map
Replace atomiccache with sync.Map.
@@ -69,8 +69,7 @@ import (
"reflect"
"sort"
"strings"
-
- "cloud.google.com/go/internal/atomiccache"
+ "sync"
)
// A Field records information about a struct field.
@@ -105,7 +104,7 @@ type Cache struct {
parseTag ParseTagFunc
validate ValidateFunc
leafTypes LeafTypesFunc
- cache atomiccache.Cache // from reflect.Type to cacheValue
+ cache sync.Map // from reflect.Type to cacheValue
}
// NewCache constructs a Cache.
@@ -212,13 +211,19 @@ type cacheValue struct {
// This code has been copied and modified from
// https://go.googlesource.com/go/+/go1.7.3/src/encoding/json/encode.go.
func (c *Cache) cachedTypeFields(t reflect.Type) (List, error) {
- cv := c.cache.Get(t, func() interface{} {
+ var cv cacheValue
+ x, ok := c.cache.Load(t)
+ if ok {
+ cv = x.(cacheValue)
+ } else {
if err := c.validate(t); err != nil {
- return cacheValue{nil, err}
- }
+ cv = cacheValue{nil, err}
+ } else {
f, err := c.typeFields(t)
- return cacheValue{List(f), err}
- }).(cacheValue)
+ cv = cacheValue{List(f), err}
+ }
+ c.cache.Store(t, cv)
+ }
return cv.fields, cv.err
}
