counter.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package metrics
  2. import "sync/atomic"
  3. // Counters hold an int64 value that can be incremented and decremented.
  4. type Counter interface {
  5. Clear()
  6. Count() int64
  7. Dec(int64)
  8. Inc(int64)
  9. Snapshot() Counter
  10. }
  11. // GetOrRegisterCounter returns an existing Counter or constructs and registers
  12. // a new StandardCounter.
  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. // NewCounter constructs a new StandardCounter.
  20. func NewCounter() Counter {
  21. if UseNilMetrics {
  22. return NilCounter{}
  23. }
  24. return &StandardCounter{0}
  25. }
  26. // NewRegisteredCounter constructs and registers a new StandardCounter.
  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. // No-op Counter.
  36. type NilCounter struct{}
  37. // Clear is a no-op.
  38. func (NilCounter) Clear() {}
  39. // Count is a no-op.
  40. func (NilCounter) Count() int64 { return 0 }
  41. // Dec is a no-op.
  42. func (NilCounter) Dec(i int64) {}
  43. // Inc is a no-op.
  44. func (NilCounter) Inc(i int64) {}
  45. // The standard implementation of a Counter uses the sync/atomic package
  46. // to manage a single int64 value.
  47. type StandardCounter struct {
  48. count int64
  49. }
  50. // Clear sets the counter to zero.
  51. func (c *StandardCounter) Clear() {
  52. atomic.StoreInt64(&c.count, 0)
  53. }
  54. // Count returns the current count.
  55. func (c *StandardCounter) Count() int64 {
  56. return atomic.LoadInt64(&c.count)
  57. }
  58. // Dec decrements the counter by the given amount.
  59. func (c *StandardCounter) Dec(i int64) {
  60. atomic.AddInt64(&c.count, -i)
  61. }
  62. // Inc increments the counter by the given amount.
  63. func (c *StandardCounter) Inc(i int64) {
  64. atomic.AddInt64(&c.count, i)
  65. }