Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed copy from reverse function #9

Merged
merged 4 commits into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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