From: Matt Joiner Date: Thu, 31 Aug 2017 04:32:22 +0000 (+1000) Subject: Keep rate limited reader reads to within the burst capacity X-Git-Tag: v1.0.0~421 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=cf022be396042e9e929bfc71f2f56bf66793f09a;p=btrtrc.git Keep rate limited reader reads to within the burst capacity --- diff --git a/ratelimitreader.go b/ratelimitreader.go index a8e3483b..d7939a3d 100644 --- a/ratelimitreader.go +++ b/ratelimitreader.go @@ -1,6 +1,7 @@ package torrent import ( + "fmt" "io" "time" @@ -14,12 +15,18 @@ type rateLimitedReader struct { } func (me rateLimitedReader) Read(b []byte) (n int, err error) { + // Wait until we can read at all. 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()] + } n, err = me.r.Read(b) + // Pay the piper. if !me.l.ReserveN(time.Now(), n-1).OK() { - panic(n - 1) + panic(fmt.Sprintf("burst exceeded?: %d", n-1)) } return }