Documentation
¶
Overview ¶
Package ratelimit provides bandwidth throttling functionality for downloads.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatRate ¶
FormatRate formats a rate in bytes per second to a human-readable string.
func ParseRate ¶
ParseRate parses a human-readable rate string into bytes per second. Supports formats like:
- "1048576" (bytes per second)
- "1MB/s", "1mb/s" (megabytes per second)
- "500KB/s", "500k/s" (kilobytes per second)
- "2GB/s", "2g/s" (gigabytes per second)
- "1MB", "500k" (without /s suffix)
Returns 0 for invalid input or explicit "0".
func ValidateRate ¶
ValidateRate checks if a rate string is valid without parsing it.
Types ¶
type BandwidthLimiter ¶
type BandwidthLimiter struct {
// contains filtered or unexported fields
}
BandwidthLimiter implements thread-safe bandwidth limiting using a token bucket algorithm.
func NewBandwidthLimiter ¶
func NewBandwidthLimiter(maxRate int64) *BandwidthLimiter
NewBandwidthLimiter creates a new bandwidth limiter. maxRate is in bytes per second. A value of 0 means unlimited.
func (*BandwidthLimiter) Allow ¶
func (bl *BandwidthLimiter) Allow(n int) bool
Allow reports whether n bytes can be processed immediately.
func (*BandwidthLimiter) Rate ¶
func (bl *BandwidthLimiter) Rate() int64
Rate returns the current rate limit in bytes per second.
func (*BandwidthLimiter) SetRate ¶
func (bl *BandwidthLimiter) SetRate(bytesPerSec int64)
SetRate updates the rate limit. A value of 0 means unlimited.
type Limiter ¶
type Limiter interface {
// Wait blocks until the limiter allows n bytes to be processed.
// Returns an error if the context is cancelled.
Wait(ctx context.Context, n int) error
// Allow reports whether n bytes can be processed immediately.
Allow(n int) bool
// Rate returns the current rate limit in bytes per second.
Rate() int64
// SetRate updates the rate limit. A value of 0 means unlimited.
SetRate(bytesPerSec int64)
}
Limiter interface defines the contract for bandwidth limiting.
type NullLimiter ¶
type NullLimiter struct{}
NullLimiter is a no-op limiter that allows unlimited bandwidth.
func NewNullLimiter ¶
func NewNullLimiter() *NullLimiter
NewNullLimiter creates a limiter that imposes no limits.
func (*NullLimiter) SetRate ¶
func (nl *NullLimiter) SetRate(bytesPerSec int64)
SetRate is a no-op for the null limiter.