amuz.es/src/go/misc@v1.0.1/strutil/byte_size.go (about)

     1  package strutil
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  )
     7  
     8  var (
     9  	sizesIEC = []string{
    10  		"B",
    11  		"KiB",
    12  		"MiB",
    13  		"GiB",
    14  		"TiB",
    15  		"PiB",
    16  		"EiB",
    17  		"ZiB",
    18  		"YiB",
    19  	}
    20  	sizes = []string{
    21  		"B",
    22  		"KB",
    23  		"MB",
    24  		"GB",
    25  		"TB",
    26  		"PB",
    27  		"EB",
    28  		"ZB",
    29  		"YB",
    30  	}
    31  )
    32  
    33  func logn(n, b float64) float64 {
    34  	return math.Log(n) / math.Log(b)
    35  }
    36  
    37  func humanateBytes(s uint64, base float64, sizes []string) string {
    38  	if s < 10 {
    39  		return fmt.Sprintf("%dB", s)
    40  	}
    41  	e := math.Floor(logn(float64(s), base))
    42  	suffix := sizes[int(e)]
    43  	val := float64(s) / math.Pow(base, math.Floor(e))
    44  	f := "%.0f"
    45  	if val < 10 {
    46  		f = "%.1f"
    47  	}
    48  
    49  	return fmt.Sprintf(f+"%s", val, suffix)
    50  }
    51  
    52  // FileSize calculates the file size and generate user-friendly string.
    53  func FileSizeIEC(s uint64) string {
    54  	return humanateBytes(s, 1024, sizesIEC)
    55  }
    56  
    57  // FileSize calculates the file size and generate user-friendly string.
    58  func FileSize(s uint64) string {
    59  	return humanateBytes(s, 1000, sizes)
    60  }