mq_coder/encoder.go

78 lines
1.4 KiB
Go
Raw Normal View History

2022-10-07 15:30:45 +08:00
package mq_coder
import (
"bytes"
2022-10-10 14:47:49 +08:00
"fmt"
"git.hpds.cc/Component/mq_coder/encoding"
2022-10-07 15:30:45 +08:00
)
2022-10-10 14:47:49 +08:00
// Encoder will encode object to encoding
type encoder struct {
seqID byte
2023-03-10 23:58:36 +08:00
valBuf []byte
2022-10-10 14:47:49 +08:00
isNode bool
isArray bool
buf *bytes.Buffer
complete bool
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
type iEncoder interface {
Encode() []byte
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) GetValBuf() []byte {
2023-03-10 23:58:36 +08:00
return enc.valBuf
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) IsEmpty() bool {
2023-03-10 23:58:36 +08:00
return len(enc.valBuf) == 0
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) AddBytes(buf []byte) {
2023-03-10 23:58:36 +08:00
enc.valBuf = append(enc.valBuf, buf...)
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) addRawPacket(en iEncoder) {
2023-03-10 23:58:36 +08:00
enc.valBuf = append(enc.valBuf, en.Encode()...)
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
// setTag write tag as seqID
func (enc *encoder) writeTag() {
if enc.seqID > 0x3F {
panic(fmt.Errorf("sid should be in [0..0x3F]"))
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
if enc.isNode {
enc.seqID = enc.seqID | 0x80
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
if enc.isArray {
enc.seqID = enc.seqID | 0x40
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
enc.buf.WriteByte(enc.seqID)
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) writeLengthBuf() {
2023-03-10 23:58:36 +08:00
valLen := len(enc.valBuf)
size := encoding.SizeOfPVarInt32(int32(valLen))
2022-10-10 14:47:49 +08:00
codec := encoding.VarCodec{Size: size}
tmp := make([]byte, size)
2023-03-10 23:58:36 +08:00
err := codec.EncodePVarInt32(tmp, int32(valLen))
2022-10-07 15:30:45 +08:00
if err != nil {
2022-10-10 14:47:49 +08:00
panic(err)
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
enc.buf.Write(tmp)
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
// Encode returns a final Y3 encoded byte slice
func (enc *encoder) Encode() []byte {
if !enc.complete {
// Tag
enc.writeTag()
// Len
enc.writeLengthBuf()
// Val
2023-03-10 23:58:36 +08:00
enc.buf.Write(enc.valBuf)
2022-10-10 14:47:49 +08:00
enc.complete = true
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
return enc.buf.Bytes()
2022-10-07 15:30:45 +08:00
}