counter.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // Force the compiler to check that NilCounter implements Counter.
  23. var _ Counter = NilCounter{}
  24. // No-op.
  25. func (c NilCounter) Clear() {}
  26. // No-op.
  27. func (c NilCounter) Count() int64 { return 0 }
  28. // No-op.
  29. func (c NilCounter) Dec(i int64) {}
  30. // No-op.
  31. func (c NilCounter) Inc(i int64) {}
  32. // The standard implementation of a Counter uses the sync/atomic package
  33. // to manage a single int64 value.
  34. type StandardCounter struct {
  35. count int64
  36. }
  37. // Force the compiler to check that StandardCounter implements Counter.
  38. var _ Counter = &StandardCounter{}
  39. // Clear the counter: set it to zero.
  40. func (c *StandardCounter) Clear() {
  41. atomic.StoreInt64(&c.count, 0)
  42. }
  43. // Return the current count.
  44. func (c *StandardCounter) Count() int64 {
  45. return atomic.LoadInt64(&c.count)
  46. }
  47. // Decrement the counter by the given amount.
  48. func (c *StandardCounter) Dec(i int64) {
  49. atomic.AddInt64(&c.count, -i)
  50. }
  51. // Increment the counter by the given amount.
  52. func (c *StandardCounter) Inc(i int64) {
  53. atomic.AddInt64(&c.count, i)
  54. }