Export reverse byte order function (#10040)

* Reverse byte order

* Update BUILD.bazel

* Go imports

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
This commit is contained in:
terence tsao
2022-01-11 10:42:03 -08:00
committed by GitHub
parent 3d02addfe4
commit 88b94eae18
4 changed files with 26 additions and 11 deletions

View File

@@ -383,3 +383,14 @@ func IsHex(b []byte) bool {
}
return hexRegex.Match(b)
}
// ReverseByteOrder Switch the endianness of a byte slice by reversing its order.
// this function does not modify the actual input bytes.
func ReverseByteOrder(input []byte) []byte {
b := make([]byte, len(input))
copy(b, input)
for i := 0; i < len(b)/2; i++ {
b[i], b[len(b)-i-1] = b[len(b)-i-1], b[i]
}
return b
}

View File

@@ -1,6 +1,7 @@
package bytesutil_test
import (
"bytes"
"reflect"
"testing"
@@ -495,5 +496,14 @@ func TestBytesInvalidInputs(t *testing.T) {
intRes := bytesutil.ToLowInt64([]byte{})
assert.Equal(t, intRes, int64(0))
}
func TestReverseByteOrder(t *testing.T) {
input := []byte{0, 1, 2, 3, 4, 5}
expectedResult := []byte{5, 4, 3, 2, 1, 0}
output := bytesutil.ReverseByteOrder(input)
// check that the input is not modified and the output is reversed
assert.Equal(t, bytes.Equal(input, []byte{0, 1, 2, 3, 4, 5}), true)
assert.Equal(t, bytes.Equal(expectedResult, output), true)
}