counter.go 1001 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. // Create a new counter.
  19. func NewCounter() *StandardCounter {
  20. return &StandardCounter{0}
  21. }
  22. // Clear the counter: set it to zero.
  23. func (c *StandardCounter) Clear() {
  24. atomic.StoreInt64(&c.count, 0)
  25. }
  26. // Return the current count.
  27. func (c *StandardCounter) Count() int64 {
  28. return atomic.LoadInt64(&c.count)
  29. }
  30. // Decrement the counter by the given amount.
  31. func (c *StandardCounter) Dec(i int64) {
  32. atomic.AddInt64(&c.count, -i)
  33. }
  34. // Increment the counter by the given amount.
  35. func (c *StandardCounter) Inc(i int64) {
  36. atomic.AddInt64(&c.count, i)
  37. }