-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoption.go
161 lines (128 loc) · 2.43 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
153
154
155
156
157
158
159
160
161
package option
import (
"errors"
"fmt"
"reflect"
"unsafe"
)
var errYouIdiot error = errors.New("you forgot to panic you idiot")
type Optional[T any] struct {
data *T
err error
}
func (o *Optional[T]) Expect(err string) T {
if o.data == nil {
panic(err)
}
deref := *o.data
if reflect.ValueOf(deref).Kind() == reflect.String {
ptr := unsafe.Pointer(&deref)
castString := (*string)(ptr)
if *castString == "" {
panic(err)
}
}
return deref
}
func (o *Optional[T]) ExpectNil(err string) {
if o.data != nil {
panic(err)
}
}
func (o *Optional[T]) Or(value T) T {
if o.data == nil {
return value
}
return *o.data
}
func (o *Optional[T]) UnwrapOrElse(errFn func(err error) T) T {
if o.err != nil {
return errFn(o.err)
}
return *o.data
}
func (o *Optional[T]) Unwrap() T {
if o.data == nil && o.err == nil {
panic("optional value is nil")
} else if o.data == nil {
panic(o.err)
}
return *o.data
}
func (o *Optional[T]) IsNil() bool {
return o.data == (*T)(nil)
}
func (o *Optional[T]) Error() string {
if o.err != nil {
return o.err.Error()
}
return ""
}
func newOptional[T any](value interface{}) Optional[T] {
var tmp T
if reflect.ValueOf(value).Kind() == reflect.Ptr {
cast, ok := value.(T)
if !ok {
panic(
fmt.Sprintf(
"Failed to create Optional: %s to %s",
reflect.ValueOf(tmp).Type().Name(),
reflect.ValueOf(value).Type().Name(),
),
)
}
return Optional[T]{
data: &cast,
}
}
if value == nil {
return Optional[T]{
data: nil,
}
}
if reflect.ValueOf(tmp).Kind() != reflect.ValueOf(value).Kind() {
panic(
fmt.Sprintf(
"Failed to create Optional: type mismatch %s to %s",
reflect.ValueOf(tmp).Type().Name(),
reflect.ValueOf(value).Type().Name(),
),
)
}
cast, ok := value.(T)
if !ok {
panic("Failed optional cast")
}
return Optional[T]{
data: &cast,
}
}
func newOptionalPair[T any](value interface{}, err error) Optional[T] {
if err != nil {
return Optional[T]{
data: nil,
err: err,
}
}
return newOptional[T](value)
}
func None[T any]() *Optional[T] {
return &Optional[T]{
data: nil,
err: errors.New("value is None"),
}
}
func Err[T any](err_ error) *Optional[T] {
return &Optional[T]{
data: nil,
err: err_,
}
}
func Some[T any](value T) *Optional[T] {
o := newOptional[T](value)
return &o
}
func SomePair[T any](value T, err error) *Optional[T] {
o := newOptionalPair[T](value, err)
return &o
}