/
primitives.go
106 lines (89 loc) · 2.05 KB
/
primitives.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
99
100
101
102
103
104
105
106
// Copyright (C) 2014 Constantin Schomburg <me@cschomburg.com>
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package meals
import (
"fmt"
"strconv"
"strings"
)
type Weight float64
type Volume float64
type Energy float64
const (
Milligram Weight = 1.0 / 1000
Gram Weight = 1000 * Milligram
Kilogram = 1000 * Gram
Joule Energy = 1.0 / 1000
Kilojoule = 1000 * Joule
Kcal = 4184 * Joule
Millilitre Volume = 1.0
Litre Volume = 1000 * Millilitre
)
func (w *Weight) UnmarshalJSON(item []byte) error {
s := strings.Trim(string(item), `"`)
n, err := strconv.ParseFloat(s, 64)
*w = Weight(n)
return err
}
func (w *Volume) UnmarshalJSON(item []byte) error {
s := strings.Trim(string(item), `"`)
n, err := strconv.ParseFloat(s, 64)
*w = Volume(n)
return err
}
func (w *Energy) UnmarshalJSON(item []byte) error {
s := strings.Trim(string(item), `"`)
n, err := strconv.ParseFloat(s, 64)
*w = Energy(n)
return err
}
func convertToFloat64(src interface{}) (float64, error) {
switch v := src.(type) {
case float64:
return v, nil
case []uint8:
return strconv.ParseFloat(string(v), 64)
}
return 0, fmt.Errorf("cannot convert %v (%T) to float64", src, src)
}
func (w *Weight) Scan(src interface{}) error {
v, err := convertToFloat64(src)
if err == nil {
*w = Weight(v)
}
return err
}
func (w *Volume) Scan(src interface{}) error {
v, err := convertToFloat64(src)
if err == nil {
*w = Volume(v)
}
return err
}
func (w *Energy) Scan(src interface{}) error {
v, err := convertToFloat64(src)
if err == nil {
*w = Energy(v)
}
return err
}
func (v Weight) String() string {
if v >= Kilogram {
return fmt.Sprintf("%.5g kg", v/Kilogram)
}
return fmt.Sprintf("%.5g g", v)
}
func (v Volume) String() string {
if v >= Litre {
return fmt.Sprintf("%.5g l", v/Litre)
}
return fmt.Sprintf("%.5g ml", v)
}
func (v Energy) String() string {
return fmt.Sprintf("%.5g kJ", v)
}
func (v Energy) StringKcal() string {
return fmt.Sprintf("%.5g kcal", v/Kcal)
}