forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgauge.go
70 lines (58 loc) · 1.58 KB
/
gauge.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
package metrics
import "sync/atomic"
// GaugeSnapshot is a read-only copy of a Gauge.
type GaugeSnapshot int64
// Value returns the value at the time the snapshot was taken.
func (g GaugeSnapshot) Value() int64 { return int64(g) }
// GetOrRegisterGauge returns an existing Gauge or constructs and registers a
// new Gauge.
func GetOrRegisterGauge(name string, r Registry) *Gauge {
if r == nil {
r = DefaultRegistry
}
return r.GetOrRegister(name, NewGauge).(*Gauge)
}
// NewGauge constructs a new Gauge.
func NewGauge() *Gauge {
return &Gauge{}
}
// NewRegisteredGauge constructs and registers a new Gauge.
func NewRegisteredGauge(name string, r Registry) *Gauge {
c := NewGauge()
if r == nil {
r = DefaultRegistry
}
r.Register(name, c)
return c
}
// Gauge holds an int64 value that can be set arbitrarily.
type Gauge atomic.Int64
// Snapshot returns a read-only copy of the gauge.
func (g *Gauge) Snapshot() GaugeSnapshot {
return GaugeSnapshot((*atomic.Int64)(g).Load())
}
// Update updates the gauge's value.
func (g *Gauge) Update(v int64) {
(*atomic.Int64)(g).Store(v)
}
// UpdateIfGt updates the gauge's value if v is larger then the current value.
func (g *Gauge) UpdateIfGt(v int64) {
value := (*atomic.Int64)(g)
for {
exist := value.Load()
if exist >= v {
break
}
if value.CompareAndSwap(exist, v) {
break
}
}
}
// Dec decrements the gauge's current value by the given amount.
func (g *Gauge) Dec(i int64) {
(*atomic.Int64)(g).Add(-i)
}
// Inc increments the gauge's current value by the given amount.
func (g *Gauge) Inc(i int64) {
(*atomic.Int64)(g).Add(i)
}