gytes.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package gytes
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. )
  7. var (
  8. global = New()
  9. )
  10. type (
  11. Gytes struct {
  12. iec bool
  13. }
  14. )
  15. func New() *Gytes {
  16. return &Gytes{}
  17. }
  18. // BinaryPrefix turns on binary prefix format.
  19. func (g *Gytes) BinaryPrefix(on bool) {
  20. g.iec = on
  21. }
  22. // Format formats bytes to string. For example, 1323 bytes will return 1.32 KB.
  23. // If binary prefix is set, it will return 1.29 KiB.
  24. func (g *Gytes) Format(b uint64) string {
  25. unit := uint64(1000)
  26. if g.iec {
  27. unit = 1024
  28. }
  29. if b < unit {
  30. return strconv.FormatUint(b, 10) + " B"
  31. } else {
  32. b := float64(b)
  33. unit := float64(unit)
  34. x := math.Floor(math.Log(b) / math.Log(unit))
  35. pre := make([]byte, 1, 2)
  36. pre[0] = "KMGTPE"[uint8(x)-1]
  37. if g.iec {
  38. pre = pre[:2]
  39. pre[1] = 'i'
  40. }
  41. // TODO: Improve performance?
  42. return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, x), pre)
  43. }
  44. }
  45. // BinaryPrefix wraps default instance's BinaryPrefix function.
  46. func BinaryPrefix(on bool) {
  47. global.BinaryPrefix(on)
  48. }
  49. // Format wraps default instance's Format function.
  50. func Format(b uint64) string {
  51. return global.Format(b)
  52. }