forked from guregu/null
-
Notifications
You must be signed in to change notification settings - Fork 35
/
int64.go
118 lines (101 loc) · 2.33 KB
/
int64.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package null
import (
"bytes"
"database/sql/driver"
"encoding/json"
"strconv"
"gopkg.in/volatiletech/null.v6/convert"
)
// Int64 is an nullable int64.
type Int64 struct {
Int64 int64
Valid bool
}
// NewInt64 creates a new Int64
func NewInt64(i int64, valid bool) Int64 {
return Int64{
Int64: i,
Valid: valid,
}
}
// Int64From creates a new Int64 that will always be valid.
func Int64From(i int64) Int64 {
return NewInt64(i, true)
}
// Int64FromPtr creates a new Int64 that be null if i is nil.
func Int64FromPtr(i *int64) Int64 {
if i == nil {
return NewInt64(0, false)
}
return NewInt64(*i, true)
}
// UnmarshalJSON implements json.Unmarshaler.
func (i *Int64) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullBytes) {
i.Valid = false
i.Int64 = 0
return nil
}
if err := json.Unmarshal(data, &i.Int64); err != nil {
return err
}
i.Valid = true
return nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (i *Int64) UnmarshalText(text []byte) error {
if text == nil || len(text) == 0 {
i.Valid = false
return nil
}
var err error
i.Int64, err = strconv.ParseInt(string(text), 10, 64)
i.Valid = err == nil
return err
}
// MarshalJSON implements json.Marshaler.
func (i Int64) MarshalJSON() ([]byte, error) {
if !i.Valid {
return NullBytes, nil
}
return []byte(strconv.FormatInt(i.Int64, 10)), nil
}
// MarshalText implements encoding.TextMarshaler.
func (i Int64) MarshalText() ([]byte, error) {
if !i.Valid {
return []byte{}, nil
}
return []byte(strconv.FormatInt(i.Int64, 10)), nil
}
// SetValid changes this Int64's value and also sets it to be non-null.
func (i *Int64) SetValid(n int64) {
i.Int64 = n
i.Valid = true
}
// Ptr returns a pointer to this Int64's value, or a nil pointer if this Int64 is null.
func (i Int64) Ptr() *int64 {
if !i.Valid {
return nil
}
return &i.Int64
}
// IsZero returns true for invalid Int64's, for future omitempty support (Go 1.4?)
func (i Int64) IsZero() bool {
return !i.Valid
}
// Scan implements the Scanner interface.
func (i *Int64) Scan(value interface{}) error {
if value == nil {
i.Int64, i.Valid = 0, false
return nil
}
i.Valid = true
return convert.ConvertAssign(&i.Int64, value)
}
// Value implements the driver Valuer interface.
func (i Int64) Value() (driver.Value, error) {
if !i.Valid {
return nil, nil
}
return i.Int64, nil
}