2019-02-25 22:44:14 +00:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2019-03-17 18:26:35 +00:00
|
|
|
//BinWriter is a convenient wrapper around a io.Writer and err object
|
|
|
|
// Used to simplify error handling when writing into a io.Writer
|
|
|
|
// from a struct with many fields
|
2019-02-25 22:44:14 +00:00
|
|
|
type BinWriter struct {
|
|
|
|
W io.Writer
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
2019-08-28 10:24:06 +00:00
|
|
|
// WriteLE writes into the underlying io.Writer from an object v in little-endian format
|
|
|
|
func (w *BinWriter) WriteLE(v interface{}) {
|
2019-02-25 22:44:14 +00:00
|
|
|
if w.Err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, v)
|
|
|
|
}
|
|
|
|
|
2019-08-28 10:24:06 +00:00
|
|
|
// WriteBE writes into the underlying io.Writer from an object v in big-endian format
|
|
|
|
func (w *BinWriter) WriteBE(v interface{}) {
|
2019-02-25 22:44:14 +00:00
|
|
|
if w.Err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Err = binary.Write(w.W, binary.BigEndian, v)
|
|
|
|
}
|
|
|
|
|
2019-08-28 10:24:06 +00:00
|
|
|
// WriteVarUint writes a uint64 into the underlying writer using variable-length encoding
|
|
|
|
func (w *BinWriter) WriteVarUint(val uint64) {
|
2019-08-29 10:24:03 +00:00
|
|
|
if w.Err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-02-25 22:44:14 +00:00
|
|
|
if val < 0 {
|
|
|
|
w.Err = errors.New("value out of range")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if w.Err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if val < 0xfd {
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, uint8(val))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if val < 0xFFFF {
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, byte(0xfd))
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, uint16(val))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if val < 0xFFFFFFFF {
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, byte(0xfe))
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, uint32(val))
|
|
|
|
return
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, byte(0xff))
|
|
|
|
w.Err = binary.Write(w.W, binary.LittleEndian, val)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-08-28 10:24:06 +00:00
|
|
|
// WriteBytes writes a variable length byte array into the underlying io.Writer
|
|
|
|
func (w *BinWriter) WriteBytes(b []byte) {
|
|
|
|
w.WriteVarUint(uint64(len(b)))
|
|
|
|
w.WriteLE(b)
|
2019-02-25 22:44:14 +00:00
|
|
|
}
|
2019-03-17 18:26:35 +00:00
|
|
|
|
2019-08-28 10:24:06 +00:00
|
|
|
// WriteString writes a variable length string into the underlying io.Writer
|
|
|
|
func (w *BinWriter) WriteString(s string) {
|
|
|
|
w.WriteBytes([]byte(s))
|
2019-03-17 18:26:35 +00:00
|
|
|
}
|