-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint.go
More file actions
111 lines (93 loc) · 1.86 KB
/
int.go
File metadata and controls
111 lines (93 loc) · 1.86 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
103
104
105
106
107
108
109
110
111
package nulled
import (
"bytes"
"encoding/gob"
"encoding/json"
"net/url"
"strconv"
"gopkg.in/guregu/null.v4"
)
type Int null.Int
func NewInt(i int64, valid bool) Int {
return Int(null.NewInt(i, valid))
}
func IntFrom(i int64) Int {
return NewInt(i, true)
}
func IntFromPtr(i *int64) Int {
if i == nil {
return NewInt(0, false)
}
return NewInt(*i, true)
}
func (i Int) ValueOrZero() int64 {
if !i.Valid {
return 0
}
return i.Int64
}
func (i Int) EncodeValues(key string, v *url.Values) error {
if !i.Valid {
return nil
}
v.Set(key, strconv.FormatInt(i.Int64, 10))
return nil
}
func (i Int) MarshalJSON() ([]byte, error) {
if !i.Valid {
return []byte(`null`), nil
}
return []byte(strconv.FormatInt(i.Int64, 10)), nil
}
// GobEncode implements the gob.GobEncoder interface.
func (i Int) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(i.Int64)
if err != nil {
return nil, err
}
err = enc.Encode(i.Valid)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// GobDecode implements the gob.GobDecoder interface.
func (i *Int) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&i.Int64)
if err != nil {
return err
}
return dec.Decode(&i.Valid)
}
func (i *Int) UnmarshalJSON(bytes []byte) error {
// 通过类型转换获取值
n := null.Int(*i)
// 处理空字符串或 null 的情况
if string(bytes) == `""` || string(bytes) == `null` || string(bytes) == `nil` {
n.Valid = false
n.Int64 = 0
*i = Int(n)
return nil
}
// 解析数值
err := json.Unmarshal(bytes, &n.Int64)
if err != nil {
n.Valid = false
n.Int64 = 0
*i = Int(n)
return err
}
n.Valid = true
*i = Int(n)
return nil
}
func (i Int) NullValue() null.Int {
if i.Valid {
return null.IntFrom(i.Int64)
}
return null.NewInt(0, false)
}