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.
|
// ArrayReverse returns a reversed version of the given byte slice.
|
||||||
func ArrayReverse(b []byte) []byte {
|
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))
|
dest := make([]byte, len(b))
|
||||||
for i, j := 0, len(b)-1; i <= j; i, j = i+1, j-1 {
|
for i, j := 0, len(b)-1; i <= j; i, j = i+1, j-1 {
|
||||||
dest[i], dest[j] = b[j], b[i]
|
dest[i], dest[j] = b[j], b[i]
|
||||||
|
|
|
@ -6,24 +6,40 @@ import (
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestArrayEvenReverse(t *testing.T) {
|
var testCases = []struct {
|
||||||
arr := []byte{0x01, 0x02, 0x03, 0x04}
|
arr []byte
|
||||||
have := ArrayReverse(arr)
|
rev []byte
|
||||||
want := []byte{0x04, 0x03, 0x02, 0x01}
|
}{
|
||||||
require.Equal(t, want, have)
|
{
|
||||||
|
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) {
|
func TestArrayReverse(t *testing.T) {
|
||||||
arr := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
|
for _, tc := range testCases {
|
||||||
have := ArrayReverse(arr)
|
arg := make([]byte, len(tc.arr))
|
||||||
want := []byte{0x05, 0x04, 0x03, 0x02, 0x01}
|
copy(arg, tc.arr)
|
||||||
require.Equal(t, want, have)
|
|
||||||
}
|
|
||||||
|
|
||||||
// This tests a bug that occurred with arrays of size 1
|
have := ArrayReverse(arg)
|
||||||
func TestArrayReverseLen2(t *testing.T) {
|
require.Equal(t, tc.rev, have)
|
||||||
arr := []byte{0x01}
|
|
||||||
have := ArrayReverse(arr)
|
// test that argument was copied
|
||||||
want := []byte{0x01}
|
for i := range have {
|
||||||
require.Equal(t, want, have)
|
have[i] = ^have[i]
|
||||||
|
}
|
||||||
|
require.Equal(t, tc.arr, arg)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue