More efficient message marshaling

This commit is contained in:
Neale Pickett 2020-04-12 20:55:17 -06:00
parent 7492e9d5bb
commit a28a0bb2df
2 changed files with 4 additions and 11 deletions

View File

@ -3,7 +3,6 @@ package main
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"log"
) )
// VailMessage is a single Vail message. // VailMessage is a single Vail message.
@ -19,31 +18,25 @@ type Message struct {
Duration []uint8 Duration []uint8
} }
// Marshaling presumes something else is keeping track of lengths
func (m Message) MarshalBinary() ([]byte, error) { func (m Message) MarshalBinary() ([]byte, error) {
var w bytes.Buffer var w bytes.Buffer
if err := binary.Write(&w, binary.BigEndian, m.Timestamp); err != nil { if err := binary.Write(&w, binary.BigEndian, m.Timestamp); err != nil {
return nil, err return nil, err
} }
dlen := uint16(len(m.Duration))
if err := binary.Write(&w, binary.BigEndian, dlen); err != nil {
return nil, err
}
if err := binary.Write(&w, binary.BigEndian, m.Duration); err != nil { if err := binary.Write(&w, binary.BigEndian, m.Duration); err != nil {
return nil, err return nil, err
} }
return w.Bytes(), nil return w.Bytes(), nil
} }
// Unmarshaling presumes something else is keeping track of lengths
func (m *Message) UnmarshalBinary(data []byte) error { func (m *Message) UnmarshalBinary(data []byte) error {
r := bytes.NewReader(data) r := bytes.NewReader(data)
if err := binary.Read(r, binary.BigEndian, &m.Timestamp); err != nil { if err := binary.Read(r, binary.BigEndian, &m.Timestamp); err != nil {
return err return err
} }
log.Printf("timestamp %x", m.Timestamp) dlen := r.Len()
var dlen uint16
if err := binary.Read(r, binary.BigEndian, &dlen); err != nil {
return err
}
m.Duration = make([]uint8, dlen) m.Duration = make([]uint8, dlen)
if err := binary.Read(r, binary.BigEndian, &m.Duration); err != nil { if err := binary.Read(r, binary.BigEndian, &m.Duration); err != nil {
return err return err

View File

@ -23,7 +23,7 @@ func TestMessage(t *testing.T) {
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if ! bytes.Equal(bm, []byte("\x11\x22\x33\x44\x55\x66\x77\x88\x00\x03\xaa\xbb\xcc")) { if ! bytes.Equal(bm, []byte("\x11\x22\x33\x44\x55\x66\x77\x88\xaa\xbb\xcc")) {
t.Error("Encoded wrong:", bm) t.Error("Encoded wrong:", bm)
} }