2020-11-04 14:11:29 +01:00
|
|
|
package progress
|
|
|
|
|
|
|
|
|
|
import (
|
2025-09-16 09:46:46 +02:00
|
|
|
"sync/atomic"
|
2020-11-04 14:11:29 +01:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// A Func is a callback for a Counter.
|
|
|
|
|
//
|
|
|
|
|
// The final argument is true if Counter.Done has been called,
|
|
|
|
|
// which means that the current call will be the last.
|
2020-12-05 23:57:06 +01:00
|
|
|
type Func func(value uint64, total uint64, runtime time.Duration, final bool)
|
2020-11-04 14:11:29 +01:00
|
|
|
|
|
|
|
|
// A Counter tracks a running count and controls a goroutine that passes its
|
|
|
|
|
// value periodically to a Func.
|
|
|
|
|
//
|
|
|
|
|
// The Func is also called when SIGUSR1 (or SIGINFO, on BSD) is received.
|
|
|
|
|
type Counter struct {
|
2022-12-29 12:29:46 +01:00
|
|
|
Updater
|
2025-09-16 09:46:46 +02:00
|
|
|
value, max atomic.Uint64
|
2020-11-04 14:11:29 +01:00
|
|
|
}
|
|
|
|
|
|
2022-12-29 12:29:46 +01:00
|
|
|
// NewCounter starts a new Counter.
|
|
|
|
|
func NewCounter(interval time.Duration, total uint64, report Func) *Counter {
|
2025-09-16 09:46:46 +02:00
|
|
|
c := new(Counter)
|
|
|
|
|
c.max.Store(total)
|
2022-12-29 12:29:46 +01:00
|
|
|
c.Updater = *NewUpdater(interval, func(runtime time.Duration, final bool) {
|
2025-02-28 20:00:40 +00:00
|
|
|
v, maxV := c.Get()
|
|
|
|
|
report(v, maxV, runtime, final)
|
2022-12-29 12:29:46 +01:00
|
|
|
})
|
2020-11-04 14:11:29 +01:00
|
|
|
return c
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add v to the Counter. This method is concurrency-safe.
|
|
|
|
|
func (c *Counter) Add(v uint64) {
|
2025-09-16 09:46:46 +02:00
|
|
|
if c != nil {
|
|
|
|
|
c.value.Add(v)
|
2020-11-04 14:11:29 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-05 23:57:06 +01:00
|
|
|
// SetMax sets the maximum expected counter value. This method is concurrency-safe.
|
|
|
|
|
func (c *Counter) SetMax(max uint64) {
|
2025-09-16 09:46:46 +02:00
|
|
|
if c != nil {
|
|
|
|
|
c.max.Store(max)
|
2020-12-05 23:57:06 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-25 07:41:44 +02:00
|
|
|
// Get returns the current value and the maximum of c.
|
|
|
|
|
// This method is concurrency-safe.
|
|
|
|
|
func (c *Counter) Get() (v, max uint64) {
|
2025-09-16 09:46:46 +02:00
|
|
|
return c.value.Load(), c.max.Load()
|
2020-12-05 23:57:06 +01:00
|
|
|
}
|
|
|
|
|
|
2022-12-29 12:29:46 +01:00
|
|
|
func (c *Counter) Done() {
|
|
|
|
|
if c != nil {
|
|
|
|
|
c.Updater.Done()
|
2020-11-04 14:11:29 +01:00
|
|
|
}
|
|
|
|
|
}
|