convert.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
  2. // 🤖 Github Repository: https://github.com/gofiber/fiber
  3. // 📌 API Documentation: https://docs.gofiber.io
  4. package utils
  5. import (
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "unsafe"
  10. )
  11. // #nosec G103
  12. // GetString returns a string pointer without allocation
  13. func UnsafeString(b []byte) string {
  14. return *(*string)(unsafe.Pointer(&b))
  15. }
  16. // #nosec G103
  17. // GetBytes returns a byte pointer without allocation
  18. func UnsafeBytes(s string) (bs []byte) {
  19. sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
  20. bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
  21. bh.Data = sh.Data
  22. bh.Len = sh.Len
  23. bh.Cap = sh.Len
  24. return
  25. }
  26. // SafeString copies a string to make it immutable
  27. func SafeString(s string) string {
  28. return string(UnsafeBytes(s))
  29. }
  30. // SafeBytes copies a slice to make it immutable
  31. func SafeBytes(b []byte) []byte {
  32. tmp := make([]byte, len(b))
  33. copy(tmp, b)
  34. return tmp
  35. }
  36. const (
  37. uByte = 1 << (10 * iota)
  38. uKilobyte
  39. uMegabyte
  40. uGigabyte
  41. uTerabyte
  42. uPetabyte
  43. uExabyte
  44. )
  45. // ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth.
  46. // The unit that results in the smallest number greater than or equal to 1 is always chosen.
  47. func ByteSize(bytes uint64) string {
  48. unit := ""
  49. value := float64(bytes)
  50. switch {
  51. case bytes >= uExabyte:
  52. unit = "EB"
  53. value = value / uExabyte
  54. case bytes >= uPetabyte:
  55. unit = "PB"
  56. value = value / uPetabyte
  57. case bytes >= uTerabyte:
  58. unit = "TB"
  59. value = value / uTerabyte
  60. case bytes >= uGigabyte:
  61. unit = "GB"
  62. value = value / uGigabyte
  63. case bytes >= uMegabyte:
  64. unit = "MB"
  65. value = value / uMegabyte
  66. case bytes >= uKilobyte:
  67. unit = "KB"
  68. value = value / uKilobyte
  69. case bytes >= uByte:
  70. unit = "B"
  71. default:
  72. return "0B"
  73. }
  74. result := strconv.FormatFloat(value, 'f', 1, 64)
  75. result = strings.TrimSuffix(result, ".0")
  76. return result + unit
  77. }
  78. // Deprecated fn's
  79. // #nosec G103
  80. // GetString returns a string pointer without allocation
  81. func GetString(b []byte) string {
  82. return UnsafeString(b)
  83. }
  84. // #nosec G103
  85. // GetBytes returns a byte pointer without allocation
  86. func GetBytes(s string) []byte {
  87. return UnsafeBytes(s)
  88. }
  89. // ImmutableString copies a string to make it immutable
  90. func ImmutableString(s string) string {
  91. return SafeString(s)
  92. }