From a28a0bb2df01a74ac161591893a13cbf2ae20a1e Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Sun, 12 Apr 2020 20:55:17 -0600 Subject: [PATCH] More efficient message marshaling --- message.go | 13 +++---------- message_test.go | 2 +- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/message.go b/message.go index ee7cb87..d42defc 100644 --- a/message.go +++ b/message.go @@ -3,7 +3,6 @@ package main import ( "bytes" "encoding/binary" - "log" ) // VailMessage is a single Vail message. @@ -19,31 +18,25 @@ type Message struct { Duration []uint8 } +// Marshaling presumes something else is keeping track of lengths func (m Message) MarshalBinary() ([]byte, error) { var w bytes.Buffer if err := binary.Write(&w, binary.BigEndian, m.Timestamp); err != nil { 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 { return nil, err } return w.Bytes(), nil } +// Unmarshaling presumes something else is keeping track of lengths func (m *Message) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) if err := binary.Read(r, binary.BigEndian, &m.Timestamp); err != nil { return err } - log.Printf("timestamp %x", m.Timestamp) - var dlen uint16 - if err := binary.Read(r, binary.BigEndian, &dlen); err != nil { - return err - } + dlen := r.Len() m.Duration = make([]uint8, dlen) if err := binary.Read(r, binary.BigEndian, &m.Duration); err != nil { return err diff --git a/message_test.go b/message_test.go index cd6f452..bc31454 100644 --- a/message_test.go +++ b/message_test.go @@ -23,7 +23,7 @@ func TestMessage(t *testing.T) { if err != nil { 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) }