bytes.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Copyright 2016 The Rook Authors. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package display
  14. import (
  15. "fmt"
  16. "math"
  17. )
  18. const (
  19. // KiB kibibyte
  20. KiB uint64 = 1024
  21. // MiB mebibyte
  22. MiB uint64 = KiB * 1024
  23. // GiB gibibyte
  24. GiB uint64 = MiB * 1024
  25. // TiB tebibyte
  26. TiB uint64 = GiB * 1024
  27. // PiB pebibyte
  28. PiB uint64 = TiB * 1024
  29. // EiB exbibyte
  30. EiB uint64 = PiB * 1024
  31. )
  32. // BytesToString converts bytes to strings
  33. func BytesToString(b uint64) string {
  34. if b < KiB {
  35. return fmt.Sprintf("%d B", b)
  36. } else if b < MiB {
  37. return formatStorageString(b, KiB, "KiB")
  38. } else if b < GiB {
  39. return formatStorageString(b, MiB, "MiB")
  40. } else if b < TiB {
  41. return formatStorageString(b, GiB, "GiB")
  42. } else if b < PiB {
  43. return formatStorageString(b, TiB, "TiB")
  44. } else if b < EiB {
  45. return formatStorageString(b, PiB, "PiB")
  46. }
  47. return formatStorageString(b, EiB, "EiB")
  48. }
  49. func formatStorageString(b, u uint64, unitLabel string) string {
  50. return fmt.Sprintf("%.2f %s", float64(b)/float64(u), unitLabel)
  51. }
  52. // BToMb converts bytes to megabytes
  53. func BToMb(b uint64) uint64 {
  54. mb := float64(b) / 1024.0 / 1024.0
  55. return uint64(math.Round(mb))
  56. }
  57. // MbTob converts megabytes to bytes
  58. func MbTob(b uint64) uint64 {
  59. return b * 1024 * 1024
  60. }