-
Notifications
You must be signed in to change notification settings - Fork 0
/
uint64.go
60 lines (53 loc) · 1.59 KB
/
uint64.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
/*
This file was auto-generated. Do not modify it, lest your changes be overwritten.
*/
package oncecell
import (
"errors"
"sync/atomic"
)
// OnceUint64 wraps a uint64 and enforces at runtime that the value is set at most once.
type OnceUint64 struct {
value uint64
isSet uint32
}
// SetValue sets the value of the uint64 to the provided value.
// This function will return an error if called more than once.
// This is thread-safe as the isSet flag is atomically set, thus ensuring that no two
// callers can check the flag at the same time.
func (o *OnceUint64) SetValue(value uint64) error {
if atomic.CompareAndSwapUint32(&o.isSet, 0, 1) {
o.value = value
return nil
} else {
return errors.New(setErrorMsg)
}
}
// Value returns the value stored in the cell or an error if it has not yet been set
func (o *OnceUint64) Value() (retval uint64, err error) {
if atomic.LoadUint32(&o.isSet) == 1 {
retval = o.value
} else {
err = errors.New(getErrorMsg)
}
return
}
// MustSetValue sets the value of the uint64 to the provided value.
// This function will panic if the value has already been set
// This is thread-safe as the isSet flag is atomically set, thus ensuring that no two
// callers can check the flag at the same time.
func (o *OnceUint64) MustSetValue(value uint64) {
if atomic.CompareAndSwapUint32(&o.isSet, 0, 1) {
o.value = value
} else {
panic(setErrorMsg)
}
}
// MustValue returns the value stored in the cell or panics if it has not yet been set
func (o *OnceUint64) MustValue() uint64 {
if atomic.LoadUint32(&o.isSet) == 1 {
return o.value
} else {
panic(getErrorMsg)
}
}