bytes.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package units
  2. // Base2Bytes is the old non-SI power-of-2 byte scale (1024 bytes in a kilobyte,
  3. // etc.).
  4. type Base2Bytes int64
  5. // Base-2 byte units.
  6. const (
  7. Kibibyte Base2Bytes = 1024
  8. KiB = Kibibyte
  9. Mebibyte = Kibibyte * 1024
  10. MiB = Mebibyte
  11. Gibibyte = Mebibyte * 1024
  12. GiB = Gibibyte
  13. Tebibyte = Gibibyte * 1024
  14. TiB = Tebibyte
  15. Pebibyte = Tebibyte * 1024
  16. PiB = Pebibyte
  17. Exbibyte = Pebibyte * 1024
  18. EiB = Exbibyte
  19. )
  20. var (
  21. bytesUnitMap = MakeUnitMap("iB", "B", 1024)
  22. oldBytesUnitMap = MakeUnitMap("B", "B", 1024)
  23. )
  24. // ParseBase2Bytes supports both iB and B in base-2 multipliers. That is, KB
  25. // and KiB are both 1024.
  26. // However "kB", which is the correct SI spelling of 1000 Bytes, is rejected.
  27. func ParseBase2Bytes(s string) (Base2Bytes, error) {
  28. n, err := ParseUnit(s, bytesUnitMap)
  29. if err != nil {
  30. n, err = ParseUnit(s, oldBytesUnitMap)
  31. }
  32. return Base2Bytes(n), err
  33. }
  34. func (b Base2Bytes) String() string {
  35. return ToString(int64(b), 1024, "iB", "B")
  36. }
  37. var (
  38. metricBytesUnitMap = MakeUnitMap("B", "B", 1000)
  39. )
  40. // MetricBytes are SI byte units (1000 bytes in a kilobyte).
  41. type MetricBytes SI
  42. // SI base-10 byte units.
  43. const (
  44. Kilobyte MetricBytes = 1000
  45. KB = Kilobyte
  46. Megabyte = Kilobyte * 1000
  47. MB = Megabyte
  48. Gigabyte = Megabyte * 1000
  49. GB = Gigabyte
  50. Terabyte = Gigabyte * 1000
  51. TB = Terabyte
  52. Petabyte = Terabyte * 1000
  53. PB = Petabyte
  54. Exabyte = Petabyte * 1000
  55. EB = Exabyte
  56. )
  57. // ParseMetricBytes parses base-10 metric byte units. That is, KB is 1000 bytes.
  58. func ParseMetricBytes(s string) (MetricBytes, error) {
  59. n, err := ParseUnit(s, metricBytesUnitMap)
  60. return MetricBytes(n), err
  61. }
  62. // TODO: represents 1000B as uppercase "KB", while SI standard requires "kB".
  63. func (m MetricBytes) String() string {
  64. return ToString(int64(m), 1000, "B", "B")
  65. }
  66. // ParseStrictBytes supports both iB and B suffixes for base 2 and metric,
  67. // respectively. That is, KiB represents 1024 and kB, KB represent 1000.
  68. func ParseStrictBytes(s string) (int64, error) {
  69. n, err := ParseUnit(s, bytesUnitMap)
  70. if err != nil {
  71. n, err = ParseUnit(s, metricBytesUnitMap)
  72. }
  73. return int64(n), err
  74. }