-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
60 lines (53 loc) · 1.59 KB
/
string.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"
)
// OnceString wraps a string and enforces at runtime that the value is set at most once.
type OnceString struct {
value string
isSet uint32
}
// SetValue sets the value of the string 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 *OnceString) SetValue(value string) 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 *OnceString) Value() (retval string, err error) {
if atomic.LoadUint32(&o.isSet) == 1 {
retval = o.value
} else {
err = errors.New(getErrorMsg)
}
return
}
// MustSetValue sets the value of the string 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 *OnceString) MustSetValue(value string) {
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 *OnceString) MustValue() string {
if atomic.LoadUint32(&o.isSet) == 1 {
return o.value
} else {
panic(getErrorMsg)
}
}