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:
Roman Khimov 2019-12-12 18:52:23 +03:00
parent 89d7f6d26e
commit 54d888ba70
43 changed files with 441 additions and 205 deletions

View file

@ -5,6 +5,8 @@ import (
"errors"
"strconv"
"strings"
"github.com/CityOfZion/neo-go/pkg/io"
)
const (
@ -109,6 +111,16 @@ func (f Fixed8) MarshalJSON() ([]byte, error) {
return []byte(`"` + f.String() + `"`), nil
}
// DecodeBinary implements the io.Serializable interface.
func (f *Fixed8) DecodeBinary(r *io.BinReader) {
*f = Fixed8(r.ReadU64LE())
}
// EncodeBinary implements the io.Serializable interface.
func (f *Fixed8) EncodeBinary(w *io.BinWriter) {
w.WriteU64LE(uint64(*f))
}
// Satoshi defines the value of a 'Satoshi'.
func Satoshi() Fixed8 {
return Fixed8(1)

View file

@ -5,7 +5,9 @@ import (
"strconv"
"testing"
"github.com/CityOfZion/neo-go/pkg/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFixed8FromInt64(t *testing.T) {
@ -134,3 +136,16 @@ func TestFixed8_Arith(t *testing.T) {
assert.Zero(t, u1.CompareTo(u1))
assert.EqualValues(t, Fixed8(2), u2.Div(3))
}
func TestFixed8_Serializable(t *testing.T) {
a := Fixed8(0x0102030405060708)
w := io.NewBufBinWriter()
a.EncodeBinary(w.BinWriter)
require.NoError(t, w.Err)
var b Fixed8
r := io.NewBinReaderFromBuf(w.Bytes())
b.DecodeBinary(r)
require.Equal(t, a, b)
}