network/frame/payload_frame.go

67 lines
1.6 KiB
Go

package frame
import (
coder "git.hpds.cc/Component/mq_coder"
)
type Tag uint32
// PayloadFrame is a coder encoded bytes, Tag is a fixed value TYPE_ID_PAYLOAD_FRAME
// the Len is the length of Val. Val is also a coder encoded PrimitivePacket, storing
// raw bytes as user's data
type PayloadFrame struct {
Tag Tag
Carriage []byte
}
//// NewPayloadFrame creates a new PayloadFrame with a given TagId of user's data
//func NewPayloadFrame(tag byte) *PayloadFrame {
// return &PayloadFrame{
// Tag: tag,
// }
//}
// SetCarriage sets the user's raw data
func (m *PayloadFrame) SetCarriage(buf []byte) *PayloadFrame {
m.Carriage = buf
return m
}
// Encode to coder encoded bytes
func (m *PayloadFrame) Encode() []byte {
tag := coder.NewPrimitivePacketEncoder(byte(TagOfPayloadDataTag))
tag.SetUInt32Value(uint32(m.Tag))
carriage := coder.NewPrimitivePacketEncoder(byte(TagOfPayloadCarriage))
carriage.SetBytesValue(m.Carriage)
payload := coder.NewNodePacketEncoder(byte(TagOfPayloadFrame))
payload.AddPrimitivePacket(tag)
payload.AddPrimitivePacket(carriage)
return payload.Encode()
}
// DecodeToPayloadFrame decodes coder encoded bytes to PayloadFrame
func DecodeToPayloadFrame(buf []byte, payload *PayloadFrame) error {
nodeBlock := coder.NodePacket{}
_, err := coder.DecodeToNodePacket(buf, &nodeBlock)
if err != nil {
return err
}
if p, ok := nodeBlock.PrimitivePackets[byte(TagOfPayloadDataTag)]; ok {
tag, err := p.ToUInt32()
if err != nil {
return err
}
payload.Tag = Tag(tag)
}
if p, ok := nodeBlock.PrimitivePackets[byte(TagOfPayloadCarriage)]; ok {
payload.Carriage = p.GetValBuf()
}
return nil
}