forked from benjojo/bondcat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
devzero.go
78 lines (65 loc) · 1.27 KB
/
devzero.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
package main
import (
"fmt"
"os"
"sync"
"time"
)
func makeDevZero() DevZero {
c := Counter{}
return DevZero{&c, &sync.Mutex{}}
}
type Counter struct {
RX, TX uint64
}
type DevZero struct {
C *Counter
L *sync.Mutex
}
func (D DevZero) Monitor() {
oldRX, oldTX := uint64(0), uint64(0)
for {
D.L.Lock()
fmt.Fprintf(os.Stderr, "RX: %v (%v/s)\t\tTX: %v (%v/s)\n",
ByteCountIEC(int64(D.C.RX)), ByteCountIEC(int64(D.C.RX-oldRX)),
ByteCountIEC(int64(D.C.TX)), ByteCountIEC(int64(D.C.TX-oldTX)))
oldRX, oldTX = D.C.RX, D.C.TX
D.L.Unlock()
time.Sleep(time.Second)
}
}
func (D DevZero) Close() error {
return nil
}
func (D DevZero) Write(b []byte) (int, error) {
D.L.Lock()
defer D.L.Unlock()
D.C.RX += uint64(len(b))
return len(b), nil
}
func (D DevZero) Read(b []byte) (int, error) {
D.L.Lock()
defer D.L.Unlock()
for k := range b {
b[k] = 0x00
}
transmitted := len(b)
if len(b) < transmitted {
transmitted = len(b)
}
D.C.TX += uint64(transmitted)
return transmitted, nil
}
func ByteCountIEC(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB",
float64(b)/float64(div), "KMGTPE"[exp])
}