bytes.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package bytes
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. )
  7. type (
  8. Bytes struct {
  9. }
  10. )
  11. const (
  12. B = 1 << (10 * iota)
  13. KB
  14. MB
  15. GB
  16. TB
  17. PB
  18. EB
  19. )
  20. var (
  21. pattern = regexp.MustCompile(`(?i)^(-?\d+)([KMGTP]B?|B)$`)
  22. global = New()
  23. )
  24. // New creates a Bytes instance.
  25. func New() *Bytes {
  26. return &Bytes{}
  27. }
  28. // Format formats bytes integer to human readable string.
  29. // For example, 31323 bytes will return 30.59KB.
  30. func (*Bytes) Format(b int) string {
  31. multiple := ""
  32. value := float32(b)
  33. switch {
  34. case b < KB:
  35. return strconv.Itoa(b) + "B"
  36. case b < MB:
  37. value /= KB
  38. multiple = "KB"
  39. case b < MB:
  40. value /= KB
  41. multiple = "KB"
  42. case b < GB:
  43. value /= MB
  44. multiple = "MB"
  45. case b < TB:
  46. value /= GB
  47. multiple = "GB"
  48. case b < PB:
  49. value /= TB
  50. multiple = "TB"
  51. case b < EB:
  52. value /= PB
  53. multiple = "PB"
  54. }
  55. return fmt.Sprintf("%.02f%s", value, multiple)
  56. }
  57. // Parse parses human readable bytes string to bytes integer.
  58. // For example, 6GB (6G is also valid) will return 6442450944.
  59. func (*Bytes) Parse(value string) (i int, err error) {
  60. parts := pattern.FindStringSubmatch(value)
  61. if len(parts) < 3 {
  62. return 0, fmt.Errorf("error parsing value=%s", value)
  63. }
  64. bytesString := parts[1]
  65. multiple := parts[2]
  66. bytes, err := strconv.Atoi(bytesString)
  67. if err != nil {
  68. return
  69. }
  70. switch multiple {
  71. case "B":
  72. return bytes * B, nil
  73. case "K", "KB":
  74. return bytes * KB, nil
  75. case "M", "MB":
  76. return bytes * MB, nil
  77. case "G", "GB":
  78. return bytes * GB, nil
  79. case "T", "TB":
  80. return bytes * TB, nil
  81. case "P", "PB":
  82. return bytes * PB, nil
  83. }
  84. return
  85. }
  86. // Format wraps global Bytes's Format function.
  87. func Format(b int) string {
  88. return global.Format(b)
  89. }
  90. // Parse wraps global Bytes's Parse function.
  91. func Parse(val string) (int, error) {
  92. return global.Parse(val)
  93. }