49 lines
946 B
Go
49 lines
946 B
Go
package models
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"errors"
|
|
)
|
|
|
|
type Message struct {
|
|
Type uint16
|
|
Version uint16
|
|
Payload []byte
|
|
}
|
|
|
|
func (m *Message) Encode() []byte {
|
|
payloadLen := len(m.Payload)
|
|
if payloadLen > 0xFFFF {
|
|
return nil
|
|
}
|
|
|
|
buf := make([]byte, 8+payloadLen)
|
|
|
|
binary.LittleEndian.PutUint16(buf[0:2], m.Type)
|
|
binary.LittleEndian.PutUint16(buf[2:4], m.Version)
|
|
binary.LittleEndian.PutUint16(buf[4:6], uint16(payloadLen))
|
|
|
|
copy(buf[8:], m.Payload)
|
|
return buf
|
|
}
|
|
|
|
func Decode(data []byte) (*Message, error) {
|
|
if len(data) < 8 {
|
|
return nil, errors.New("message too short")
|
|
}
|
|
|
|
payloadLen := binary.LittleEndian.Uint16(data[4:6])
|
|
if len(data) != int(8+payloadLen) {
|
|
return nil, errors.New("invalid payload length")
|
|
}
|
|
|
|
msg := &Message{
|
|
Type: binary.LittleEndian.Uint16(data[0:2]),
|
|
Version: binary.LittleEndian.Uint16(data[2:4]),
|
|
Payload: make([]byte, payloadLen),
|
|
}
|
|
|
|
copy(msg.Payload, data[8:])
|
|
return msg, nil
|
|
}
|