-
Notifications
You must be signed in to change notification settings - Fork 2
/
option.go
74 lines (62 loc) · 1.15 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
package safetypes
import (
"encoding/json"
"strings"
)
type Option[T any] struct {
Value *T `json:"value,omitempty" bson:"value,omitempty" rethinkdb:"value,omitempty"`
}
func Some[T any](value T) Option[T] {
return Option[T]{
Value: &value,
}
}
func None[T any]() Option[T] {
return Option[T]{
Value: nil,
}
}
func (o Option[T]) Some(value T) Option[T] {
o.Value = &value
return o
}
func (o Option[T]) None() Option[T] {
o.Value = nil
return o
}
func (o *Option[T]) IsSome() bool {
return o.Value != nil
}
func (o *Option[T]) IsNone() bool {
return o.Value == nil
}
func (o *Option[T]) Unwrap() T {
if o.IsNone() {
panic("can't unwrap none value")
}
return *o.Value
}
func (o *Option[T]) UnwrapOr(or T) T {
if o.IsNone() {
return or
}
return *o.Value
}
func (o Option[T]) MarshalJSON() ([]byte, error) {
if o.IsSome() {
return json.Marshal(o.Value)
}
return []byte("{}"), nil
}
func (o *Option[T]) UnmarshalJSON(data []byte) error {
var result T
if err := json.Unmarshal(data, &result); err != nil {
if strings.HasPrefix(string(data), "{}") {
o.Value = nil
return nil
}
return err
}
o.Value = &result
return nil
}