You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
1.7 KiB

  1. package internal
  2. import (
  3. "context"
  4. "net"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/redis/go-redis/v9/internal/util"
  9. )
  10. func Sleep(ctx context.Context, dur time.Duration) error {
  11. t := time.NewTimer(dur)
  12. defer t.Stop()
  13. select {
  14. case <-t.C:
  15. return nil
  16. case <-ctx.Done():
  17. return ctx.Err()
  18. }
  19. }
  20. func ToLower(s string) string {
  21. if isLower(s) {
  22. return s
  23. }
  24. b := make([]byte, len(s))
  25. for i := range b {
  26. c := s[i]
  27. if c >= 'A' && c <= 'Z' {
  28. c += 'a' - 'A'
  29. }
  30. b[i] = c
  31. }
  32. return util.BytesToString(b)
  33. }
  34. func isLower(s string) bool {
  35. for i := 0; i < len(s); i++ {
  36. c := s[i]
  37. if c >= 'A' && c <= 'Z' {
  38. return false
  39. }
  40. }
  41. return true
  42. }
  43. func ReplaceSpaces(s string) string {
  44. return strings.ReplaceAll(s, " ", "-")
  45. }
  46. func GetAddr(addr string) string {
  47. ind := strings.LastIndexByte(addr, ':')
  48. if ind == -1 {
  49. return ""
  50. }
  51. if strings.IndexByte(addr, '.') != -1 {
  52. return addr
  53. }
  54. if addr[0] == '[' {
  55. return addr
  56. }
  57. return net.JoinHostPort(addr[:ind], addr[ind+1:])
  58. }
  59. func ToInteger(val interface{}) int {
  60. switch v := val.(type) {
  61. case int:
  62. return v
  63. case int64:
  64. return int(v)
  65. case string:
  66. i, _ := strconv.Atoi(v)
  67. return i
  68. default:
  69. return 0
  70. }
  71. }
  72. func ToFloat(val interface{}) float64 {
  73. switch v := val.(type) {
  74. case float64:
  75. return v
  76. case string:
  77. f, _ := strconv.ParseFloat(v, 64)
  78. return f
  79. default:
  80. return 0.0
  81. }
  82. }
  83. func ToString(val interface{}) string {
  84. if str, ok := val.(string); ok {
  85. return str
  86. }
  87. return ""
  88. }
  89. func ToStringSlice(val interface{}) []string {
  90. if arr, ok := val.([]interface{}); ok {
  91. result := make([]string, len(arr))
  92. for i, v := range arr {
  93. result[i] = ToString(v)
  94. }
  95. return result
  96. }
  97. return nil
  98. }