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