-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopt.go
More file actions
172 lines (140 loc) · 4.14 KB
/
opt.go
File metadata and controls
172 lines (140 loc) · 4.14 KB
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
162
163
164
165
166
167
168
169
170
171
172
package opt
import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding/json"
)
var (
_ driver.Valuer = &Optional[string]{}
_ sql.Scanner = &Optional[string]{}
_ json.Marshaler = &Optional[string]{}
_ json.Unmarshaler = &Optional[string]{}
)
func New[T any](item T) Optional[T] {
return Optional[T]{
Item: item,
state: stateValid,
}
}
func Nil[T any]() Optional[T] {
return Optional[T]{
state: stateNil,
}
}
func None[T any]() Optional[T] {
return Optional[T]{
state: stateNone,
}
}
// state represent the different states of an optional field.
// - None ([stateNone])
// - Present but nil ([stateNil])
// - Present with value ([stateValid])
type state int8
const (
stateNone state = iota // Field is not preset.
stateNil // Field is present but nil.
stateValid // Field is present with a not nil value.
)
type Optional[T any] struct {
Item T
state state
}
// Ptr returns a pointer to the inner value if the value is present and not nil. Otherwise it returns nil.
func (e Optional[T]) Ptr() *T {
if e.IsValid() {
return &e.Item
}
return nil
}
// OrElse checks if the value of Optional struct exists and is not nil,
// if so it returns it, otherwise it returns the given argument d.
func (e Optional[T]) OrElse(d T) T { //nolint:ireturn
if e.IsValid() {
return e.Item
}
return d
}
func (e Optional[T]) IsValid() bool { return e.state == stateValid }
func (e Optional[T]) IsNil() bool { return e.state == stateNil }
func (e Optional[T]) IsPresent() bool { return e.state > stateNone }
// IsZero implements the interface used by go 1.24 [encoding/json] marshall when `omitzero` tag is present.
func (e Optional[T]) IsZero() bool {
return e.state == stateNone
}
// MarshalJSON implements the [json.Marshaler] interface.
// It returns "null" if the state is either none or nil.
func (e Optional[T]) MarshalJSON() ([]byte, error) {
if e.IsValid() {
return json.Marshal(e.Item)
}
return nullBytes, nil
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
// When this function is called (e.g. by [json.Unmarshal]), the isPresent value is set to true. This is because it means there is a field matching this value field name, and there is a value for it.
// If the JSON value of data is null, the soil is set to true.
// If the [json.Unmarshal] returns error isPresent and isNil are set to false before returning the error.
func (e *Optional[T]) UnmarshalJSON(data []byte) error {
e.state = stateNil // state is > None
if string(bytes.TrimSpace(data)) == nullString {
return nil
}
err := json.Unmarshal(data, &e.Item)
if err != nil {
e.state = stateNone
return err
}
e.state = stateValid
return nil
}
var (
nullString = "null"
nullBytes = []byte(nullString)
)
// Scan implements [sql.Scanner] interface. Upon calling this function (e.g. from [sql.Rows] Scan function), the isPresent is set to true.
// It sets isNil to true if the database value (src) is null, otherwise it sets the value to [Optional.Item] and sets isNil to false.
func (e *Optional[T]) Scan(src any) error {
e.state = stateNil // state is > None
// tunnel to sql.Null to use sql.convertAssign
n := sql.Null[T]{}
err := n.Scan(src)
if err != nil {
e.state = stateNone
return err
}
if n.Valid {
e.state = stateValid
e.Item = n.V
}
return nil
}
// Value implements [driver.Valuer] interface.
// If the wrapped value Item implements [driver.Valuer] that Value() function will be called.
func (e Optional[T]) Value() (driver.Value, error) {
if !e.IsValid() {
return nil, nil //nolint:nilnil
}
var val any
var err error
val = e.Item
// if the internal value is also a valuer, call that.
// direct type assertion does not work on generics.
if v, isValuer := (any(e.Item)).(driver.Valuer); isValuer {
// this could panic if the item is nil pointer,
// todo: consider sql.callValuerValue implementation (database/sql/convert.go)
val, err = v.Value()
if err != nil {
return nil, err
}
}
return driver.DefaultParameterConverter.ConvertValue(val)
}
func FirstValid[T any](o ...Optional[T]) Optional[T] {
for _, op := range o {
if op.IsValid() {
return op
}
}
return None[T]()
}