github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/counter.go (about)

     1  package util
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  )
     7  
     8  var (
     9  	_CounterPool = sync.Pool{
    10  		New: func() any {
    11  			return &Counter{}
    12  		},
    13  	}
    14  )
    15  
    16  func SpawnCounter(total uint32) *Counter {
    17  	c := _CounterPool.Get().(*Counter)
    18  	c.total = total
    19  	return c
    20  }
    21  
    22  func RecycleCounter(c *Counter) {
    23  	_CounterPool.Put(c)
    24  }
    25  
    26  func NewCounter(total uint32) *Counter {
    27  	return &Counter{
    28  		total: total,
    29  	}
    30  }
    31  
    32  type Counter struct {
    33  	total uint32
    34  	count uint32
    35  }
    36  
    37  func (c *Counter) Total() uint32 {
    38  	return c.total
    39  }
    40  
    41  func (c *Counter) Count() uint32 {
    42  	return c.count
    43  }
    44  
    45  func (c *Counter) Reset(total uint32) {
    46  	c.count = 0
    47  	c.total = total
    48  }
    49  
    50  func (c *Counter) Add(v uint32) (uint32, bool) {
    51  	n := atomic.AddUint32(&c.count, v)
    52  	return n, n == c.total
    53  }