forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes.go
80 lines (68 loc) · 1.52 KB
/
bytes.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
79
80
package formatters
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
. "github.com/cloudfoundry/cli/cf/i18n"
)
const (
BYTE = 1.0
KILOBYTE = 1024 * BYTE
MEGABYTE = 1024 * KILOBYTE
GIGABYTE = 1024 * MEGABYTE
TERABYTE = 1024 * GIGABYTE
)
func ByteSize(bytes int64) string {
unit := ""
value := float32(bytes)
switch {
case bytes >= TERABYTE:
unit = "T"
value = value / TERABYTE
case bytes >= GIGABYTE:
unit = "G"
value = value / GIGABYTE
case bytes >= MEGABYTE:
unit = "M"
value = value / MEGABYTE
case bytes >= KILOBYTE:
unit = "K"
value = value / KILOBYTE
case bytes == 0:
return "0"
}
stringValue := fmt.Sprintf("%.1f", value)
stringValue = strings.TrimSuffix(stringValue, ".0")
return fmt.Sprintf("%s%s", stringValue, unit)
}
func ToMegabytes(s string) (int64, error) {
parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
if len(parts) < 3 {
return 0, invalidByteQuantityError()
}
value, err := strconv.ParseInt(parts[1], 10, 0)
if err != nil {
return 0, invalidByteQuantityError()
}
var bytes int64
unit := strings.ToUpper(parts[2])
switch unit {
case "T":
bytes = value * TERABYTE
case "G":
bytes = value * GIGABYTE
case "M":
bytes = value * MEGABYTE
case "K":
bytes = value * KILOBYTE
}
return bytes / MEGABYTE, nil
}
var (
bytesPattern *regexp.Regexp = regexp.MustCompile(`(?i)^(-?\d+)([KMGT])B?$`)
)
func invalidByteQuantityError() error {
return errors.New(T("Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB"))
}