forked from TrueCloudLab/neoneo-go
Merge pull request #644 from nspcc-dev/fix/array_reverse
util: always copy argument in ArrayReverse
This commit is contained in:
commit
fca86771e9
2 changed files with 33 additions and 21 deletions
|
@ -2,10 +2,6 @@ package util
|
|||
|
||||
// ArrayReverse returns a reversed version of the given byte slice.
|
||||
func ArrayReverse(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; i, j = i+1, j-1 {
|
||||
dest[i], dest[j] = b[j], b[i]
|
||||
|
|
|
@ -6,24 +6,40 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestArrayEvenReverse(t *testing.T) {
|
||||
arr := []byte{0x01, 0x02, 0x03, 0x04}
|
||||
have := ArrayReverse(arr)
|
||||
want := []byte{0x04, 0x03, 0x02, 0x01}
|
||||
require.Equal(t, want, have)
|
||||
var testCases = []struct {
|
||||
arr []byte
|
||||
rev []byte
|
||||
}{
|
||||
{
|
||||
arr: []byte{},
|
||||
rev: []byte{},
|
||||
},
|
||||
{
|
||||
arr: []byte{0x01},
|
||||
rev: []byte{0x01},
|
||||
},
|
||||
{
|
||||
arr: []byte{0x01, 0x02, 0x03, 0x04},
|
||||
rev: []byte{0x04, 0x03, 0x02, 0x01},
|
||||
},
|
||||
{
|
||||
arr: []byte{0x01, 0x02, 0x03, 0x04, 0x05},
|
||||
rev: []byte{0x05, 0x04, 0x03, 0x02, 0x01},
|
||||
},
|
||||
}
|
||||
|
||||
func TestArrayOddReverse(t *testing.T) {
|
||||
arr := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
|
||||
have := ArrayReverse(arr)
|
||||
want := []byte{0x05, 0x04, 0x03, 0x02, 0x01}
|
||||
require.Equal(t, want, have)
|
||||
}
|
||||
func TestArrayReverse(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
arg := make([]byte, len(tc.arr))
|
||||
copy(arg, tc.arr)
|
||||
|
||||
// This tests a bug that occurred with arrays of size 1
|
||||
func TestArrayReverseLen2(t *testing.T) {
|
||||
arr := []byte{0x01}
|
||||
have := ArrayReverse(arr)
|
||||
want := []byte{0x01}
|
||||
require.Equal(t, want, have)
|
||||
have := ArrayReverse(arg)
|
||||
require.Equal(t, tc.rev, have)
|
||||
|
||||
// test that argument was copied
|
||||
for i := range have {
|
||||
have[i] = ^have[i]
|
||||
}
|
||||
require.Equal(t, tc.arr, arg)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue