-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnullable.go
79 lines (67 loc) · 1.57 KB
/
nullable.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
package json
import (
"bytes"
"encoding/json"
)
// NullBytes is a byte slice containing the JSON null literal.
var NullBytes = []byte("null")
// Ptr returns a pointer of t.
func Ptr[T any](t T) *T {
return &t
}
// Null returns a null Nullable.
func Null[T any]() Nullable[T] {
return Nullable[T]{
isNull: true,
}
}
// NullPtr returns a pointer to a null Nullable.
func NullPtr[T any]() *Nullable[T] {
return &Nullable[T]{
isNull: true,
}
}
// NewNullable returns a new Nullable with t as the value.
func NewNullable[T any](t T) Nullable[T] {
return Nullable[T]{
value: t,
isNull: false,
}
}
// NewNullablePtr returns a pointer to a new Nullable with t as the value.
func NewNullablePtr[T any](t T) *Nullable[T] {
return &Nullable[T]{
value: t,
isNull: false,
}
}
// Nullable represents a nullable value.
// It gets serialized as either null or the value.
type Nullable[T any] struct {
value T
isNull bool
}
// MarshalJSON implements the Marshaler interface.
func (n Nullable[T]) MarshalJSON() ([]byte, error) {
if n.isNull {
return NullBytes, nil
}
return json.Marshal(n.value)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (n *Nullable[T]) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullBytes) {
n.isNull = true
return nil
}
return json.Unmarshal(data, &n.value)
}
// Value returns the value of the Nullable.
// If the Nullable is null, it returns the zero value of T.
func (n Nullable[T]) Value() T {
return n.value
}
// IsNull returns true if the Nullable is null.
func (n Nullable[T]) IsNull() bool {
return n.isNull
}