dsfx/pkg/encoding/vwb/vwb.go
2025-03-07 21:05:37 -05:00

56 lines
1.2 KiB
Go

// Package vwb provides utilities for working with variable-width byte slices,
// usually in the context of network requests.
package vwb
import (
"fmt"
"io"
)
func debugf(msg string, args ...any) {
fmt.Printf("(encoding/vwb): "+msg, args...)
}
// Encode ...
func Encode(w io.Writer, input []byte) error {
debugf("encoding %d bytes\n", len(input))
buf := make([]byte, 0, len(input)+2)
// Write the length of the input
buf = append(buf, byte(len(input)>>8), byte(len(input)))
// Write the input
buf = append(buf, input...)
debugf("writing %d bytes\n", len(buf))
// Write the buffer to the writer
if _, err := w.Write(buf); err != nil {
return err
}
return nil
}
// Decode ...
func Decode(r io.Reader) ([]byte, error) {
debugf("beginning decode\n")
var lenbuf [2]byte
// Read the length of the input
if _, err := io.ReadFull(r, lenbuf[:]); err != nil {
return nil, err
}
debugf("read %d bytes for length\n", lenbuf)
// Calculate the length of the input
length := int(lenbuf[0])<<8 | int(lenbuf[1])
debugf("reading %d byte sized message\n", length)
// Read the input
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, err
}
debugf("done\n")
return data, nil
}