-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.go
More file actions
102 lines (88 loc) · 1.73 KB
/
composite.go
File metadata and controls
102 lines (88 loc) · 1.73 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
package null
import (
"bytes"
"encoding/json"
)
// Optional[Nullable[int]]
type Null[T any] struct {
value T
isNull bool
}
// Value returns value, false if value is not null, or $zero, true otherwise
func (n Null[T]) Value() (T, bool) {
var zero T
if n.isNull {
return zero, true
}
return n.value, false
}
// NewNull creates new null value.
func NewNull[T any](vals ...T) Null[T] {
switch len(vals) {
case 0:
return Null[T]{
isNull: true,
}
case 1:
return Null[T]{
value: vals[0],
isNull: false,
}
default:
panic("Can't pass more than one value")
}
}
// UnmarshalJSON implements json.Unmarshaler
func (t *Null[T]) UnmarshalJSON(data []byte) error {
var zero T
t.value = zero
if bytes.Equal(data, null) {
t.isNull = true
return nil
}
if err := json.Unmarshal(data, &t.value); err != nil {
return err
}
t.isNull = false
return nil
}
type Option[T any] struct {
value T
isValid bool
}
// Value returns value, false if value is present, or $zero, true otherwise
func (n Option[T]) Value() (T, bool) {
var zero T
if !n.isValid {
return zero, true
}
return n.value, false
}
// NewOption creates new optional value, calling as NewOption[int]() creates missing value
// providing more than one argument panics
func NewOption[T any](vals ...T) Option[T] {
switch len(vals) {
case 0:
return Option[T]{
isValid: false,
}
case 1:
return Option[T]{
value: vals[0],
isValid: true,
}
default:
panic("Can't pass more than one value")
}
}
// UnmarshalJSON implements json.Unmarshaler
func (t *Option[T]) UnmarshalJSON(data []byte) error {
var zero T
t.value = zero
t.isValid = false
if err := json.Unmarshal(data, &t.value); err != nil {
return err
}
t.isValid = true
return nil
}