Commit f98bc7d4 authored by allencloud's avatar allencloud

fix CopyStrings and ShuffleStrings for slice when slice is nil

parent e4af9dcc
...@@ -26,6 +26,9 @@ import ( ...@@ -26,6 +26,9 @@ import (
// CopyStrings copies the contents of the specified string slice // CopyStrings copies the contents of the specified string slice
// into a new slice. // into a new slice.
func CopyStrings(s []string) []string { func CopyStrings(s []string) []string {
if s == nil {
return nil
}
c := make([]string, len(s)) c := make([]string, len(s))
copy(c, s) copy(c, s)
return c return c
...@@ -41,6 +44,9 @@ func SortStrings(s []string) []string { ...@@ -41,6 +44,9 @@ func SortStrings(s []string) []string {
// ShuffleStrings copies strings from the specified slice into a copy in random // ShuffleStrings copies strings from the specified slice into a copy in random
// order. It returns a new slice. // order. It returns a new slice.
func ShuffleStrings(s []string) []string { func ShuffleStrings(s []string) []string {
if s == nil {
return nil
}
shuffled := make([]string, len(s)) shuffled := make([]string, len(s))
perm := utilrand.Perm(len(s)) perm := utilrand.Perm(len(s))
for i, j := range perm { for i, j := range perm {
......
...@@ -22,15 +22,29 @@ import ( ...@@ -22,15 +22,29 @@ import (
) )
func TestCopyStrings(t *testing.T) { func TestCopyStrings(t *testing.T) {
src := []string{"a", "c", "b"} var src1 []string
dest := CopyStrings(src) 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) { if !reflect.DeepEqual(src3, dest3) {
t.Errorf("%v and %v are not equal", src, dest) t.Errorf("%v and %v are not equal", src3, dest3)
} }
src[0] = "A" src3[0] = "A"
if reflect.DeepEqual(src, dest) { if reflect.DeepEqual(src3, dest3) {
t.Errorf("CopyStrings didn't make a copy") t.Errorf("CopyStrings didn't make a copy")
} }
} }
...@@ -50,9 +64,16 @@ func TestSortStrings(t *testing.T) { ...@@ -50,9 +64,16 @@ func TestSortStrings(t *testing.T) {
} }
func TestShuffleStrings(t *testing.T) { func TestShuffleStrings(t *testing.T) {
src := []string{"a", "b", "c", "d", "e", "f"} var src []string
dest := ShuffleStrings(src) 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) { if len(src) != len(dest) {
t.Errorf("Shuffled slice is wrong length, expected %v got %v", len(src), len(dest)) t.Errorf("Shuffled slice is wrong length, expected %v got %v", len(src), len(dest))
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment