From e7687d620db59fc31893ff9faada43246b043bcc Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 6 Dec 2019 17:40:47 +0300 Subject: [PATCH] io: simplify WriteBytes() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- pkg/io/binaryWriter.go | 7 +++++-- pkg/io/binaryrw_test.go | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/pkg/io/binaryWriter.go b/pkg/io/binaryWriter.go index b5aee0d0c..16e9dfc77 100644 --- a/pkg/io/binaryWriter.go +++ b/pkg/io/binaryWriter.go @@ -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. diff --git a/pkg/io/binaryrw_test.go b/pkg/io/binaryrw_test.go index 6a6278e1e..19a8c2a55 100644 --- a/pkg/io/binaryrw_test.go +++ b/pkg/io/binaryrw_test.go @@ -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