-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloat.go
More file actions
110 lines (95 loc) · 1.9 KB
/
float.go
File metadata and controls
110 lines (95 loc) · 1.9 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
package nulled
import (
"bytes"
"encoding/gob"
"encoding/json"
"net/url"
"strconv"
"gopkg.in/guregu/null.v4"
)
type Float null.Float
func NewFloat(i float64, valid bool) Float {
return Float(null.NewFloat(i, valid))
}
func FloatFrom(i float64) Float {
return NewFloat(i, true)
}
func FloatFromPtr(f *float64) Float {
if f == nil {
return NewFloat(0, false)
}
return NewFloat(*f, true)
}
func (f Float) ValueOrZero() float64 {
if !f.Valid {
return 0
}
return f.Float64
}
func (f Float) EncodeValues(key string, v *url.Values) error {
if !f.Valid {
return nil
}
v.Set(key, strconv.FormatFloat(f.Float64, 'f', -1, 64))
return nil
}
func (f Float) MarshalJSON() ([]byte, error) {
if !f.Valid {
return []byte("null"), nil
}
return json.Marshal(f.Float64)
}
func (f *Float) UnmarshalJSON(data []byte) error {
temp := null.Float{}
if err := json.Unmarshal(data, &temp); err != nil {
f.Valid = false
return err
}
f.Float64 = temp.Float64
f.Valid = temp.Valid
return nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (f *Float) UnmarshalText(text []byte) error {
s := string(text)
if s == "" || s == "null" {
f.Valid = false
return nil
}
var err error
f.Float64, err = strconv.ParseFloat(s, 64)
if err != nil {
f.Valid = false
return err
}
f.Valid = true
return nil
}
func (f Float) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(f.Float64)
if err != nil {
return nil, err
}
err = enc.Encode(f.Valid)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (f *Float) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&f.Float64)
if err != nil {
return err
}
return dec.Decode(&f.Valid)
}
func (f Float) NullValue() null.Float {
if f.Valid {
return null.FloatFrom(f.Float64)
}
return null.NewFloat(0, false)
}