/
value_type.go
75 lines (66 loc) · 1.69 KB
/
value_type.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
package metrics
import "errors"
// Possible values for ValueType.
const (
Default = ValueType(iota) // Values are presented as-is
Time // Values are time durations (milliseconds)
Data // Values are data amounts (bytes)
Negative // Values represent negative events (e.g. failed requests)
)
// ErrInvalidValueType indicates the serialized value type is invalid.
var ErrInvalidValueType = errors.New("invalid value type")
// ValueType holds the type of values a metric contains.
type ValueType int
// MarshalJSON serializes a ValueType to a JSON string.
func (t ValueType) MarshalJSON() ([]byte, error) {
txt, err := t.MarshalText()
if err != nil {
return nil, err
}
return []byte(`"` + string(txt) + `"`), nil
}
// MarshalText serializes a ValueType as a human readable string.
func (t ValueType) MarshalText() ([]byte, error) {
switch t {
case Default:
return []byte(defaultString), nil
case Time:
return []byte(timeString), nil
case Data:
return []byte(dataString), nil
case Negative:
return []byte(negativeString), nil
default:
return nil, ErrInvalidValueType
}
}
// UnmarshalText deserializes a ValueType from a string representation.
func (t *ValueType) UnmarshalText(data []byte) error {
switch string(data) {
case defaultString:
*t = Default
case timeString:
*t = Time
case dataString:
*t = Data
case negativeString:
*t = Negative
default:
return ErrInvalidValueType
}
return nil
}
func (t ValueType) String() string {
switch t {
case Default:
return defaultString
case Time:
return timeString
case Data:
return dataString
case Negative:
return negativeString
default:
return "[INVALID]"
}
}