counter.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package tapdance
  2. import "sync"
  3. // CounterUint64 is a goroutine-safe uint64 counter.
  4. // Wraps, if underflows/overflows.
  5. type CounterUint64 struct {
  6. sync.RWMutex
  7. value uint64
  8. }
  9. // Inc increases the counter and returns resulting value
  10. func (c *CounterUint64) Inc() uint64 {
  11. c.Lock()
  12. defer c.Unlock()
  13. if c.value == ^uint64(0) {
  14. // if max
  15. c.value = 0
  16. } else {
  17. c.value++
  18. }
  19. return c.value
  20. }
  21. // GetAndInc returns current value and then increases the counter
  22. func (c *CounterUint64) GetAndInc() uint64 {
  23. c.Lock()
  24. retVal := c.value
  25. if c.value == ^uint64(0) {
  26. // if max
  27. c.value = 0
  28. } else {
  29. c.value++
  30. }
  31. c.Unlock()
  32. return retVal
  33. }
  34. // Dec decrements the counter and returns resulting value
  35. func (c *CounterUint64) Dec() uint64 {
  36. c.Lock()
  37. defer c.Unlock()
  38. if c.value == 0 {
  39. c.value = ^uint64(0)
  40. } else {
  41. c.value--
  42. }
  43. return c.value
  44. }
  45. // Get returns current counter value
  46. func (c *CounterUint64) Get() (value uint64) {
  47. c.RLock()
  48. value = c.value
  49. c.RUnlock()
  50. return
  51. }
  52. // Set assigns current counter value
  53. func (c *CounterUint64) Set(value uint64) {
  54. c.Lock()
  55. c.value = value
  56. c.Unlock()
  57. return
  58. }