github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/utilities/metrics/counter.go (about)

     1  package metrics
     2  
     3  import "sync/atomic"
     4  
     5  type Counter interface {
     6  	Clear()
     7  	Count() int64
     8  	Dec(int64)
     9  	Inc(int64)
    10  	Snapshot() Counter
    11  }
    12  
    13  func GetOrRegisterCounter(name string, r Registry) Counter {
    14  	if nil == r {
    15  		r = DefaultRegistry
    16  	}
    17  	return r.GetOrRegister(name, NewCounter).(Counter)
    18  }
    19  
    20  func NewCounter() Counter {
    21  	if !Enabled {
    22  		return NilCounter{}
    23  	}
    24  	return &StandardCounter{0}
    25  }
    26  
    27  func NewRegisteredCounter(name string, r Registry) Counter {
    28  	c := NewCounter()
    29  	if nil == r {
    30  		r = DefaultRegistry
    31  	}
    32  	r.Register(name, c)
    33  	return c
    34  }
    35  
    36  type CounterSnapshot int64
    37  
    38  func (CounterSnapshot) Clear() {
    39  	panic("Clear called on a CounterSnapshot")
    40  }
    41  
    42  func (c CounterSnapshot) Count() int64 { return int64(c) }
    43  
    44  func (CounterSnapshot) Dec(int64) {
    45  	panic("Dec called on a CounterSnapshot")
    46  }
    47  
    48  func (CounterSnapshot) Inc(int64) {
    49  	panic("Inc called on a CounterSnapshot")
    50  }
    51  
    52  func (c CounterSnapshot) Snapshot() Counter { return c }
    53  
    54  type NilCounter struct{}
    55  
    56  func (NilCounter) Clear() {}
    57  
    58  func (NilCounter) Count() int64 { return 0 }
    59  
    60  func (NilCounter) Dec(i int64) {}
    61  
    62  func (NilCounter) Inc(i int64) {}
    63  
    64  func (NilCounter) Snapshot() Counter { return NilCounter{} }
    65  
    66  type StandardCounter struct {
    67  	count int64
    68  }
    69  
    70  func (c *StandardCounter) Clear() {
    71  	atomic.StoreInt64(&c.count, 0)
    72  }
    73  
    74  func (c *StandardCounter) Count() int64 {
    75  	return atomic.LoadInt64(&c.count)
    76  }
    77  
    78  func (c *StandardCounter) Dec(i int64) {
    79  	atomic.AddInt64(&c.count, -i)
    80  }
    81  
    82  func (c *StandardCounter) Inc(i int64) {
    83  	atomic.AddInt64(&c.count, i)
    84  }
    85  
    86  func (c *StandardCounter) Snapshot() Counter {
    87  	return CounterSnapshot(c.Count())
    88  }