2021-09-11 19:12:47 +00:00
|
|
|
package errors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
2022-05-08 17:49:45 +00:00
|
|
|
// OnceError is an error structure that supports safe multi
|
|
|
|
// threaded usage and setting only once (until reset).
|
2023-11-30 16:22:34 +00:00
|
|
|
type OnceError struct{ ptr atomic.Pointer[error] }
|
2021-09-11 19:12:47 +00:00
|
|
|
|
2022-05-08 17:49:45 +00:00
|
|
|
// Store will safely set the OnceError to value, no-op if nil.
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *OnceError) Store(err error) bool {
|
2021-09-11 19:12:47 +00:00
|
|
|
if err == nil {
|
2023-11-30 16:22:34 +00:00
|
|
|
return false
|
2021-09-11 19:12:47 +00:00
|
|
|
}
|
2023-11-30 16:22:34 +00:00
|
|
|
return e.ptr.CompareAndSwap(nil, &err)
|
2021-09-11 19:12:47 +00:00
|
|
|
}
|
|
|
|
|
2022-05-08 17:49:45 +00:00
|
|
|
// Load will load the currently stored error.
|
2021-09-11 19:12:47 +00:00
|
|
|
func (e *OnceError) Load() error {
|
2023-11-30 16:22:34 +00:00
|
|
|
if ptr := e.ptr.Load(); ptr != nil {
|
|
|
|
return *ptr
|
|
|
|
}
|
|
|
|
return nil
|
2021-09-11 19:12:47 +00:00
|
|
|
}
|
|
|
|
|
2022-05-08 17:49:45 +00:00
|
|
|
// IsSet returns whether OnceError has been set.
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *OnceError) IsSet() bool { return (e.ptr.Load() != nil) }
|
2021-09-11 19:12:47 +00:00
|
|
|
|
2022-05-08 17:49:45 +00:00
|
|
|
// Reset will reset the OnceError value.
|
2023-11-30 16:22:34 +00:00
|
|
|
func (e *OnceError) Reset() { e.ptr.Store(nil) }
|