40 lines
782 B
Go
40 lines
782 B
Go
package nixwire
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"io"
|
|
)
|
|
|
|
type Serializer struct {
|
|
io.Writer
|
|
}
|
|
|
|
func (w Serializer) WritePadding(n int64) (int64, error) {
|
|
if n%8 > 0 {
|
|
n, err := w.Write(make([]byte, 8-(n%8)))
|
|
return int64(n), err
|
|
}
|
|
return 0, nil
|
|
}
|
|
|
|
func (w Serializer) WriteUint64(n uint64) (int64, error) {
|
|
buf := make([]byte, 8)
|
|
binary.LittleEndian.PutUint64(buf, n)
|
|
wrote, err := w.Write(buf)
|
|
return int64(wrote), err
|
|
}
|
|
|
|
func (w Serializer) WriteString(s string) (int64, error) {
|
|
nSize, err := w.WriteUint64(uint64(len(s)))
|
|
if err != nil {
|
|
return int64(nSize), err
|
|
}
|
|
|
|
nData, err := w.Write([]byte(s))
|
|
if err != nil {
|
|
return int64(nSize) + int64(nData), err
|
|
}
|
|
|
|
nPad, err := w.WritePadding(int64(len(s)))
|
|
return int64(nSize) + int64(nData) + int64(nPad), err
|
|
}
|