Add encoding decoding of header

This commit is contained in:
PhatPhuckDave
2024-07-22 20:41:18 +02:00
parent 21e2e17f27
commit 0ac3f31c3f
2 changed files with 33 additions and 8 deletions

View File

@@ -2,6 +2,7 @@ package pdu
type ( type (
PDU interface { PDU interface {
EncodeInto(*[]byte)
Encode() []byte Encode() []byte
Decode([]byte) Decode([]byte)
} }
@@ -19,12 +20,23 @@ type (
) )
func (p *PDU_HEADER) Encode() []byte { func (p *PDU_HEADER) Encode() []byte {
// Encode PDU_HEADER fields to byte slice buf := make([]byte, 16)
// (For simplicity, we assume little-endian encoding) EncodeUint32(buf[0:4], p.command_length)
buf := make([]byte, 16) EncodeUint32(buf[4:8], p.command_id)
encodeUint32(buf[0:4], p.command_length) EncodeUint32(buf[8:12], p.command_status)
encodeUint32(buf[4:8], p.command_id) EncodeUint32(buf[12:16], p.sequence_number)
encodeUint32(buf[8:12], p.command_status) return buf
encodeUint32(buf[12:16], p.sequence_number) }
return buf func (p *PDU_HEADER) EncodeInto(buf *[]byte) {
bufVal := *buf
EncodeUint32(bufVal[0:4], p.command_length)
EncodeUint32(bufVal[4:8], p.command_id)
EncodeUint32(bufVal[8:12], p.command_status)
EncodeUint32(bufVal[12:16], p.sequence_number)
}
func (p *PDU_HEADER) Decode(data []byte) {
p.command_length = DecodeUint32(data[0:4])
p.command_id = DecodeUint32(data[4:8])
p.command_status = DecodeUint32(data[8:12])
p.sequence_number = DecodeUint32(data[12:16])
} }

View File

@@ -1 +1,14 @@
package pdu package pdu
// EncodeUint32 encodes a uint32 into a byte slice in big-endian order
func EncodeUint32(b []byte, i uint32) {
b[0] = byte(i >> 24)
b[1] = byte(i >> 16)
b[2] = byte(i >> 8)
b[3] = byte(i)
}
// DecodeUint32 decodes a uint32 from a byte slice in big-endian order
func DecodeUint32(b []byte) uint32 {
return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
}