/
float.go
78 lines (68 loc) · 1.6 KB
/
float.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
package slices
import (
"database/sql/driver"
"fmt"
"strconv"
"strings"
)
// Float is a slice of float64.
type Float []float64
// Interface implements the nulls.nullable interface.
func (f Float) Interface() interface{} {
return []float64(f)
}
// Scan implements the sql.Scanner interface.
// It allows to read the float slice from the database value.
func (f *Float) Scan(src interface{}) error {
var str string
switch t := src.(type) {
case []byte:
str = string(t)
case string:
str = t
default:
return fmt.Errorf("scan source was not []byte nor string but %T", src)
}
v, err := strToFloat(str)
*f = v
return err
}
// Value implements the driver.Valuer interface.
// It allows to convert the float slice to a driver.value.
func (f Float) Value() (driver.Value, error) {
sa := make([]string, len(f))
for x, i := range f {
sa[x] = strconv.FormatFloat(i, 'f', -1, 64)
}
return fmt.Sprintf("{%s}", strings.Join(sa, ",")), nil
}
// UnmarshalText will unmarshall text value into
// the float slice representation of this value.
func (f *Float) UnmarshalText(text []byte) error {
var ss []float64
for _, x := range strings.Split(string(text), ",") {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return err
}
ss = append(ss, f)
}
*f = ss
return nil
}
func strToFloat(s string) ([]float64, error) {
r := strings.Trim(s, "{}")
a := make([]float64, 0, 10)
elems := strings.Split(r, ",")
if len(elems) == 1 && elems[0] == "" {
return a, nil
}
for _, t := range elems {
f, err := strconv.ParseFloat(t, 64)
if err != nil {
return nil, err
}
a = append(a, f)
}
return a, nil
}