-
Notifications
You must be signed in to change notification settings - Fork 10
/
util.go
54 lines (46 loc) · 1015 Bytes
/
util.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
// Copyright 2016 Gareth Watts
// Licensed under an MIT license
// See the LICENSE file for details
package main
import (
"fmt"
"io"
"sync/atomic"
)
const (
kib = 1 << 10
mib = 1 << 20
gib = 1 << 30
tib = 1 << 40
)
func fmtBytes(bytes int64) string {
switch {
case bytes < 0:
return "unknown"
case bytes < kib:
return fmt.Sprintf("%d bytes", bytes)
case bytes < mib:
return fmt.Sprintf("%.1f KB", float64(bytes)/kib)
case bytes < gib:
return fmt.Sprintf("%.1f MB", float64(bytes)/mib)
case bytes < tib:
return fmt.Sprintf("%.1f GB", float64(bytes)/gib)
default:
return fmt.Sprintf("%.1f TB", float64(bytes)/tib)
}
}
type readWatcher struct {
io.Reader
bytesRead int64
}
func newReadWatcher(r io.Reader) *readWatcher {
return &readWatcher{Reader: r}
}
func (r *readWatcher) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
atomic.AddInt64(&r.bytesRead, int64(n))
return n, err
}
func (r *readWatcher) BytesRead() int64 {
return atomic.LoadInt64(&r.bytesRead)
}