-
Notifications
You must be signed in to change notification settings - Fork 0
/
int.go
83 lines (67 loc) · 1.12 KB
/
int.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
82
83
package nil
import (
"bytes"
"encoding/json"
"strconv"
)
// Int holds data of nullable int value.
type Int struct {
valid bool
value int
}
// Nil
func (s Int) Nil() bool {
return !s.valid
}
// Value
func (s Int) Value() int {
return s.value
}
// String returns string representation of nillable value.
func (s Int) String() string {
if !s.valid {
return "nil"
}
return strconv.Itoa(s.value)
}
// MarshalJSON
func (s Int) MarshalJSON() ([]byte, error) {
if !s.valid {
return []byte("null"), nil
}
return json.Marshal(s.value)
}
// UnmarshalJSON
func (s *Int) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
*s = Int{}
return nil
}
var res int
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
*s = Int{value: res, valid: true}
return nil
}
// NewNilInt creates new nil int value.
func NewNilInt() Int {
return Int{
valid: false,
value: 0,
}
}
// NewInt creates new int value.
func NewInt(value int) Int {
return Int{
valid: true,
value: value,
}
}
func FromIntPtr(value *int) Int {
if value == nil {
return NewNilInt()
}
return NewInt(*value)
}