10 // See: http://en.wikipedia.org/wiki/Binary_prefix
29 type unitMap map[string]int64
32 decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB}
33 binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB}
34 sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`)
37 var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
38 var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
40 // CustomSize returns a human-readable approximation of a size
41 // using custom format.
42 func CustomSize(format string, size float64, base float64, _map []string) string {
48 return fmt.Sprintf(format, size, _map[i])
51 // HumanSize returns a human-readable approximation of a size
52 // capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
53 func HumanSize(size float64) string {
54 return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs)
57 // BytesSize returns a human-readable size in bytes, kibibytes,
58 // mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
59 func BytesSize(size float64) string {
60 return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs)
63 // FromHumanSize returns an integer from a human-readable specification of a
64 // size using SI standard (eg. "44kB", "17MB").
65 func FromHumanSize(size string) (int64, error) {
66 return parseSize(size, decimalMap)
69 // RAMInBytes parses a human-readable string representing an amount of RAM
70 // in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and
71 // returns the number of bytes, or -1 if the string is unparseable.
72 // Units are case-insensitive, and the 'b' suffix is optional.
73 func RAMInBytes(size string) (int64, error) {
74 return parseSize(size, binaryMap)
77 // Parses the human-readable size string into the amount it represents.
78 func parseSize(sizeStr string, uMap unitMap) (int64, error) {
79 matches := sizeRegex.FindStringSubmatch(sizeStr)
80 if len(matches) != 3 {
81 return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
84 size, err := strconv.ParseInt(matches[1], 10, 0)
89 unitPrefix := strings.ToLower(matches[2])
90 if mul, ok := uMap[unitPrefix]; ok {