/
point.go
59 lines (47 loc) · 1.3 KB
/
point.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
package series
import (
"encoding/json"
"math"
"time"
)
const (
// DefaultSample represents the default sample value.
DefaultSample = 400
)
// Point represents a time series point instance.
type Point struct {
Time time.Time `json:"time"`
Value Value `json:"value"`
prev *Point
next *Point
}
// MarshalJSON implements the json.Marshaler interface.
func (point Point) MarshalJSON() ([]byte, error) {
return json.Marshal([2]interface{}{int(point.Time.Unix()), point.Value})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (point *Point) UnmarshalJSON(data []byte) error {
input := [2]float64{}
if err := json.Unmarshal(data, &input); err != nil {
return err
}
point.Time = time.Unix(int64(input[0]), 0)
point.Value = Value(input[1])
return nil
}
// Value represents a time series point value.
type Value float64
// MarshalJSON implements the json.Marshaler interface.
func (value Value) MarshalJSON() ([]byte, error) {
// Handle NaN and near-zero values marshalling
if math.IsNaN(float64(value)) {
return json.Marshal(nil)
} else if math.Exp(float64(value)) == 1 {
return json.Marshal(0)
}
return json.Marshal(float64(value))
}
// IsNaN reports whether the Value is an IEEE 754 'not-a-number' value.
func (value Value) IsNaN() bool {
return math.IsNaN(float64(value))
}