Signed-off-by: Victor Vieux <vieux@docker.com>
| ... | ... |
@@ -32,18 +32,26 @@ var ( |
| 32 | 32 |
sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`) |
| 33 | 33 |
) |
| 34 | 34 |
|
| 35 |
-var unitAbbrs = [...]string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
|
|
| 35 |
+var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
|
|
| 36 |
+var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
|
|
| 36 | 37 |
|
| 37 | 38 |
// HumanSize returns a human-readable approximation of a size |
| 38 | 39 |
// using SI standard (eg. "44kB", "17MB") |
| 39 | 40 |
func HumanSize(size int64) string {
|
| 41 |
+ return intToString(float64(size), 1000.0, decimapAbbrs) |
|
| 42 |
+} |
|
| 43 |
+ |
|
| 44 |
+func BytesSize(size float64) string {
|
|
| 45 |
+ return intToString(size, 1024.0, binaryAbbrs) |
|
| 46 |
+} |
|
| 47 |
+ |
|
| 48 |
+func intToString(size, unit float64, _map []string) string {
|
|
| 40 | 49 |
i := 0 |
| 41 |
- sizef := float64(size) |
|
| 42 |
- for sizef >= 1000.0 {
|
|
| 43 |
- sizef = sizef / 1000.0 |
|
| 50 |
+ for size >= unit {
|
|
| 51 |
+ size = size / unit |
|
| 44 | 52 |
i++ |
| 45 | 53 |
} |
| 46 |
- return fmt.Sprintf("%.4g %s", sizef, unitAbbrs[i])
|
|
| 54 |
+ return fmt.Sprintf("%.4g %s", size, _map[i])
|
|
| 47 | 55 |
} |
| 48 | 56 |
|
| 49 | 57 |
// FromHumanSize returns an integer from a human-readable specification of a |
| ... | ... |
@@ -7,6 +7,16 @@ import ( |
| 7 | 7 |
"testing" |
| 8 | 8 |
) |
| 9 | 9 |
|
| 10 |
+func TestBytesSize(t *testing.T) {
|
|
| 11 |
+ assertEquals(t, "1 KiB", BytesSize(1024)) |
|
| 12 |
+ assertEquals(t, "1 MiB", BytesSize(1024*1024)) |
|
| 13 |
+ assertEquals(t, "1 MiB", BytesSize(1048576)) |
|
| 14 |
+ assertEquals(t, "2 MiB", BytesSize(2*MiB)) |
|
| 15 |
+ assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) |
|
| 16 |
+ assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) |
|
| 17 |
+ assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) |
|
| 18 |
+} |
|
| 19 |
+ |
|
| 10 | 20 |
func TestHumanSize(t *testing.T) {
|
| 11 | 21 |
assertEquals(t, "1 kB", HumanSize(1000)) |
| 12 | 22 |
assertEquals(t, "1.024 kB", HumanSize(1024)) |