Rework encoding to use go binary
This commit is contained in:
41
pdu/pdu.go
41
pdu/pdu.go
@@ -1,10 +1,13 @@
|
||||
package pdu
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
type (
|
||||
PDU interface {
|
||||
EncodeInto(*[]byte)
|
||||
Encode() []byte
|
||||
Decode([]byte)
|
||||
EncodeInto(*[]uint8)
|
||||
Encode() []uint8
|
||||
Decode([]uint8)
|
||||
Size() uint32
|
||||
}
|
||||
|
||||
PDU_HEADER struct {
|
||||
@@ -19,24 +22,24 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
func (p *PDU_HEADER) Encode() []byte {
|
||||
buf := make([]byte, 16)
|
||||
EncodeUint32(buf[0:4], p.command_length)
|
||||
EncodeUint32(buf[4:8], p.command_id)
|
||||
EncodeUint32(buf[8:12], p.command_status)
|
||||
EncodeUint32(buf[12:16], p.sequence_number)
|
||||
func (p *PDU_HEADER) Encode() []uint8 {
|
||||
buf := make([]uint8, 16)
|
||||
binary.BigEndian.PutUint32(buf[0:4], p.command_length)
|
||||
binary.BigEndian.PutUint32(buf[4:8], p.command_id)
|
||||
binary.BigEndian.PutUint32(buf[8:12], p.command_status)
|
||||
binary.BigEndian.PutUint32(buf[12:16], p.sequence_number)
|
||||
return buf
|
||||
}
|
||||
func (p *PDU_HEADER) EncodeInto(buf *[]byte) {
|
||||
func (p *PDU_HEADER) EncodeInto(buf *[]uint8) {
|
||||
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)
|
||||
binary.BigEndian.PutUint32(bufVal[0:4], p.command_length)
|
||||
binary.BigEndian.PutUint32(bufVal[4:8], p.command_id)
|
||||
binary.BigEndian.PutUint32(bufVal[8:12], p.command_status)
|
||||
binary.BigEndian.PutUint32(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])
|
||||
func (p *PDU_HEADER) Decode(data []uint8) {
|
||||
p.command_length = binary.BigEndian.Uint32(data[0:4])
|
||||
p.command_id = binary.BigEndian.Uint32(data[4:8])
|
||||
p.command_status = binary.BigEndian.Uint32(data[8:12])
|
||||
p.sequence_number = binary.BigEndian.Uint32(data[12:16])
|
||||
}
|
||||
|
14
pdu/util.go
14
pdu/util.go
@@ -1,14 +0,0 @@
|
||||
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])
|
||||
}
|
Reference in New Issue
Block a user