summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-errors/v2/once.go
blob: 467fe726d30258b53c885cbb41e7f1ec980b5159 (plain)
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
package errors

import (
	"sync/atomic"
)

// OnceError is an error structure that supports safe multi
// threaded usage and setting only once (until reset).
type OnceError struct{ ptr atomic.Pointer[error] }

// Store will safely set the OnceError to value, no-op if nil.
func (e *OnceError) Store(err error) bool {
	if err == nil {
		return false
	}
	return e.ptr.CompareAndSwap(nil, &err)
}

// Load will load the currently stored error.
func (e *OnceError) Load() error {
	if ptr := e.ptr.Load(); ptr != nil {
		return *ptr
	}
	return nil
}

// IsSet returns whether OnceError has been set.
func (e *OnceError) IsSet() bool { return (e.ptr.Load() != nil) }

// Reset will reset the OnceError value.
func (e *OnceError) Reset() { e.ptr.Store(nil) }