Prepare for a type-safe OnceKey

Add an opaque OnceKey type and use it for all calls to Once in
build/soong.  A future patch will convert the arguments to
Once* to OnceKey once users outside build/soong have been updated.

Test: onceper_test.go
Change-Id: Ifcb338e6e603e804e507203c9508d30ffb2df966
This commit is contained in:
Colin Cross
2019-02-04 11:22:08 -08:00
parent 5cb5b093d1
commit 571cccfcbc
16 changed files with 206 additions and 32 deletions

View File

@@ -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}
}