github.com/qlik-oss/gopherciser@v0.18.6/atomichandlers/counter.go (about)

     1  package atomichandlers
     2  
     3  import (
     4  	"fmt"
     5  	"sync/atomic"
     6  )
     7  
     8  type (
     9  	// AtomicCounter atomic integer counter
    10  	AtomicCounter struct {
    11  		counter uint64
    12  	}
    13  )
    14  
    15  // Inc increase counter by 1
    16  func (value *AtomicCounter) Inc() uint64 {
    17  	return atomic.AddUint64(&value.counter, 1)
    18  }
    19  
    20  // Current value of counter
    21  func (value *AtomicCounter) Current() uint64 {
    22  	return atomic.LoadUint64(&value.counter)
    23  }
    24  
    25  // Reset counter to 0
    26  func (value *AtomicCounter) Reset() {
    27  	atomic.StoreUint64(&value.counter, 0)
    28  }
    29  
    30  // Dec decrease the counter by 1
    31  func (value *AtomicCounter) Dec() uint64 {
    32  	return atomic.AddUint64(&value.counter, ^uint64(0))
    33  }
    34  
    35  // Add value to counter
    36  func (value *AtomicCounter) Add(u uint64) uint64 {
    37  	return atomic.AddUint64(&value.counter, u)
    38  }
    39  
    40  // SwapAndCompare new value, returns false without updating to new value if old value no longer the same
    41  func (value *AtomicCounter) CompareAndSwap(old, new uint64) bool {
    42  	return atomic.CompareAndSwapUint64(&value.counter, old, new)
    43  }
    44  
    45  // String representation of counter
    46  func (value *AtomicCounter) String() string {
    47  	return fmt.Sprintf("%d", value.Current())
    48  }