counter.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // NewCounter constructs a new StandardCounter.
  12. func NewCounter() Counter {
  13. return &StandardCounter{0}
  14. }
  15. // CounterSnapshot is a read-only copy of another Counter.
  16. type CounterSnapshot int64
  17. // Clear panics.
  18. func (CounterSnapshot) Clear() {
  19. panic("Clear called on a CounterSnapshot")
  20. }
  21. // Count returns the count at the time the snapshot was taken.
  22. func (c CounterSnapshot) Count() int64 { return int64(c) }
  23. // Dec panics.
  24. func (CounterSnapshot) Dec(int64) {
  25. panic("Dec called on a CounterSnapshot")
  26. }
  27. // Inc panics.
  28. func (CounterSnapshot) Inc(int64) {
  29. panic("Inc called on a CounterSnapshot")
  30. }
  31. // Snapshot returns the snapshot.
  32. func (c CounterSnapshot) Snapshot() Counter { return c }
  33. // StandardCounter is the standard implementation of a Counter and uses the
  34. // sync/atomic package to manage a single int64 value.
  35. type StandardCounter struct {
  36. count int64
  37. }
  38. // Clear sets the counter to zero.
  39. func (c *StandardCounter) Clear() {
  40. atomic.StoreInt64(&c.count, 0)
  41. }
  42. // Count returns the current count.
  43. func (c *StandardCounter) Count() int64 {
  44. return atomic.LoadInt64(&c.count)
  45. }
  46. // Dec decrements the counter by the given amount.
  47. func (c *StandardCounter) Dec(i int64) {
  48. atomic.AddInt64(&c.count, -i)
  49. }
  50. // Inc increments the counter by the given amount.
  51. func (c *StandardCounter) Inc(i int64) {
  52. atomic.AddInt64(&c.count, i)
  53. }
  54. // Snapshot returns a read-only copy of the counter.
  55. func (c *StandardCounter) Snapshot() Counter {
  56. return CounterSnapshot(c.Count())
  57. }