github.com/ethereum/go-ethereum@v1.16.1/metrics/gauge.go (about) 1 package metrics 2 3 import "sync/atomic" 4 5 // GaugeSnapshot is a read-only copy of a Gauge. 6 type GaugeSnapshot int64 7 8 // Value returns the value at the time the snapshot was taken. 9 func (g GaugeSnapshot) Value() int64 { return int64(g) } 10 11 // GetOrRegisterGauge returns an existing Gauge or constructs and registers a 12 // new Gauge. 13 func GetOrRegisterGauge(name string, r Registry) *Gauge { 14 return getOrRegister(name, NewGauge, r) 15 } 16 17 // NewGauge constructs a new Gauge. 18 func NewGauge() *Gauge { 19 return &Gauge{} 20 } 21 22 // NewRegisteredGauge constructs and registers a new Gauge. 23 func NewRegisteredGauge(name string, r Registry) *Gauge { 24 c := NewGauge() 25 if r == nil { 26 r = DefaultRegistry 27 } 28 r.Register(name, c) 29 return c 30 } 31 32 // Gauge holds an int64 value that can be set arbitrarily. 33 type Gauge atomic.Int64 34 35 // Snapshot returns a read-only copy of the gauge. 36 func (g *Gauge) Snapshot() GaugeSnapshot { 37 return GaugeSnapshot((*atomic.Int64)(g).Load()) 38 } 39 40 // Update updates the gauge's value. 41 func (g *Gauge) Update(v int64) { 42 (*atomic.Int64)(g).Store(v) 43 } 44 45 // UpdateIfGt updates the gauge's value if v is larger then the current value. 46 func (g *Gauge) UpdateIfGt(v int64) { 47 value := (*atomic.Int64)(g) 48 for { 49 exist := value.Load() 50 if exist >= v { 51 break 52 } 53 if value.CompareAndSwap(exist, v) { 54 break 55 } 56 } 57 } 58 59 // Dec decrements the gauge's current value by the given amount. 60 func (g *Gauge) Dec(i int64) { 61 (*atomic.Int64)(g).Add(-i) 62 } 63 64 // Inc increments the gauge's current value by the given amount. 65 func (g *Gauge) Inc(i int64) { 66 (*atomic.Int64)(g).Add(i) 67 }