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
valbuf []byte
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 {
return enc.valbuf
2022-10-07 15:30:45 +08:00
}
2022-10-10 14:47:49 +08:00
func (enc *encoder) IsEmpty() bool {
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) {
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) {
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() {
vallen := len(enc.valbuf)
size := encoding.SizeOfPVarInt32(int32(vallen))
codec := encoding.VarCodec{Size: size}
tmp := make([]byte, size)
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
enc.buf.Write(enc.valbuf)
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
}