-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathbytecounter.go
54 lines (46 loc) · 1.2 KB
/
bytecounter.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
// Package bytecounter contains a io.ReadWriter wrapper that allows to count read and written bytes.
package bytecounter
import (
"io"
"sync/atomic"
)
// ByteCounter is a io.ReadWriter wrapper that allows to count read and written bytes.
type ByteCounter struct {
rw io.ReadWriter
received *uint64
sent *uint64
}
// New allocates a ByteCounter.
func New(rw io.ReadWriter, received *uint64, sent *uint64) *ByteCounter {
if received == nil {
received = new(uint64)
}
if sent == nil {
sent = new(uint64)
}
return &ByteCounter{
rw: rw,
received: received,
sent: sent,
}
}
// Read implements io.ReadWriter.
func (bc *ByteCounter) Read(p []byte) (int, error) {
n, err := bc.rw.Read(p)
atomic.AddUint64(bc.received, uint64(n))
return n, err
}
// Write implements io.ReadWriter.
func (bc *ByteCounter) Write(p []byte) (int, error) {
n, err := bc.rw.Write(p)
atomic.AddUint64(bc.sent, uint64(n))
return n, err
}
// BytesReceived returns the number of bytes received.
func (bc *ByteCounter) BytesReceived() uint64 {
return atomic.LoadUint64(bc.received)
}
// BytesSent returns the number of bytes sent.
func (bc *ByteCounter) BytesSent() uint64 {
return atomic.LoadUint64(bc.sent)
}