-
-
Notifications
You must be signed in to change notification settings - Fork 628
/
ratelimitreader.go
53 lines (48 loc) · 1.05 KB
/
ratelimitreader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package torrent
import (
"context"
"fmt"
"io"
"time"
"golang.org/x/time/rate"
)
type rateLimitedReader struct {
l *rate.Limiter
r io.Reader
// This is the time of the last Read's reservation.
lastRead time.Time
}
func (me *rateLimitedReader) Read(b []byte) (n int, err error) {
const oldStyle = false // Retained for future reference.
if oldStyle {
// 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.
now := time.Now()
me.lastRead = now
if !me.l.ReserveN(now, n-1).OK() {
panic(fmt.Sprintf("burst exceeded?: %d", n-1))
}
} else {
// 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)
now := time.Now()
r := me.l.ReserveN(now, n)
if !r.OK() {
panic(n)
}
me.lastRead = now
time.Sleep(r.Delay())
}
return
}