Source file
doc/progs/eff_bytesize.go
1
2
3
4
5 package main
6
7 import "fmt"
8
9 type ByteSize float64
10
11 const (
12 _ = iota
13 KB ByteSize = 1 << (10 * iota)
14 MB
15 GB
16 TB
17 PB
18 EB
19 ZB
20 YB
21 )
22
23 func (b ByteSize) String() string {
24 switch {
25 case b >= YB:
26 return fmt.Sprintf("%.2fYB", b/YB)
27 case b >= ZB:
28 return fmt.Sprintf("%.2fZB", b/ZB)
29 case b >= EB:
30 return fmt.Sprintf("%.2fEB", b/EB)
31 case b >= PB:
32 return fmt.Sprintf("%.2fPB", b/PB)
33 case b >= TB:
34 return fmt.Sprintf("%.2fTB", b/TB)
35 case b >= GB:
36 return fmt.Sprintf("%.2fGB", b/GB)
37 case b >= MB:
38 return fmt.Sprintf("%.2fMB", b/MB)
39 case b >= KB:
40 return fmt.Sprintf("%.2fKB", b/KB)
41 }
42 return fmt.Sprintf("%.2fB", b)
43 }
44
45 func main() {
46 fmt.Println(YB, ByteSize(1e13))
47 }
48
View as plain text