Files
waf-platform/EdgeNode/internal/utils/sync/counter.go
2026-02-04 20:27:13 +08:00

47 lines
866 B
Go

// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package syncutils
import (
"sync/atomic"
)
type CounterType interface {
int32 | int64 | uint32 | uint64
}
type Counter[T CounterType] struct {
values *Values[T]
}
func NewCounter[T CounterType]() *Counter[T] {
return &Counter[T]{
values: NewValues[T](func() T {
return 0
}),
}
}
func (this *Counter[T]) Add(delta T) {
this.values.DoUnsafe(func(value *T) {
switch x := any(value).(type) {
case *int32:
atomic.AddInt32(x, int32(delta))
case *int64:
atomic.AddInt64(x, int64(delta))
case *uint32:
atomic.AddUint32(x, uint32(delta))
case *uint64:
atomic.AddUint64(x, uint64(delta))
}
})
}
func (this *Counter[T]) Load() T {
var result T
this.values.DoUnsafeAll(func(value T) {
result += value
})
return result
}