network/frame/backflow_frame.go

78 lines
1.9 KiB
Go

package frame
import (
coder "git.hpds.cc/Component/mq_coder"
)
// BackFlowFrame is a coder encoded bytes
// It's used to receive stream function processed result
type BackFlowFrame struct {
Tag Tag
Carriage []byte
}
// NewBackFlowFrame creates a new BackFlowFrame with a given tag and carriage
func NewBackFlowFrame(tag Tag, carriage []byte) *BackFlowFrame {
return &BackFlowFrame{
Tag: tag,
Carriage: carriage,
}
}
// Type gets the type of Frame.
func (f *BackFlowFrame) Type() Type {
return TagOfBackFlowFrame
}
// SetCarriage sets the user's raw data
func (f *BackFlowFrame) SetCarriage(buf []byte) *BackFlowFrame {
f.Carriage = buf
return f
}
// Encode to coder encoded bytes
func (f *BackFlowFrame) Encode() []byte {
tag := coder.NewPrimitivePacketEncoder(byte(TagOfBackFlowDataTag))
tag.SetUInt32Value(uint32(f.Tag))
carriage := coder.NewPrimitivePacketEncoder(byte(TagOfBackFlowCarriage))
carriage.SetBytesValue(f.Carriage)
node := coder.NewNodePacketEncoder(byte(TagOfBackFlowFrame))
node.AddPrimitivePacket(tag)
node.AddPrimitivePacket(carriage)
return node.Encode()
}
// GetDataTag return the Tag of user's data
func (f *BackFlowFrame) GetDataTag() Tag {
return f.Tag
}
// GetCarriage return data
func (f *BackFlowFrame) GetCarriage() []byte {
return f.Carriage
}
// DecodeToBackFlowFrame decodes coder encoded bytes to BackFlowFrame
func DecodeToBackFlowFrame(buf []byte) (*BackFlowFrame, error) {
nodeBlock := coder.NodePacket{}
_, err := coder.DecodeToNodePacket(buf, &nodeBlock)
if err != nil {
return nil, err
}
payload := &BackFlowFrame{}
if p, ok := nodeBlock.PrimitivePackets[byte(TagOfBackFlowDataTag)]; ok {
tag, err := p.ToUInt32()
if err != nil {
return nil, err
}
payload.Tag = Tag(tag)
}
if p, ok := nodeBlock.PrimitivePackets[byte(TagOfBackFlowCarriage)]; ok {
payload.Carriage = p.GetValBuf()
}
return payload, nil
}