torrent/ratelimitreader.go

33 lines
615 B
Go
Raw Normal View History

2016-10-10 06:29:39 +00:00
package torrent
import (
"fmt"
2016-10-10 06:29:39 +00:00
"io"
"time"
2017-03-19 06:04:32 +00:00
"golang.org/x/net/context"
2016-10-10 06:29:39 +00:00
"golang.org/x/time/rate"
)
type rateLimitedReader struct {
l *rate.Limiter
r io.Reader
}
func (me rateLimitedReader) Read(b []byte) (n int, err error) {
// Wait until we can read at all.
2016-10-10 06:29:39 +00:00
if err := me.l.WaitN(context.Background(), 1); err != nil {
panic(err)
}
// Limit the read to within the burst.
if me.l.Limit() != rate.Inf && len(b) > me.l.Burst() {
b = b[:me.l.Burst()]
}
2016-10-10 06:29:39 +00:00
n, err = me.r.Read(b)
// Pay the piper.
2016-10-10 06:29:39 +00:00
if !me.l.ReserveN(time.Now(), n-1).OK() {
panic(fmt.Sprintf("burst exceeded?: %d", n-1))
2016-10-10 06:29:39 +00:00
}
return
}