mirror of https://github.com/nealey/vail.git
More efficient message marshaling
This commit is contained in:
parent
7492e9d5bb
commit
a28a0bb2df
13
message.go
13
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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue