fix CopyStrings and ShuffleStrings for slice when slice is nil

Signed-off-by: allencloud <allen.sun@daocloud.io>
pull/6/head
allencloud 2017-06-23 11:41:18 +08:00
parent e4af9dccb0
commit f98bc7d454
2 changed files with 34 additions and 7 deletions

View File

@ -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
@ -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 {

View File

@ -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(src, dest) {
t.Errorf("%v and %v are not equal", src, dest)
if !reflect.DeepEqual(src1, dest1) {
t.Errorf("%v and %v are not equal", src1, dest1)
}
src[0] = "A"
if reflect.DeepEqual(src, dest) {
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(src3, dest3) {
t.Errorf("%v and %v are not equal", src3, dest3)
}
src3[0] = "A"
if reflect.DeepEqual(src3, dest3) {
t.Errorf("CopyStrings didn't make a copy")
}
}
@ -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))
}