-
Notifications
You must be signed in to change notification settings - Fork 0
/
float32.go
61 lines (54 loc) · 1.3 KB
/
float32.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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/json"
)
// Float32 holds a nullable float32.
type Float32 struct {
// Float32 is the actual value when Valid.
Float32 float32 `exhaustruct:"optional"`
// Valid when no NULL-value is represented.
Valid bool
}
// NewFloat32 returns a valid Float32 with the given value.
func NewFloat32(f float32) Float32 {
return Float32{
Float32: f,
Valid: true,
}
}
// MarshalJSON marshals the float32. If not valid, a NULL-value is returned.
func (f Float32) MarshalJSON() ([]byte, error) {
if !f.Valid {
return json.Marshal(nil)
}
return json.Marshal(f.Float32)
}
// UnmarshalJSON as float32 or sets Valid to false if null.
func (f *Float32) UnmarshalJSON(data []byte) error {
if isNull(data) {
f.Valid = false
return nil
}
f.Valid = true
return json.Unmarshal(data, &f.Float32)
}
// Scan to float32 value or not valid if nil.
func (f *Float32) Scan(src any) error {
var sqlFloat sql.NullFloat64
err := sqlFloat.Scan(src)
if err != nil {
return err
}
f.Valid = sqlFloat.Valid
f.Float32 = float32(sqlFloat.Float64)
return nil
}
// Value returns the value for satisfying the driver.Valuer interface.
func (f Float32) Value() (driver.Value, error) {
return sql.NullFloat64{
Float64: float64(f.Float32),
Valid: f.Valid,
}.Value()
}