forked from XinFinOrg/XDPoSChain
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcounter_float64.go
69 lines (57 loc) · 1.85 KB
/
counter_float64.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
package metrics
import (
"math"
"sync/atomic"
)
// GetOrRegisterCounterFloat64 returns an existing *CounterFloat64 or constructs and registers
// a new CounterFloat64.
func GetOrRegisterCounterFloat64(name string, r Registry) *CounterFloat64 {
if nil == r {
r = DefaultRegistry
}
return r.GetOrRegister(name, NewCounterFloat64).(*CounterFloat64)
}
// NewCounterFloat64 constructs a new CounterFloat64.
func NewCounterFloat64() *CounterFloat64 {
return new(CounterFloat64)
}
// NewRegisteredCounterFloat64 constructs and registers a new CounterFloat64.
func NewRegisteredCounterFloat64(name string, r Registry) *CounterFloat64 {
c := NewCounterFloat64()
if r == nil {
r = DefaultRegistry
}
r.Register(name, c)
return c
}
// CounterFloat64Snapshot is a read-only copy of a float64 counter.
type CounterFloat64Snapshot float64
// Count returns the value at the time the snapshot was taken.
func (c CounterFloat64Snapshot) Count() float64 { return float64(c) }
// CounterFloat64 holds a float64 value that can be incremented and decremented.
type CounterFloat64 atomic.Uint64
// Clear sets the counter to zero.
func (c *CounterFloat64) Clear() {
(*atomic.Uint64)(c).Store(0)
}
// Dec decrements the counter by the given amount.
func (c *CounterFloat64) Dec(v float64) {
atomicAddFloat((*atomic.Uint64)(c), -v)
}
// Inc increments the counter by the given amount.
func (c *CounterFloat64) Inc(v float64) {
atomicAddFloat((*atomic.Uint64)(c), v)
}
// Snapshot returns a read-only copy of the counter.
func (c *CounterFloat64) Snapshot() CounterFloat64Snapshot {
return CounterFloat64Snapshot(math.Float64frombits((*atomic.Uint64)(c).Load()))
}
func atomicAddFloat(fbits *atomic.Uint64, v float64) {
for {
loadedBits := fbits.Load()
newBits := math.Float64bits(math.Float64frombits(loadedBits) + v)
if fbits.CompareAndSwap(loadedBits, newBits) {
break
}
}
}