/
nullfloat64.go
98 lines (82 loc) · 1.7 KB
/
nullfloat64.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
package nulltype
import (
"bytes"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"strconv"
"unsafe"
jsoniter "github.com/json-iterator/go"
)
/* SQL and JSon null.Float64 */
type Float64 sql.NullFloat64
func NewFloat64(f float64) Float64 {
nf := Float64{}
nf.Valid = true
nf.Float64 = f
return nf
}
func (nf *Float64) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
val := (*Float64)(ptr)
if val.Valid {
stream.WriteVal(val.Float64)
} else {
stream.WriteVal(nil)
}
}
// IsEmpty detect whether primitive.ObjectID is empty.
func (nf *Float64) IsEmpty(ptr unsafe.Pointer) bool {
val := (*Float64)(ptr)
return !val.Valid
}
func (nf *Float64) UnmarshalCSV(b string) error {
var err error
nf.Float64, err = strconv.ParseFloat(b, 64)
return err
}
// MarshalCSV marshals CSV
func (nf Float64) MarshalCSV() (string, error) {
if nf.Valid {
return fmt.Sprintf("%f", nf.Float64), nil
}
return "", nil
}
func (nf *Float64) UnmarshalJSON(b []byte) error {
var i float64
if err := json.Unmarshal(b, &i); err != nil {
return err
}
if bytes.Compare(b, []byte("null")) == 0 {
nf.Valid = false
return nil
}
nf.Float64 = i
nf.Valid = true
return nil
}
func (nf Float64) MarshalJSON() ([]byte, error) {
if nf.Valid {
return json.Marshal(nf.Float64)
}
return json.Marshal(nil)
}
func (nf *Float64) Scan(value interface{}) error {
var f sql.NullFloat64
if err := f.Scan(value); err != nil {
return err
}
// if nil then make Valid false
if reflect.TypeOf(value) == nil {
*nf = Float64{f.Float64, false}
} else {
*nf = Float64{f.Float64, true}
}
return nil
}
func (nf Float64) Value() (driver.Value, error) {
if !nf.Valid {
return nil, nil
}
return nf.Float64, nil
}