-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathint.go
94 lines (77 loc) · 1.58 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
84
85
86
87
88
89
90
91
92
93
94
package extratypes
import (
"bytes"
"database/sql/driver"
"encoding/json"
"fmt"
)
// Int struct contains int data type that can be null, and also string
// on JSON and SQL, but value will be converted to int type
type Int struct {
Val int
Nil bool
}
func (i Int) String() string {
if i.Nil {
return "nil"
}
return fmt.Sprintf("%d", i.Val)
}
// Value interface for db
func (i Int) Value() (driver.Value, error) {
return int64(i.Val), nil
}
// Scan implement the Scan function from db interface
func (i *Int) Scan(v interface{}) error {
isNil, err := toType(v, &i.Val)
if err != nil {
return err
}
i.Nil = isNil
return nil
}
// MarshalJSON takes a Int and marshal it as a string
func (i Int) MarshalJSON() ([]byte, error) {
if i.Nil {
return json.Marshal(nil)
}
return json.Marshal(i.Val)
}
// UnmarshalJSON takes a slice of bytes and convert it to Int
func (i *Int) UnmarshalJSON(b []byte) error {
var v interface{}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
result, err := toType(v, &i.Val)
if err != nil {
return err
}
i.Nil = result
return nil
}
// MarshalText takes a Int and marshal it as a string
func (i Int) MarshalText() ([]byte, error) {
if i.Nil {
return []byte(""), nil
}
return asByteSlice(i.String()), nil
}
// UnmarshalText takes a slice of bytes and convert it to Int
func (i *Int) UnmarshalText(b []byte) error {
if b == nil {
i.Nil = true
return nil
}
if bytes.Compare(b, []byte("")) == 0 {
i.Nil = true
return nil
}
result, err := toType(b, &i.Val)
if err != nil {
return err
}
i.Nil = result
return nil
}