-
Notifications
You must be signed in to change notification settings - Fork 2
/
writer.go
47 lines (43 loc) · 869 Bytes
/
writer.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
package ioshape
import (
"io"
"time"
)
// Writer is a traffic shaper struct that implements io.Writer interface. A
// Writer writes to W by B.
// Priority changes between 0(highest) and 15(lowest).
type Writer struct {
W io.Writer // underlying reader
B *Bucket // bucket
Pr int // priority
}
// Write writes to W by b.
func (wr *Writer) Write(p []byte) (n int, err error) {
if wr.B == nil {
n, err = wr.W.Write(p)
return
}
l := len(p)
m := l
for n < l && err == nil {
k := int(wr.B.getTokens(int64(m), wr.Pr))
if k <= 0 {
time.Sleep(time.Second / (freq * freqMul))
continue
}
var nn int
nn, err = wr.W.Write(p[n : n+k])
if nn < 0 || nn > k {
wr.B.giveTokens(int64(k))
err = ErrOutOfRange
continue
}
if nn != k {
wr.B.giveTokens(int64(k - nn))
err = io.ErrShortWrite
}
n += nn
m -= nn
}
return
}