counter.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package metrics
  2. import "sync/atomic"
  3. // Counters hold an int64 value that can be incremented and decremented.
  4. //
  5. // This is an interface so as to encourage other structs to implement
  6. // the Counter API as appropriate.
  7. type Counter interface {
  8. Clear()
  9. Count() int64
  10. Dec(int64)
  11. Inc(int64)
  12. }
  13. // Create a new Counter.
  14. func NewCounter() Counter {
  15. if UseNilMetrics {
  16. return NilCounter{}
  17. }
  18. return &StandardCounter{0}
  19. }
  20. // No-op Counter.
  21. type NilCounter struct{}
  22. // No-op.
  23. func (c NilCounter) Clear() {}
  24. // No-op.
  25. func (c NilCounter) Count() int64 { return 0 }
  26. // No-op.
  27. func (c NilCounter) Dec(i int64) {}
  28. // No-op.
  29. func (c NilCounter) Inc(i int64) {}
  30. // The standard implementation of a Counter uses the sync/atomic package
  31. // to manage a single int64 value.
  32. type StandardCounter struct {
  33. count int64
  34. }
  35. // Clear the counter: set it to zero.
  36. func (c *StandardCounter) Clear() {
  37. atomic.StoreInt64(&c.count, 0)
  38. }
  39. // Return the current count.
  40. func (c *StandardCounter) Count() int64 {
  41. return atomic.LoadInt64(&c.count)
  42. }
  43. // Decrement the counter by the given amount.
  44. func (c *StandardCounter) Dec(i int64) {
  45. atomic.AddInt64(&c.count, -i)
  46. }
  47. // Increment the counter by the given amount.
  48. func (c *StandardCounter) Inc(i int64) {
  49. atomic.AddInt64(&c.count, i)
  50. }