forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.go
58 lines (47 loc) · 1.36 KB
/
counter.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
package metrics
import (
"sync/atomic"
)
// GetOrRegisterCounter returns an existing Counter or constructs and registers
// a new Counter.
func GetOrRegisterCounter(name string, r Registry) *Counter {
if r == nil {
r = DefaultRegistry
}
return r.GetOrRegister(name, NewCounter).(*Counter)
}
// NewCounter constructs a new Counter.
func NewCounter() *Counter {
return new(Counter)
}
// NewRegisteredCounter constructs and registers a new Counter.
func NewRegisteredCounter(name string, r Registry) *Counter {
c := NewCounter()
if r == nil {
r = DefaultRegistry
}
r.Register(name, c)
return c
}
// CounterSnapshot is a read-only copy of a Counter.
type CounterSnapshot int64
// Count returns the count at the time the snapshot was taken.
func (c CounterSnapshot) Count() int64 { return int64(c) }
// Counter hold an int64 value that can be incremented and decremented.
type Counter atomic.Int64
// Clear sets the counter to zero.
func (c *Counter) Clear() {
(*atomic.Int64)(c).Store(0)
}
// Dec decrements the counter by the given amount.
func (c *Counter) Dec(i int64) {
(*atomic.Int64)(c).Add(-i)
}
// Inc increments the counter by the given amount.
func (c *Counter) Inc(i int64) {
(*atomic.Int64)(c).Add(i)
}
// Snapshot returns a read-only copy of the counter.
func (c *Counter) Snapshot() CounterSnapshot {
return CounterSnapshot((*atomic.Int64)(c).Load())
}