nettools/data_structures/counter.go

54 lines
1.1 KiB
Go

package dsUtils
import "sync/atomic"
type ICounter[i int32 | int64] interface {
Set(new i) (old i)
Add(delta i) (newVal i)
Get() (val i)
}
// Counter32 is a 32 bit implementation of ICounter
type Counter32 struct {
val int32
}
// NewCounter32 creates new Counter32 instance
func NewCounter32(initVal int32) ICounter[int32] {
return &Counter32{val: initVal}
}
func (c *Counter32) Set(new int32) (old int32) {
return atomic.SwapInt32(&c.val, new)
}
func (c *Counter32) Add(delta int32) (newVal int32) {
return atomic.AddInt32(&c.val, delta)
}
func (c *Counter32) Get() (val int32) {
return atomic.LoadInt32(&c.val)
}
// Counter64 is a 64 bit implementation of ICounter
type Counter64 struct {
val int64
}
// NewCounter64 creates new Counter64 instance
func NewCounter64(initVal int64) ICounter[int64] {
return &Counter64{val: initVal}
}
func (c *Counter64) Set(new int64) (old int64) {
return atomic.SwapInt64(&c.val, new)
}
func (c *Counter64) Add(delta int64) (newVal int64) {
return atomic.AddInt64(&c.val, delta)
}
func (c *Counter64) Get() (val int64) {
return atomic.LoadInt64(&c.val)
}