forked from charmbracelet/mods
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
33 lines (30 loc) · 685 Bytes
/
Copy pathsync.go
File metadata and controls
33 lines (30 loc) · 685 Bytes
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
package main
import "sync"
// copied from go1.21, remove and use sync.OnceValue once go 1.21 is widely
// available in package managers.
// OnceValue returns a function that invokes f only once and returns the value
// returned by f. The returned function may be called concurrently.
//
// If f panics, the returned function will panic with the same value on every call.
func OnceValue[T any](f func() T) func() T {
var once sync.Once
var valid bool
var p any
var result T
return func() T {
once.Do(func() {
defer func() {
p = recover()
if !valid {
panic(p)
}
}()
result = f()
valid = true
})
if !valid {
panic(p)
}
return result
}
}