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. When the latest weeklies land in a
  15. // release, atomic.LoadInt64 will be available and this code will become
  16. // safe on 32-bit architectures.
  17. type StandardCounter struct {
  18. count int64
  19. }
  20. // Create a new counter.
  21. func NewCounter() Counter {
  22. return &StandardCounter{0}
  23. }
  24. // Clear the counter: set it to zero.
  25. func (c *StandardCounter) Clear() {
  26. c.count = 0
  27. }
  28. // Return the current count. This is the method that's currently unsafe
  29. // on 32-bit architectures.
  30. func (c *StandardCounter) Count() int64 {
  31. return c.count
  32. }
  33. // Decrement the counter by the given amount.
  34. func (c *StandardCounter) Dec(i int64) {
  35. atomic.AddInt64(&c.count, -i)
  36. }
  37. // Increment the counter by the given amount.
  38. func (c *StandardCounter) Inc(i int64) {
  39. atomic.AddInt64(&c.count, i)
  40. }