From 2008f60e509b96be751a461c7658267429154cd1 Mon Sep 17 00:00:00 2001 From: SimFG Date: Fri, 17 Jun 2022 10:22:11 +0800 Subject: [PATCH] Simplify the implementations of the ToPhysicalChannel and the ConvertChannelName func (#17605) Signed-off-by: SimFG --- internal/util/funcutil/func.go | 27 +++++++++------------------ internal/util/funcutil/func_test.go | 2 ++ 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/internal/util/funcutil/func.go b/internal/util/funcutil/func.go index b8a6cbd972..f0f9624fd3 100644 --- a/internal/util/funcutil/func.go +++ b/internal/util/funcutil/func.go @@ -28,6 +28,7 @@ import ( "net/http" "reflect" "strconv" + "strings" "time" "go.uber.org/zap" @@ -243,32 +244,22 @@ func GetAvailablePort() int { // ToPhysicalChannel get physical channel name from virtual channel name func ToPhysicalChannel(vchannel string) string { - var idx int - for idx = len(vchannel) - 1; idx >= 0; idx-- { - if vchannel[idx] == '_' { - break - } - } - if idx < 0 { + index := strings.LastIndex(vchannel, "_") + if index < 0 { return vchannel } - return vchannel[:idx] + return vchannel[:index] } // ConvertChannelName assembles channel name according to parameters. func ConvertChannelName(chanName string, tokenFrom string, tokenTo string) (string, error) { - chanNameLen := len(chanName) - tokenFromLen := len(tokenFrom) - if chanNameLen < tokenFromLen { + if tokenFrom == "" { + return "", fmt.Errorf("the tokenFrom is empty") + } + if !strings.Contains(chanName, tokenFrom) { return "", fmt.Errorf("cannot find token '%s' in '%s'", tokenFrom, chanName) } - - for i := 0; i < (chanNameLen - tokenFromLen); i++ { - if chanName[i:i+tokenFromLen] == tokenFrom { - return chanName[0:i] + tokenTo + chanName[i+tokenFromLen:], nil - } - } - return "", fmt.Errorf("cannot find token '%s' in '%s'", tokenFrom, chanName) + return strings.Replace(chanName, tokenFrom, tokenTo, 1), nil } func getNumRowsOfScalarField(datas interface{}) uint64 { diff --git a/internal/util/funcutil/func_test.go b/internal/util/funcutil/func_test.go index 35d6c49e71..7b69326e74 100644 --- a/internal/util/funcutil/func_test.go +++ b/internal/util/funcutil/func_test.go @@ -311,6 +311,8 @@ func Test_ConvertChannelName(t *testing.T) { ) _, err := ConvertChannelName("by-dev", tFrom, tTo) assert.NotNil(t, err) + _, err = ConvertChannelName("by-dev", "", tTo) + assert.NotNil(t, err) _, err = ConvertChannelName("by-dev_rootcoord-delta_123v0", tFrom, tTo) assert.NotNil(t, err) str, err := ConvertChannelName(chanName, tFrom, tTo)