diff options
Diffstat (limited to 'android/onceper.go')
-rw-r--r-- | android/onceper.go | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/android/onceper.go b/android/onceper.go index f19f75c08..6160506b0 100644 --- a/android/onceper.go +++ b/android/onceper.go @@ -24,8 +24,6 @@ type OncePer struct { valuesLock sync.Mutex } -type valueMap map[interface{}]interface{} - // Once computes a value the first time it is called with a given key per OncePer, and returns the // value without recomputing when called with the same key. key must be hashable. func (once *OncePer) Once(key interface{}, value func() interface{}) interface{} { @@ -50,6 +48,8 @@ func (once *OncePer) Once(key interface{}, value func() interface{}) interface{} return v } +// Get returns the value previously computed with Once for a given key. If Once has not been called for the given +// key Get will panic. func (once *OncePer) Get(key interface{}) interface{} { v, ok := once.values.Load(key) if !ok { @@ -59,10 +59,12 @@ func (once *OncePer) Get(key interface{}) interface{} { return v } +// OnceStringSlice is the same as Once, but returns the value cast to a []string func (once *OncePer) OnceStringSlice(key interface{}, value func() []string) []string { return once.Once(key, func() interface{} { return value() }).([]string) } +// OnceStringSlice is the same as Once, but returns two values cast to []string func (once *OncePer) Once2StringSlice(key interface{}, value func() ([]string, []string)) ([]string, []string) { type twoStringSlice [2][]string s := once.Once(key, func() interface{} { @@ -72,3 +74,21 @@ func (once *OncePer) Once2StringSlice(key interface{}, value func() ([]string, [ }).(twoStringSlice) return s[0], s[1] } + +// OnceKey is an opaque type to be used as the key in calls to Once. +type OnceKey struct { + key interface{} +} + +// NewOnceKey returns an opaque OnceKey object for the provided key. Two calls to NewOnceKey with the same key string +// DO NOT produce the same OnceKey object. +func NewOnceKey(key string) OnceKey { + return OnceKey{&key} +} + +// NewCustomOnceKey returns an opaque OnceKey object for the provided key. The key can be any type that is valid as the +// key in a map, i.e. comparable. Two calls to NewCustomOnceKey with key values that compare equal will return OnceKey +// objects that access the same value stored with Once. +func NewCustomOnceKey(key interface{}) OnceKey { + return OnceKey{key} +} |