MCPcopy Create free account
hub / github.com/cloudfoundry/bytefmt / ToBytes

Function ToBytes

bytes.go:88–122  ·  view source on GitHub ↗

ToBytes parses a string formatted by ByteSize as bytes. Note binary-prefixed and SI prefixed units both mean a base-2 units KB = K = KiB = 1024 MB = M = MiB = 1024 * K GB = G = GiB = 1024 * M TB = T = TiB = 1024 * G PB = P = PiB = 1024 * T EB = E = EiB = 1024 * P

(s string)

Source from the content-addressed store, hash-verified

86// PB = P = PiB = 1024 * T
87// EB = E = EiB = 1024 * P
88func ToBytes(s string) (uint64, error) {
89 s = strings.TrimSpace(s)
90 s = strings.ToUpper(s)
91
92 i := strings.IndexFunc(s, unicode.IsLetter)
93
94 if i == -1 {
95 return 0, invalidByteQuantityError
96 }
97
98 bytesString, multiple := s[:i], s[i:]
99 bytes, err := strconv.ParseFloat(bytesString, 64)
100 if err != nil || bytes < 0 {
101 return 0, invalidByteQuantityError
102 }
103
104 switch multiple {
105 case "E", "EB", "EIB":
106 return uint64(bytes * EXABYTE), nil
107 case "P", "PB", "PIB":
108 return uint64(bytes * PETABYTE), nil
109 case "T", "TB", "TIB":
110 return uint64(bytes * TERABYTE), nil
111 case "G", "GB", "GIB":
112 return uint64(bytes * GIGABYTE), nil
113 case "M", "MB", "MIB":
114 return uint64(bytes * MEGABYTE), nil
115 case "K", "KB", "KIB":
116 return uint64(bytes * KILOBYTE), nil
117 case "B":
118 return uint64(bytes), nil
119 default:
120 return 0, invalidByteQuantityError
121 }
122}

Callers 3

bytes_test.goFile · 0.85
ToMegabytesFunction · 0.85
BenchmarkToBytesFunction · 0.85

Calls

no outgoing calls

Tested by 1

BenchmarkToBytesFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…