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
diff --git a/android/onceper.go b/android/onceper.go
index f19f75c..6160506 100644
--- a/android/onceper.go
+++ b/android/onceper.go
@@ -24,8 +24,6 @@
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 @@
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 @@
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 @@
}).(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}
+}