io: add type-specific read/write methods
This seriously improves the serialization/deserialization performance for several reasons: * no time spent in `binary` reflection * no memory allocations being made on every read/write * uses fast ReadBytes everywhere it's appropriate It also makes Fixed8 Serializable just for convenience.
This commit is contained in:
parent
89d7f6d26e
commit
54d888ba70
43 changed files with 441 additions and 205 deletions
|
@ -11,12 +11,20 @@ import (
|
|||
// from a struct with many fields.
|
||||
type BinWriter struct {
|
||||
w io.Writer
|
||||
u64 []byte
|
||||
u32 []byte
|
||||
u16 []byte
|
||||
u8 []byte
|
||||
Err error
|
||||
}
|
||||
|
||||
// NewBinWriterFromIO makes a BinWriter from io.Writer.
|
||||
func NewBinWriterFromIO(iow io.Writer) *BinWriter {
|
||||
return &BinWriter{w: iow}
|
||||
u64 := make([]byte, 8)
|
||||
u32 := u64[:4]
|
||||
u16 := u64[:2]
|
||||
u8 := u64[:1]
|
||||
return &BinWriter{w: iow, u64: u64, u32: u32, u16: u16, u8: u8}
|
||||
}
|
||||
|
||||
// WriteLE writes into the underlying io.Writer from an object v in little-endian format.
|
||||
|
@ -35,6 +43,50 @@ func (w *BinWriter) WriteBE(v interface{}) {
|
|||
w.Err = binary.Write(w.w, binary.BigEndian, v)
|
||||
}
|
||||
|
||||
// WriteU64LE writes an uint64 value into the underlying io.Writer in
|
||||
// little-endian format.
|
||||
func (w *BinWriter) WriteU64LE(u64 uint64) {
|
||||
binary.LittleEndian.PutUint64(w.u64, u64)
|
||||
w.WriteBytes(w.u64)
|
||||
}
|
||||
|
||||
// WriteU32LE writes an uint32 value into the underlying io.Writer in
|
||||
// little-endian format.
|
||||
func (w *BinWriter) WriteU32LE(u32 uint32) {
|
||||
binary.LittleEndian.PutUint32(w.u32, u32)
|
||||
w.WriteBytes(w.u32)
|
||||
}
|
||||
|
||||
// WriteU16LE writes an uint16 value into the underlying io.Writer in
|
||||
// little-endian format.
|
||||
func (w *BinWriter) WriteU16LE(u16 uint16) {
|
||||
binary.LittleEndian.PutUint16(w.u16, u16)
|
||||
w.WriteBytes(w.u16)
|
||||
}
|
||||
|
||||
// WriteU16BE writes an uint16 value into the underlying io.Writer in
|
||||
// big-endian format.
|
||||
func (w *BinWriter) WriteU16BE(u16 uint16) {
|
||||
binary.BigEndian.PutUint16(w.u16, u16)
|
||||
w.WriteBytes(w.u16)
|
||||
}
|
||||
|
||||
// WriteByte writes a byte into the underlying io.Writer.
|
||||
func (w *BinWriter) WriteByte(u8 byte) {
|
||||
w.u8[0] = u8
|
||||
w.WriteBytes(w.u8)
|
||||
}
|
||||
|
||||
// WriteBool writes a boolean value into the underlying io.Writer encoded as
|
||||
// a byte with values of 0 or 1.
|
||||
func (w *BinWriter) WriteBool(b bool) {
|
||||
var i byte
|
||||
if b {
|
||||
i = 1
|
||||
}
|
||||
w.WriteByte(i)
|
||||
}
|
||||
|
||||
// WriteArray writes a slice or an array arr into w. Note that nil slices and
|
||||
// empty slices are gonna be treated the same resulting in equal zero-length
|
||||
// array encoded.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue