-
Notifications
You must be signed in to change notification settings - Fork 1
/
once.go
96 lines (84 loc) · 1.88 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package once
import (
"sync"
"sync/atomic"
)
// Once is backwards compatible re-implementation of sync.Once.
// See https://golang.org/pkg/sync/#Once
type Once struct {
m sync.Mutex
done uint32
}
// Do is a backwards compatible re-implementation of Do from sync.Once
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 1 {
return
}
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
// Error is similar to Once, except it returns an error value.
type Error struct {
m sync.Mutex
done uint32
err error
}
// Do runs the specified function only once, but all callers gets the same
// result from that single execution.
func (o *Error) Do(f func() error) error {
if atomic.LoadUint32(&o.done) == 1 {
return o.err
}
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
o.err = f()
}
return o.err
}
// Value is similar to Once, except it returns a value.
type Value[T any] struct {
m sync.Mutex
done uint32
value T
}
// Do runs the specified function only once, but all callers gets the same
// result from that single execution.
func (o *Value[T]) Do(f func() T) T {
if atomic.LoadUint32(&o.done) == 1 {
return o.value
}
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
o.value = f()
}
return o.value
}
// ValueError is similar to Once, except it return a (value, error) tuple
type ValueError[T any] struct {
m sync.Mutex
done uint32
value T
err error
}
// Do runs the specified function only once, but all callers gets the same
// result from that single execution.
func (o *ValueError[T]) Do(f func() (T, error)) (T, error) {
if atomic.LoadUint32(&o.done) == 1 {
return o.value, o.err
}
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
o.value, o.err = f()
}
return o.value, o.err
}