network/frame/data_frame.go

111 lines
2.6 KiB
Go
Raw Normal View History

2022-10-11 17:36:09 +08:00
package frame
import (
coder "git.hpds.cc/Component/mq_coder"
)
// DataFrame defines the data structure carried with user's data
type DataFrame struct {
metaFrame *MetaFrame
payloadFrame *PayloadFrame
}
// NewDataFrame create `DataFrame` with a transactionId string,
// consider change transactionID to UUID type later
func NewDataFrame() *DataFrame {
data := &DataFrame{
metaFrame: NewMetaFrame(),
}
return data
}
// Type gets the type of Frame.
func (d *DataFrame) Type() Type {
return TagOfDataFrame
}
// Tag return the tag of carriage data.
func (d *DataFrame) Tag() byte {
return d.payloadFrame.Tag
}
// SetCarriage set user's raw data in `DataFrame`
func (d *DataFrame) SetCarriage(tag byte, carriage []byte) {
d.payloadFrame = NewPayloadFrame(tag).SetCarriage(carriage)
}
// GetCarriage return user's raw data in `DataFrame`
func (d *DataFrame) GetCarriage() []byte {
return d.payloadFrame.Carriage
}
// TransactionId return transactionId string
func (d *DataFrame) TransactionId() string {
return d.metaFrame.TransactionId()
}
// SetTransactionId set transactionId string
func (d *DataFrame) SetTransactionId(transactionID string) {
d.metaFrame.SetTransactionId(transactionID)
}
// GetMetaFrame return MetaFrame.
func (d *DataFrame) GetMetaFrame() *MetaFrame {
return d.metaFrame
}
// GetDataTag return the Tag of user's data
func (d *DataFrame) GetDataTag() byte {
return d.payloadFrame.Tag
}
// SetSourceId set the source id.
func (d *DataFrame) SetSourceId(sourceID string) {
d.metaFrame.SetSourceId(sourceID)
}
// SourceId returns source id
func (d *DataFrame) SourceId() string {
return d.metaFrame.SourceId()
}
// Encode return coder encoded bytes of `DataFrame`
func (d *DataFrame) Encode() []byte {
2023-03-26 23:18:55 +08:00
data := coder.NewNodePacketEncoder(byte(d.Type()))
2022-10-11 17:36:09 +08:00
// MetaFrame
data.AddBytes(d.metaFrame.Encode())
// PayloadFrame
data.AddBytes(d.payloadFrame.Encode())
return data.Encode()
}
// DecodeToDataFrame decode coder encoded bytes to `DataFrame`
func DecodeToDataFrame(buf []byte) (*DataFrame, error) {
packet := coder.NodePacket{}
_, err := coder.DecodeToNodePacket(buf, &packet)
if err != nil {
return nil, err
}
data := &DataFrame{}
2023-03-26 23:18:55 +08:00
if metaBlock, ok := packet.NodePackets[byte(TagOfMetaFrame)]; ok {
2022-10-11 17:36:09 +08:00
meta, err := DecodeToMetaFrame(metaBlock.GetRawBytes())
if err != nil {
return nil, err
}
data.metaFrame = meta
}
2023-03-26 23:18:55 +08:00
if payloadBlock, ok := packet.NodePackets[byte(TagOfPayloadFrame)]; ok {
2022-10-11 17:36:09 +08:00
payload, err := DecodeToPayloadFrame(payloadBlock.GetRawBytes())
if err != nil {
return nil, err
}
data.payloadFrame = payload
}
return data, nil
}