array: add a test for even num of elements

And drop duplicating code from _pkg.dev.
This commit is contained in:
Roman Khimov 2019-08-23 15:44:49 +03:00
parent 0cde8d962d
commit 37be2e215c
3 changed files with 10 additions and 49 deletions

View file

@ -1,15 +0,0 @@
package slice
// Reverse return a reversed version of the given byte slice.
func Reverse(b []byte) []byte {
// Protect from big.Ints that have 1 len bytes.
if len(b) < 2 {
return b
}
dest := make([]byte, len(b))
for i, j := 0, len(b)-1; i < j+1; i, j = i+1, j-1 {
dest[i], dest[j] = b[j], b[i]
}
return dest
}

View file

@ -1,33 +0,0 @@
package slice
import (
"bytes"
"testing"
)
func TestSliceReverse(t *testing.T) {
arr := []byte{0x01, 0x02, 0x03, 0x04}
have := Reverse(arr)
want := []byte{0x04, 0x03, 0x02, 0x01}
if bytes.Compare(have, want) != 0 {
t.Fatalf("expected %v got %v", want, have)
}
}
func TestSliceReverseOddNumberOfElements(t *testing.T) {
arr := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
have := Reverse(arr)
want := []byte{0x05, 0x04, 0x03, 0x02, 0x01}
if bytes.Compare(have, want) != 0 {
t.Fatalf("expected %v got %v", want, have)
}
}
// This tests a bug that occured with arrays of size 1
func TestSliceReverseLen2(t *testing.T) {
arr := []byte{0x01}
have := Reverse(arr)
want := []byte{0x01}
if bytes.Compare(have, want) != 0 {
t.Fatalf("expected %v got %v", want, have)
}
}

View file

@ -5,7 +5,16 @@ import (
"testing"
)
func TestArrayReverse(t *testing.T) {
func TestArrayEvenReverse(t *testing.T) {
arr := []byte{0x01, 0x02, 0x03, 0x04}
have := ArrayReverse(arr)
want := []byte{0x04, 0x03, 0x02, 0x01}
if !bytes.Equal(have, want) {
t.Fatalf("expected %v got %v", want, have)
}
}
func TestArrayOddReverse(t *testing.T) {
arr := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
have := ArrayReverse(arr)
want := []byte{0x05, 0x04, 0x03, 0x02, 0x01}