counter.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. // The standard implementation of a Counter uses the sync/atomic package
  14. // to manage a single int64 value.
  15. type StandardCounter struct {
  16. count int64
  17. }
  18. // Force the compiler to check that StandardCounter implements Counter.
  19. var _ Counter = &StandardCounter{}
  20. // Create a new counter.
  21. func NewCounter() *StandardCounter {
  22. return &StandardCounter{0}
  23. }
  24. // Clear the counter: set it to zero.
  25. func (c *StandardCounter) Clear() {
  26. atomic.StoreInt64(&c.count, 0)
  27. }
  28. // Return the current count.
  29. func (c *StandardCounter) Count() int64 {
  30. return atomic.LoadInt64(&c.count)
  31. }
  32. // Decrement the counter by the given amount.
  33. func (c *StandardCounter) Dec(i int64) {
  34. atomic.AddInt64(&c.count, -i)
  35. }
  36. // Increment the counter by the given amount.
  37. func (c *StandardCounter) Inc(i int64) {
  38. atomic.AddInt64(&c.count, i)
  39. }