mirror of
https://github.com/yusing/godoxy.git
synced 2025-05-21 04:52:35 +02:00
48 lines
866 B
Go
48 lines
866 B
Go
package period
|
|
|
|
import (
|
|
"time"
|
|
)
|
|
|
|
type Entries[T any] struct {
|
|
entries [maxEntries]*T
|
|
index int
|
|
count int
|
|
interval time.Duration
|
|
lastAdd time.Time
|
|
}
|
|
|
|
const maxEntries = 100
|
|
|
|
func newEntries[T any](duration time.Duration) *Entries[T] {
|
|
interval := duration / maxEntries
|
|
if interval < time.Second {
|
|
interval = time.Second
|
|
}
|
|
return &Entries[T]{
|
|
interval: interval,
|
|
lastAdd: time.Now(),
|
|
}
|
|
}
|
|
|
|
func (e *Entries[T]) Add(now time.Time, info *T) {
|
|
if now.Sub(e.lastAdd) < e.interval {
|
|
return
|
|
}
|
|
e.entries[e.index] = info
|
|
e.index = (e.index + 1) % maxEntries
|
|
if e.count < maxEntries {
|
|
e.count++
|
|
}
|
|
e.lastAdd = now
|
|
}
|
|
|
|
func (e *Entries[T]) Get() []*T {
|
|
if e.count < maxEntries {
|
|
return e.entries[:e.count]
|
|
}
|
|
res := make([]*T, maxEntries)
|
|
copy(res, e.entries[e.index:])
|
|
copy(res[maxEntries-e.index:], e.entries[:e.index])
|
|
return res
|
|
}
|