| 1 |
/* |
| 2 |
Copyright 2019 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package promise |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"sync" |
| 22 |
) |
| 23 |
|
| 24 |
// promise implements the WriteOnce interface. |
| 25 |
type promise struct { |
| 26 |
doneCtx context.Context |
| 27 |
doneVal interface{} |
| 28 |
setCh chan struct{} |
| 29 |
onceler sync.Once |
| 30 |
value interface{} |
| 31 |
} |
| 32 |
|
| 33 |
var _ WriteOnce = &promise{} |
| 34 |
|
| 35 |
// NewWriteOnce makes a new thread-safe WriteOnce. |
| 36 |
// |
| 37 |
// If `initial` is non-nil then that value is Set at creation time. |
| 38 |
// |
| 39 |
// If a `Get` is waiting soon after the channel associated with the |
| 40 |
// `doneCtx` becomes selectable (which never happens for the nil |
| 41 |
// channel) then `Set(doneVal)` effectively happens at that time. |
| 42 |
func NewWriteOnce(initial interface{}, doneCtx context.Context, doneVal interface{}) WriteOnce { |
| 43 |
p := &promise{ |
| 44 |
doneCtx: doneCtx, |
| 45 |
doneVal: doneVal, |
| 46 |
setCh: make(chan struct{}), |
| 47 |
} |
| 48 |
if initial != nil { |
| 49 |
p.Set(initial) |
| 50 |
} |
| 51 |
return p |
| 52 |
} |
| 53 |
|
| 54 |
func (p *promise) Get() interface{} { |
| 55 |
select { |
| 56 |
case <-p.setCh: |
| 57 |
case <-p.doneCtx.Done(): |
| 58 |
p.Set(p.doneVal) |
| 59 |
} |
| 60 |
return p.value |
| 61 |
} |
| 62 |
|
| 63 |
func (p *promise) Set(value interface{}) bool { |
| 64 |
var ans bool |
| 65 |
p.onceler.Do(func() { |
| 66 |
p.value = value |
| 67 |
close(p.setCh) |
| 68 |
ans = true |
| 69 |
}) |
| 70 |
return ans |
| 71 |
} |