github.com/westcoastroms/westcoastroms-build@v0.0.0-20190928114312-2350e5a73030/build/soong/android/onceper.go (about) 1 // Copyright 2016 Google Inc. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package android 16 17 import ( 18 "fmt" 19 "sync" 20 ) 21 22 type OncePer struct { 23 values sync.Map 24 valuesLock sync.Mutex 25 } 26 27 type valueMap map[interface{}]interface{} 28 29 // Once computes a value the first time it is called with a given key per OncePer, and returns the 30 // value without recomputing when called with the same key. key must be hashable. 31 func (once *OncePer) Once(key interface{}, value func() interface{}) interface{} { 32 // Fast path: check if the key is already in the map 33 if v, ok := once.values.Load(key); ok { 34 return v 35 } 36 37 // Slow path: lock so that we don't call the value function twice concurrently 38 once.valuesLock.Lock() 39 defer once.valuesLock.Unlock() 40 41 // Check again with the lock held 42 if v, ok := once.values.Load(key); ok { 43 return v 44 } 45 46 // Still not in the map, call the value function and store it 47 v := value() 48 once.values.Store(key, v) 49 50 return v 51 } 52 53 func (once *OncePer) Get(key interface{}) interface{} { 54 v, ok := once.values.Load(key) 55 if !ok { 56 panic(fmt.Errorf("Get() called before Once()")) 57 } 58 59 return v 60 } 61 62 func (once *OncePer) OnceStringSlice(key interface{}, value func() []string) []string { 63 return once.Once(key, func() interface{} { return value() }).([]string) 64 } 65 66 func (once *OncePer) Once2StringSlice(key interface{}, value func() ([]string, []string)) ([]string, []string) { 67 type twoStringSlice [2][]string 68 s := once.Once(key, func() interface{} { 69 var s twoStringSlice 70 s[0], s[1] = value() 71 return s 72 }).(twoStringSlice) 73 return s[0], s[1] 74 }