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