aboutsummaryrefslogtreecommitdiff
path: root/writer.go
blob: 3980f032f9adfe69284d568a78ca6dbaa66125a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package muxer

import (
	"bufio"
	"encoding/binary"
)

// Writer implements a buffered message writer for the muxer protocol.
// It encodes and writes messages to an underlying bufio.Writer, handling
// message framing and varint-based length encoding. Writer is not safe for
// concurrent use by multiple goroutines.
type Writer struct {
	wd      *bufio.Writer
	scratch [20]byte
}

// NewWriter returns a new Writer writing to w.
func NewWriter(wd *bufio.Writer) *Writer {
	return &Writer{wd: wd}
}

// WriteMessage writes a variable number of messages to w.
func (w *Writer) WriteMessage(messages ...*Message) error {
	for _, m := range messages {
		header := m.ID<<4 | uint64(m.Type)
		headerLen := binary.PutUvarint(w.scratch[10:], header)
		bodyLen := uint64(headerLen + len(m.Data))
		lengthSize := binary.PutUvarint(w.scratch[:10], bodyLen)
		// Shift header bytes to be adjacent to length bytes
		copy(w.scratch[lengthSize:], w.scratch[10:10+headerLen])
		if _, err := w.wd.Write(w.scratch[:lengthSize+headerLen]); err != nil {
			return err
		}
		if len(m.Data) > 0 {
			if _, err := w.wd.Write(m.Data); err != nil {
				return err
			}
		}
	}
	return w.wd.Flush()
}