-
Notifications
You must be signed in to change notification settings - Fork 62
/
null.go
81 lines (66 loc) · 1.52 KB
/
null.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
// SPDX-License-Identifier: AGPL-3.0-only
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
//nolint:musttag
package null
import (
"encoding/json"
)
var _ json.Unmarshaler = (*Null[any])(nil)
// Null is a nullable type.
type Null[T any] struct {
Value T
Set bool
}
func New[T any](t T) Null[T] {
return Null[T]{
Value: t,
Set: true,
}
}
func NewFromPtr[T any](p *T) Null[T] {
if p == nil {
return Null[T]{}
}
return Null[T]{
Value: *p,
Set: true,
}
}
func (t Null[T]) Ptr() *T {
if t.Set {
return &t.Value
}
return nil
}
// Default return default value its value is Null or not Set.
func (t Null[T]) Default(v T) T {
if t.Set {
return t.Value
}
return v
}
func (t Null[T]) Interface() any {
if t.Set {
return t.Value
}
return nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (t *Null[T]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
t.Set = true
return json.Unmarshal(data, &t.Value) //nolint:wrapcheck
}