github.com/ethereum/go-ethereum@v1.16.1/metrics/counter.go (about)

     1  package metrics
     2  
     3  import (
     4  	"sync/atomic"
     5  )
     6  
     7  // GetOrRegisterCounter returns an existing Counter or constructs and registers
     8  // a new Counter.
     9  func GetOrRegisterCounter(name string, r Registry) *Counter {
    10  	return getOrRegister(name, NewCounter, r)
    11  }
    12  
    13  // NewCounter constructs a new Counter.
    14  func NewCounter() *Counter {
    15  	return new(Counter)
    16  }
    17  
    18  // NewRegisteredCounter constructs and registers a new Counter.
    19  func NewRegisteredCounter(name string, r Registry) *Counter {
    20  	c := NewCounter()
    21  	if r == nil {
    22  		r = DefaultRegistry
    23  	}
    24  	r.Register(name, c)
    25  	return c
    26  }
    27  
    28  // CounterSnapshot is a read-only copy of a Counter.
    29  type CounterSnapshot int64
    30  
    31  // Count returns the count at the time the snapshot was taken.
    32  func (c CounterSnapshot) Count() int64 { return int64(c) }
    33  
    34  // Counter hold an int64 value that can be incremented and decremented.
    35  type Counter atomic.Int64
    36  
    37  // Clear sets the counter to zero.
    38  func (c *Counter) Clear() {
    39  	(*atomic.Int64)(c).Store(0)
    40  }
    41  
    42  // Dec decrements the counter by the given amount.
    43  func (c *Counter) Dec(i int64) {
    44  	(*atomic.Int64)(c).Add(-i)
    45  }
    46  
    47  // Inc increments the counter by the given amount.
    48  func (c *Counter) Inc(i int64) {
    49  	(*atomic.Int64)(c).Add(i)
    50  }
    51  
    52  // Snapshot returns a read-only copy of the counter.
    53  func (c *Counter) Snapshot() CounterSnapshot {
    54  	return CounterSnapshot((*atomic.Int64)(c).Load())
    55  }