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)
| 86 | // PB = P = PiB = 1024 * T |
| 87 | // EB = E = EiB = 1024 * P |
| 88 | func 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 | } |
no outgoing calls
searching dependent graphs…