-
Notifications
You must be signed in to change notification settings - Fork 14
/
example_test.go
104 lines (87 loc) · 2.2 KB
/
example_test.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package iocontrol_test
import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"time"
"github.com/aybabtme/iocontrol"
"github.com/dustin/go-humanize"
)
func Example_ThrottledReader() {
totalSize := 10 * iocontrol.KiB
readPerSec := 100 * iocontrol.KiB
maxBurst := 10 * time.Millisecond
input := randBytes(totalSize)
src := bytes.NewReader(input)
measured := iocontrol.NewMeasuredReader(src)
throttled := iocontrol.ThrottledReader(measured, readPerSec, maxBurst)
done := make(chan []byte)
go func() {
start := time.Now()
output, err := ioutil.ReadAll(throttled)
fmt.Printf("done in %.1fs", time.Since(start).Seconds())
if err != nil {
log.Fatalf("error reading: %v", err)
}
done <- output
}()
for {
select {
case <-time.Tick(time.Millisecond * 10):
log.Printf("reading at %s/s", humanize.IBytes(measured.BytesPerSec()))
case output := <-done:
if !bytes.Equal(input, output) {
log.Print("==== input ====\n", hex.Dump(input))
log.Print("==== output ====\n", hex.Dump(output))
log.Fatalf("mismatch between input and output")
}
return
}
}
// Output:
// done in 0.1s
}
func Example_ThrottledWriter() {
totalSize := 10 * iocontrol.KiB
readPerSec := 100 * iocontrol.KiB
maxBurst := 10 * time.Millisecond
input := randBytes(totalSize)
src := bytes.NewReader(input)
dst := bytes.NewBuffer(nil)
measured := iocontrol.NewMeasuredWriter(dst)
throttled := iocontrol.ThrottledWriter(measured, readPerSec, maxBurst)
done := make(chan []byte)
go func() {
start := time.Now()
_, err := io.Copy(throttled, src)
fmt.Printf("done in %.1fs", time.Since(start).Seconds())
if err != nil {
log.Fatalf("error writing: %v", err)
}
done <- dst.Bytes()
}()
for {
select {
case <-time.Tick(time.Millisecond * 10):
log.Printf("writing at %s/s", humanize.IBytes(measured.BytesPerSec()))
case output := <-done:
if !bytes.Equal(input, output) {
log.Print("==== input ====\n", hex.Dump(input))
log.Print("==== output ====\n", hex.Dump(output))
log.Fatalf("mismatch between input and output")
}
return
}
}
// Output:
// done in 0.1s
}
func randBytes(n int) []byte {
b := make([]byte, n)
_, _ = rand.Read(b)
return b
}