-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
152 lines (115 loc) · 2.1 KB
/
option.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package result
import (
"context"
"errors"
"fmt"
"sync"
)
var NoneOptionError = errors.New("value is none")
var UnsetOptionError = errors.New("option not yet set")
type OptionKind int
const (
Some = OptionKind(0)
None = OptionKind(1)
Error = OptionKind(2)
NotSet = OptionKind(9999)
neverSet = OptionKind(-1) //used for testing
)
type Option[T any] struct {
some T
err error
isSet bool
isNone bool
setterMux sync.RWMutex
setOnce sync.Once
setChan chan struct{}
}
func NewOption[T any]() *Option[T] {
setChan := make(chan struct{})
return &Option[T]{
setChan: setChan,
}
}
func (o *Option[T]) SetSome(value T) *Option[T] {
o.setOnce.Do(func() {
o.setterMux.Lock()
defer o.setterMux.Unlock()
o.isSet = true
o.some = value
close(o.setChan)
})
return o
}
func (o *Option[T]) SetNone() *Option[T] {
o.setOnce.Do(func() {
o.setterMux.Lock()
defer o.setterMux.Unlock()
var emptyT T
o.some = emptyT
o.isSet = true
o.isNone = true
close(o.setChan)
})
return o
}
func (o *Option[T]) SetError(e error) *Option[T] {
o.setOnce.Do(func() {
o.setterMux.Lock()
defer o.setterMux.Unlock()
var emptyT T
o.some = emptyT
o.isSet = true
o.isNone = true
o.err = e
close(o.setChan)
})
return o
}
func (o *Option[T]) Unwrap() (T, error) {
o.setterMux.RLock()
defer o.setterMux.RUnlock()
if !o.isSet {
var emptyT T
return emptyT, UnsetOptionError
}
if o.err != nil {
var emptyT T
return emptyT, o.err
}
if o.isNone {
var emptyT T
return emptyT, NoneOptionError
}
return o.some, nil
}
func (o *Option[T]) Wait(ctx context.Context) (T, error) {
select {
case <-ctx.Done():
var emptyT T
return emptyT, fmt.Errorf("wait context error: %w", ctx.Err())
case <-o.setChan:
if o.err != nil {
var emptyT T
return emptyT, o.err
}
if o.isNone {
var emptyT T
return emptyT, NoneOptionError
}
return o.some, nil
}
}
func (o *Option[T]) Kind() OptionKind {
o.setterMux.RLock()
defer o.setterMux.RUnlock()
if !o.isSet {
return NotSet
}
if o.err != nil {
return Error
}
if o.isNone {
return None
}
return Some
}