-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonce.go
70 lines (65 loc) · 1.58 KB
/
once.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package sync
import (
"fmt"
"reflect"
"sync"
)
// OnceFunc returns a function that invokes fn only once.
// The returned function may be called concurrently.
func OnceFunc(fn func()) func() {
var once sync.Once
return func() {
once.Do(fn)
}
}
// OnceValue returns a function that invokes fn only once and returns the
// value returned by fn. The returned function may be called concurrently.
func OnceValue[T any](fn func() T) func() T {
var (
once sync.Once
v T
)
return func() T {
once.Do(func() {
v = fn()
})
return v
}
}
// OnceValues returns a function that invokes fn only once and returns the
// values returned by fn. The returned function may be called concurrently.
func OnceValues[T1, T2 any](fn func() (T1, T2)) func() (T1, T2) {
var (
once sync.Once
v1 T1
v2 T2
)
return func() (T1, T2) {
once.Do(func() {
v1, v2 = fn()
})
return v1, v2
}
}
// OnceFuncReflect returns a function that invokes fn only once and returns the
// value returned by fn. The returned function may be called concurrently.
func OnceFuncReflect[F any](fn F) F {
fnv := reflect.ValueOf(fn)
if fnv.Kind() != reflect.Func {
panic(fmt.Errorf("sync: OnceFuncReflect called with non-function value (%T)", fn))
}
fnt := fnv.Type()
if fnt.NumIn() != 0 {
panic(fmt.Errorf("sync: OnceFuncReflect called with function with more than zero args (%T)", fn))
}
var (
once sync.Once
results []reflect.Value
)
return reflect.MakeFunc(fnt, func([]reflect.Value) []reflect.Value {
once.Do(func() {
results = fnv.Call(nil)
})
return results
}).Interface().(F)
}