Files
2026-06-05 17:26:44 +08:00

45 lines
779 B
Go

package limit
import (
"math"
"time"
)
type Limiter struct {
mbps float64
bytesPerSecond int64
}
func New(mbps float64) Limiter {
if mbps <= 0 {
return Limiter{}
}
return Limiter{
mbps: mbps,
bytesPerSecond: int64(math.Round(mbps * 1_000_000 / 8)),
}
}
func (l Limiter) Enabled() bool {
return l.bytesPerSecond > 0
}
func (l Limiter) Mbps() float64 {
return l.mbps
}
func (l Limiter) BytesPerSecond() int64 {
return l.bytesPerSecond
}
func (l Limiter) DelayFor(bytesSent int64, elapsed time.Duration) time.Duration {
if !l.Enabled() || bytesSent <= 0 {
return 0
}
expected := time.Duration(float64(bytesSent) / float64(l.bytesPerSecond) * float64(time.Second))
if expected <= elapsed {
return 0
}
return expected - elapsed
}