Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix CopyStrings and ShuffleStrings for slice when slice is nil #47944

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/util/slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ import (
// CopyStrings copies the contents of the specified string slice
// into a new slice.
func CopyStrings(s []string) []string {
if s == nil {
return nil
}
c := make([]string, len(s))
copy(c, s)
return c
Expand All @@ -41,6 +44,9 @@ func SortStrings(s []string) []string {
// ShuffleStrings copies strings from the specified slice into a copy in random
// order. It returns a new slice.
func ShuffleStrings(s []string) []string {
if s == nil {
return nil
}
shuffled := make([]string, len(s))
perm := utilrand.Perm(len(s))
for i, j := range perm {
Expand Down
35 changes: 28 additions & 7 deletions pkg/util/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,29 @@ import (
)

func TestCopyStrings(t *testing.T) {
src := []string{"a", "c", "b"}
dest := CopyStrings(src)
var src1 []string
dest1 := CopyStrings(src1)

if !reflect.DeepEqual(src1, dest1) {
t.Errorf("%v and %v are not equal", src1, dest1)
}

src2 := []string{}
dest2 := CopyStrings(src2)

if !reflect.DeepEqual(src2, dest2) {
t.Errorf("%v and %v are not equal", src2, dest2)
}

src3 := []string{"a", "c", "b"}
dest3 := CopyStrings(src3)

if !reflect.DeepEqual(src, dest) {
t.Errorf("%v and %v are not equal", src, dest)
if !reflect.DeepEqual(src3, dest3) {
t.Errorf("%v and %v are not equal", src3, dest3)
}

src[0] = "A"
if reflect.DeepEqual(src, dest) {
src3[0] = "A"
if reflect.DeepEqual(src3, dest3) {
t.Errorf("CopyStrings didn't make a copy")
}
}
Expand All @@ -50,9 +64,16 @@ func TestSortStrings(t *testing.T) {
}

func TestShuffleStrings(t *testing.T) {
src := []string{"a", "b", "c", "d", "e", "f"}
var src []string
dest := ShuffleStrings(src)

if dest != nil {
t.Errorf("ShuffleStrings for a nil slice got a non-nil slice")
}

src = []string{"a", "b", "c", "d", "e", "f"}
dest = ShuffleStrings(src)

if len(src) != len(dest) {
t.Errorf("Shuffled slice is wrong length, expected %v got %v", len(src), len(dest))
}
Expand Down