Added an CRC Checksum, v0.2.0
This commit is contained in:
parent
6bb502dbf2
commit
3ea5c1a322
2
go.mod
2
go.mod
@ -1,3 +1,5 @@
|
||||
module git.barfuss.email/jan/SimpleFinancePackage
|
||||
|
||||
go 1.22.1
|
||||
|
||||
require git.barfuss.email/jan/crc16 v0.1.0 // indirect
|
||||
|
2
go.sum
Normal file
2
go.sum
Normal file
@ -0,0 +1,2 @@
|
||||
git.barfuss.email/jan/crc16 v0.1.0 h1:9u/m/JO1/njaR6w2WsGTVezW/niYlT1tBRK2mRDR92w=
|
||||
git.barfuss.email/jan/crc16 v0.1.0/go.mod h1:ibTarWCN7/nak76mWoU/pNhF+O0VzKX+8YpDftjc8LU=
|
20
spf.go
20
spf.go
@ -5,6 +5,8 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
crc "git.barfuss.email/jan/crc16"
|
||||
)
|
||||
|
||||
type SimpleFinancePackage struct {
|
||||
@ -13,11 +15,18 @@ type SimpleFinancePackage struct {
|
||||
Asset byte // 1 byte for asset
|
||||
Price float64 // 8 bytes for price (float64 for precision)
|
||||
Volume float64 // 8 bytes for volume
|
||||
CRC uint16 // 2 bytes for CRC
|
||||
}
|
||||
|
||||
func ParseSimpleFinanacePackage(data []byte) (*SimpleFinancePackage, error) {
|
||||
if len(data) != 26 {
|
||||
return nil, errors.New("invalid packet size, expected 26 bytes")
|
||||
if len(data) != 28 {
|
||||
return nil, errors.New("invalid packet size, expected 28 bytes")
|
||||
}
|
||||
|
||||
//Check CRC
|
||||
check := binary.BigEndian.Uint16(data[26:])
|
||||
if check != crc.Calculate(data[:26]) {
|
||||
return nil, errors.New("CRC check failed")
|
||||
}
|
||||
|
||||
reader := bytes.NewReader(data)
|
||||
@ -59,6 +68,13 @@ func EncodeSimpleFinanacePackage(packet SimpleFinancePackage) ([]byte, error) {
|
||||
return nil, fmt.Errorf("failed to encode volume: %w", err)
|
||||
}
|
||||
|
||||
// Calculate and write CRC
|
||||
packet.CRC = crc.Calculate(buf.Bytes())
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, packet.CRC); err != nil {
|
||||
return nil, fmt.Errorf("failed to encode CRC: %w", err)
|
||||
}
|
||||
|
||||
// Return the resulting byte slice
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
@ -24,8 +24,8 @@ func TestEncodeDecodeCustomPacket(t *testing.T) {
|
||||
}
|
||||
|
||||
// Check the encoded length
|
||||
if len(encoded) != 26 {
|
||||
t.Fatalf("Encoded data has incorrect length: got %d, want 26", len(encoded))
|
||||
if len(encoded) != 28 {
|
||||
t.Fatalf("Encoded data has incorrect length: got %d, want 28", len(encoded))
|
||||
}
|
||||
|
||||
// Decode the packet
|
||||
|
Loading…
Reference in New Issue
Block a user