46 lines
939 B
Go
46 lines
939 B
Go
package ll
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"io"
|
|
"sync"
|
|
)
|
|
|
|
const hdrMagic string = "DJR"
|
|
const magicSize int = len(hdrMagic)
|
|
const remaningHeaderSize int = 3
|
|
const hdrSize int = magicSize + remaningHeaderSize
|
|
|
|
// Encoder writes Messages to an output stream
|
|
type Encoder struct {
|
|
w io.Writer
|
|
mu sync.Mutex
|
|
}
|
|
|
|
// NewEncoder returns a new encoder that writes to w
|
|
func NewEncoder(w io.Writer) *Encoder {
|
|
return &Encoder{w: w}
|
|
}
|
|
|
|
// Encode writes the Low-level encoding of m to the stream
|
|
func (enc *Encoder) Encode(m *Msg) error {
|
|
enc.mu.Lock()
|
|
|
|
if _, err := enc.w.Write([]byte(hdrMagic)); err != nil {
|
|
enc.mu.Unlock()
|
|
return err
|
|
}
|
|
if err := binary.Write(enc.w, binary.BigEndian, uint8(m.Type)); err != nil {
|
|
enc.mu.Unlock()
|
|
return err
|
|
}
|
|
if err := binary.Write(enc.w, binary.BigEndian, uint16(len(m.Data)+hdrSize)); err != nil {
|
|
enc.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
_, err := enc.w.Write(m.Data)
|
|
enc.mu.Unlock()
|
|
return err
|
|
}
|