Skip to content

Commit

Permalink
cherry-pick-9661-to-release-6.5
Browse files Browse the repository at this point in the history
  • Loading branch information
asddongmen committed Sep 11, 2023
1 parent 6635d9c commit 3c1af5c
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
33 changes: 33 additions & 0 deletions pkg/util/comparison.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import "sort"

// AreStringSlicesEquivalent checks if two string slices are equivalent.
// If the slices are of the same length and contain the same elements (but possibly in different order), the function returns true.
// Note: This function does modify the slices. Please be caution of this if you are using it.
func AreStringSlicesEquivalent(a, b []string) bool {
if len(a) != len(b) {
return false
}
sort.Strings(a)
sort.Strings(b)
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
61 changes: 61 additions & 0 deletions pkg/util/comparison_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package util

import (
"testing"
)

func TestAreStringSlicesEquivalent(t *testing.T) {
tests := []struct {
name string
a []string
b []string
want bool
}{
{
name: "equal slices",
a: []string{"foo", "bar", "baz"},
b: []string{"baz", "foo", "bar"},
want: true,
},
{
name: "different lengths",
a: []string{"foo", "bar", "baz"},
b: []string{"foo", "bar"},
want: false,
},
{
name: "different elements",
a: []string{"foo", "bar", "baz"},
b: []string{"qux", "quux", "corge"},
want: false,
},
{
name: "nil elements",
a: []string{},
b: []string{},
want: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := AreStringSlicesEquivalent(tt.a, tt.b); got != tt.want {
t.Errorf("AreStringSlicesEquivalent() = %v, want %v", got, tt.want)
}
})
}
}

// END: j3d8f4b2j2p9

0 comments on commit 3c1af5c

Please sign in to comment.