io: simplify WriteBytes()

Which speeds it up at least twofold for a typical 32-bytes write (and that's
for a very naïve test that allocates new BufBinWriter on every iteration):

pkg: github.com/CityOfZion/neo-go/pkg/io
BenchmarkWriteBytes-8           10000000               124 ns/op
BenchmarkWriteBytesOld-8         5000000               251 ns/op
This commit is contained in:
Roman Khimov 2019-12-06 17:40:47 +03:00
parent c034aae378
commit e7687d620d
2 changed files with 10 additions and 2 deletions

View file

@ -95,13 +95,16 @@ func (w *BinWriter) WriteVarUint(val uint64) {
// WriteBytes writes a variable byte into the underlying io.Writer without prefix.
func (w *BinWriter) WriteBytes(b []byte) {
w.WriteLE(b)
if w.Err != nil {
return
}
_, w.Err = w.w.Write(b)
}
// WriteVarBytes writes a variable length byte array into the underlying io.Writer.
func (w *BinWriter) WriteVarBytes(b []byte) {
w.WriteVarUint(uint64(len(b)))
w.WriteLE(b)
w.WriteBytes(b)
}
// WriteString writes a variable length string into the underlying io.Writer.

View file

@ -210,6 +210,11 @@ func TestWriteBytes(t *testing.T) {
buf := bw.Bytes()
assert.Equal(t, 4, len(buf))
assert.Equal(t, byte(0xde), buf[0])
bw = NewBufBinWriter()
bw.Err = errors.New("smth bad")
bw.WriteBytes(bin)
assert.Equal(t, 0, bw.Len())
}
type testSerializable uint16