aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-02-10 09:58:41 +0100
committerOnur Gündüz <ogunduz@gmail.com>2026-02-10 09:58:41 +0100
commit498118ff4f4c2b0f95e943bf32868a845fb0d1ff (patch)
tree9b26fb02bf3e0baeec487b8ac426badbc625388e
parent6c8ec632074bc7e36028ae8d425d951ee8e693fd (diff)
downloadmuxer-498118ff4f4c2b0f95e943bf32868a845fb0d1ff.tar.gz
muxer-498118ff4f4c2b0f95e943bf32868a845fb0d1ff.zip
Use scratch buffer in writer for varint encoding
-rw-r--r--writer.go33
1 files changed, 13 insertions, 20 deletions
diff --git a/writer.go b/writer.go
index 035b1aa..34b2496 100644
--- a/writer.go
+++ b/writer.go
@@ -8,7 +8,8 @@ import (
// A Writer implements convenience methods for writing
// requests or responses to a binary protocol network connection.
type Writer struct {
- wd *bufio.Writer
+ wd *bufio.Writer
+ scratch [20]byte
}
// NewWriter returns a new Writer writing to w.
@@ -18,29 +19,21 @@ func NewWriter(wd *bufio.Writer) *Writer {
// WriteMessage writes a variable number of messages to w.
func (w *Writer) WriteMessage(messages ...*Message) error {
- var vb [10]byte // max 10 bytes per varint
-
for _, m := range messages {
- header := uint64(m.ID<<4) | uint64(m.Channel)
- bodyLen := uint64(encodingLength(header) + len(m.Data))
-
- // write body length varint
- n := binary.PutUvarint(vb[:], bodyLen)
- if _, err := w.wd.Write(vb[:n]); err != nil {
- return err
- }
-
- // write header varint
- n = binary.PutUvarint(vb[:], header)
- if _, err := w.wd.Write(vb[:n]); err != nil {
+ header := m.ID<<4 | uint64(m.Channel)
+ 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
}
-
- // write data payload
- if _, err := w.wd.Write(m.Data); err != nil {
- return err
+ if len(m.Data) > 0 {
+ if _, err := w.wd.Write(m.Data); err != nil {
+ return err
+ }
}
}
-
return w.wd.Flush()
}