io: use optimized Read/WriteUXX for Read/WriteVarUint()

This commit is contained in:
Roman Khimov 2019-12-12 19:20:03 +03:00
parent 54d888ba70
commit 0b14916d79
2 changed files with 11 additions and 19 deletions

View file

@ -169,23 +169,16 @@ func (r *BinReader) ReadVarUint() uint64 {
return 0 return 0
} }
var b uint8 var b = r.ReadByte()
r.Err = binary.Read(r.r, binary.LittleEndian, &b)
if b == 0xfd { if b == 0xfd {
var v uint16 return uint64(r.ReadU16LE())
r.Err = binary.Read(r.r, binary.LittleEndian, &v)
return uint64(v)
} }
if b == 0xfe { if b == 0xfe {
var v uint32 return uint64(r.ReadU32LE())
r.Err = binary.Read(r.r, binary.LittleEndian, &v)
return uint64(v)
} }
if b == 0xff { if b == 0xff {
var v uint64 return r.ReadU64LE()
r.Err = binary.Read(r.r, binary.LittleEndian, &v)
return v
} }
return uint64(b) return uint64(b)

View file

@ -123,24 +123,23 @@ func (w *BinWriter) WriteVarUint(val uint64) {
} }
if val < 0xfd { if val < 0xfd {
w.Err = binary.Write(w.w, binary.LittleEndian, uint8(val)) w.WriteByte(byte(val))
return return
} }
if val < 0xFFFF { if val < 0xFFFF {
w.Err = binary.Write(w.w, binary.LittleEndian, byte(0xfd)) w.WriteByte(byte(0xfd))
w.Err = binary.Write(w.w, binary.LittleEndian, uint16(val)) w.WriteU16LE(uint16(val))
return return
} }
if val < 0xFFFFFFFF { if val < 0xFFFFFFFF {
w.Err = binary.Write(w.w, binary.LittleEndian, byte(0xfe)) w.WriteByte(byte(0xfe))
w.Err = binary.Write(w.w, binary.LittleEndian, uint32(val)) w.WriteU32LE(uint32(val))
return return
} }
w.Err = binary.Write(w.w, binary.LittleEndian, byte(0xff)) w.WriteByte(byte(0xff))
w.Err = binary.Write(w.w, binary.LittleEndian, val) w.WriteU64LE(val)
} }
// WriteBytes writes a variable byte into the underlying io.Writer without prefix. // WriteBytes writes a variable byte into the underlying io.Writer without prefix.