Skip to content

Commit

Permalink
Merge pull request #9 from jshiv/fix/change_reverse
Browse files Browse the repository at this point in the history
Removed copy from reverse function
  • Loading branch information
naveenv92 authored Aug 2, 2022
2 parents f5e2511 + 68bf611 commit 615c5a9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
7 changes: 3 additions & 4 deletions payload.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,9 @@ func (p *Payload) PackLittleEndian() *big.Int {

// Reverse byte array for little endian signals.
func reverse(data []byte) []byte {
reversedArray := make([]byte, len(data))
copy(reversedArray, data)
for i, j := 0, len(reversedArray)-1; i < j; i, j = i+1, j-1 {
reversedArray[i], reversedArray[j] = reversedArray[j], reversedArray[i]
reversedArray := make([]byte, 0, len(data))
for i := len(data) - 1; i >= 0; i-- {
reversedArray = append(reversedArray, data[i])
}
return reversedArray
}
Expand Down
19 changes: 19 additions & 0 deletions payload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package can

import (
"fmt"
"reflect"
"testing"
)

Expand Down Expand Up @@ -66,6 +67,24 @@ func TestSignedBigEndian(t *testing.T) {
fmt.Println(payload.SignedBitsBigEndian(signal.start, signal.length))
}

func TestReverse(t *testing.T) {
payloadHexes := []string{
"17399b6c89d22805003f", // Even Length
"17399b6c89d22805003f17399b6c89d22805003f17399b6c89d22805003f", // Long Even
"17399b6c89d2280500", // Odd Length
"17399b6c89d228050017399b6c89d228050017399b6c89d2280500", // Long Odd
}

for _, hex := range payloadHexes {
p, _ := PayloadFromHex(hex)

twiceReversed := reverse(reverse(p.Data))
if !reflect.DeepEqual(p.Data, twiceReversed) {
t.Errorf("Reversed slices are not equal, input: %v, output: %v", p.Data, twiceReversed)
}
}
}

func Benchmark4BytesPayload_PackLittleEndian(b *testing.B) {
data := []byte{0x40, 0x23, 0x01, 0x12}
payload := Payload{Data: data}
Expand Down

0 comments on commit 615c5a9

Please sign in to comment.