-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnilable.go
50 lines (43 loc) · 1 KB
/
nilable.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
package nilable
import (
"bytes"
"encoding/json"
"reflect"
)
type Nilable[T any] struct {
Item T
Set bool
}
// From converts from non-pointer types to Nilable.
func From[T any](item T) Nilable[T] {
reflectVal := reflect.ValueOf(item)
if (reflectVal.Kind() == reflect.Ptr || reflectVal.Kind() == reflect.Slice || reflectVal.Kind() == reflect.Map) && reflectVal.IsNil() {
return Nilable[T]{Set: false}
}
return Nilable[T]{Item: item, Set: true}
}
// FromPtr converts from pointer types to Nilable.
func FromPtr[T any](item *T) Nilable[T] {
if item == nil {
return Nilable[T]{Set: false}
}
return Nilable[T]{Item: *item, Set: true}
}
func (n Nilable[T]) MarshalJSON() ([]byte, error) {
if !n.Set {
return []byte("null"), nil
}
return json.Marshal(n.Item)
}
func (n *Nilable[T]) UnmarshalJSON(data []byte) error {
if data == nil || bytes.Equal(data, []byte("null")) {
n.Set = false
return nil
}
err := json.Unmarshal(data, &n.Item)
if err != nil {
return err
}
n.Set = true
return nil
}