strings.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package util
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "time"
  7. )
  8. func init() {
  9. rand.Seed(time.Now().UnixNano())
  10. }
  11. var alpha = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  12. var alphanumeric = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  13. const (
  14. _ = 1 << (10 * iota)
  15. // KiB is bytes per Kibibyte
  16. KiB
  17. // MiB is bytes per Mebibyte
  18. MiB
  19. // GiB is bytes per Gibibyte
  20. GiB
  21. // TiB is bytes per Tebibyte
  22. TiB
  23. )
  24. // RandSeq generates a pseudo-random alphabetic string of the given length
  25. func RandSeq(n int) string {
  26. b := make([]rune, n)
  27. for i := range b {
  28. b[i] = alpha[rand.Intn(len(alpha))]
  29. }
  30. return string(b)
  31. }
  32. // FormatBytes takes a number of bytes and formats it as a string
  33. func FormatBytes(numBytes int64) string {
  34. if numBytes > TiB {
  35. return fmt.Sprintf("%.2fTiB", float64(numBytes)/TiB)
  36. }
  37. if numBytes > GiB {
  38. return fmt.Sprintf("%.2fGiB", float64(numBytes)/GiB)
  39. }
  40. if numBytes > MiB {
  41. return fmt.Sprintf("%.2fMiB", float64(numBytes)/MiB)
  42. }
  43. if numBytes > KiB {
  44. return fmt.Sprintf("%.2fKiB", float64(numBytes)/KiB)
  45. }
  46. return fmt.Sprintf("%dB", numBytes)
  47. }
  48. // FormatUTCOffset converts a duration to a string of format "-07:00"
  49. func FormatUTCOffset(dur time.Duration) string {
  50. utcOffSig := "+"
  51. if dur.Hours() < 0 {
  52. utcOffSig = "-"
  53. }
  54. utcOffHrs := int(math.Trunc(math.Abs(dur.Hours())))
  55. utcOffMin := int(math.Abs(dur.Minutes())) - (utcOffHrs * 60)
  56. return fmt.Sprintf("%s%02d:%02d", utcOffSig, utcOffHrs, utcOffMin)
  57. }