forked from google/mtail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datum.go
120 lines (99 loc) · 1.93 KB
/
datum.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Copyright 2017 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package datum
import (
"fmt"
"sync/atomic"
"time"
)
type Type int
const (
Int Type = iota
Float
)
func (t Type) String() string {
switch t {
case Int:
return "Int"
case Float:
return "Float"
}
return "?"
}
// Datum
type Datum interface {
// Type returns the Datum type.
Type() Type
ValueString() string
TimeString() string
}
type BaseDatum struct {
Time int64 // nanoseconds since unix epoch
}
var zeroTime time.Time
func (d *BaseDatum) stamp(timestamp time.Time) {
if timestamp.IsZero() {
atomic.StoreInt64(&d.Time, time.Now().UTC().UnixNano())
} else {
atomic.StoreInt64(&d.Time, timestamp.UnixNano())
}
}
func (d *BaseDatum) TimeString() string {
return fmt.Sprintf("%d", atomic.LoadInt64(&d.Time)/1e9)
}
func NewInt() Datum {
return MakeInt(0, zeroTime)
}
func NewFloat() Datum {
return MakeFloat(0., zeroTime)
}
func MakeInt(v int64, ts time.Time) Datum {
d := &IntDatum{}
d.Set(v, ts)
return d
}
func MakeFloat(v float64, ts time.Time) Datum {
d := &FloatDatum{}
d.Set(v, ts)
return d
}
func GetInt(d Datum) int64 {
switch d := d.(type) {
case *IntDatum:
return d.Get()
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
}
func GetFloat(d Datum) float64 {
switch d := d.(type) {
case *FloatDatum:
return d.Get()
default:
panic(fmt.Sprintf("datum %v is not a Float", d))
}
}
func SetInt(d Datum, v int64, ts time.Time) {
switch d := d.(type) {
case *IntDatum:
d.Set(v, ts)
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
}
func SetFloat(d Datum, v float64, ts time.Time) {
switch d := d.(type) {
case *FloatDatum:
d.Set(v, ts)
default:
panic(fmt.Sprintf("datum %v is not a Float", d))
}
}
func IncIntBy(d Datum, v int64, ts time.Time) {
switch d := d.(type) {
case *IntDatum:
d.IncBy(v, ts)
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
}