meta/msgpack_writer.go

97 lines
2.5 KiB
Go

package meta
import (
"io"
"github.com/pkg/errors"
"github.com/vmihailenco/msgpack/v5"
)
type msgpackWriter struct {
enc *msgpack.Encoder
containers []struct{}
}
func NewMsgpackWriter(w io.Writer) Writer {
return &msgpackWriter{
enc: msgpack.NewEncoder(w),
containers: make([]struct{}, 0, 1),
}
}
func (wr *msgpackWriter) WriteInt8(v int8, field string) error {
return errors.WithStack(wr.enc.EncodeInt(int64(v)))
}
func (wr *msgpackWriter) WriteInt16(v int16, field string) error {
return errors.WithStack(wr.enc.EncodeInt(int64(v)))
}
func (wr *msgpackWriter) WriteInt32(v int32, field string) error {
return errors.WithStack(wr.enc.EncodeInt(int64(v)))
}
func (wr *msgpackWriter) WriteInt64(v int64, field string) error {
return errors.WithStack(wr.enc.EncodeInt(v))
}
func (wr *msgpackWriter) WriteUint8(v uint8, field string) error {
return errors.WithStack(wr.enc.EncodeUint(uint64(v)))
}
func (wr *msgpackWriter) WriteUint16(v uint16, field string) error {
return errors.WithStack(wr.enc.EncodeUint(uint64(v)))
}
func (wr *msgpackWriter) WriteUint32(v uint32, field string) error {
return errors.WithStack(wr.enc.EncodeUint(uint64(v)))
}
func (wr *msgpackWriter) WriteUint64(v uint64, field string) error {
return errors.WithStack(wr.enc.EncodeUint(uint64(v)))
}
func (wr *msgpackWriter) WriteBool(v bool, field string) error {
return errors.WithStack(wr.enc.EncodeBool(v))
}
func (wr *msgpackWriter) WriteFloat32(v float32, field string) error {
return errors.WithStack(wr.enc.EncodeFloat32(v))
}
func (wr *msgpackWriter) WriteFloat64(v float64, field string) error {
return errors.WithStack(wr.enc.EncodeFloat64(v))
}
func (wr *msgpackWriter) WriteString(v string, field string) error {
return errors.WithStack(wr.enc.EncodeString(v))
}
func (wr *msgpackWriter) WriteBytes(v []byte, field string) error {
return errors.WithStack(wr.enc.EncodeBytes(v))
}
func (wr *msgpackWriter) BeginContainer(length int, field string) error {
return wr.BeginCollection(length, field)
}
func (wr *msgpackWriter) EndContainer() error {
return wr.EndCollection()
}
func (wr *msgpackWriter) BeginCollection(length int, field string) error {
if err := wr.enc.EncodeArrayLen(length); err != nil {
return errors.WithStack(err)
}
wr.containers = append(wr.containers, struct{}{})
return nil
}
func (wr *msgpackWriter) EndCollection() error {
if len(wr.containers) == 0 {
return errors.New("there is no open containers")
}
wr.containers = wr.containers[:len(wr.containers)-1]
return nil
}