state: optimize NEP17Balance serialization

Put to slice directly and allow to provide pre-allocated buffer.
```
BenchmarkNEP17BalanceBytes/stackitem-8         	 1712475	       673.4 ns/op	     448 B/op	       9 allocs/op
BenchmarkNEP17BalanceBytes/bytes-8             	13422715	        75.80 ns/op	      32 B/op	       2 allocs/op
BenchmarkNEP17BalanceBytes/bytes,_prealloc-8   	25990371	        46.46 ns/op	      16 B/op	       1 allocs/op
```

Signed-off-by: Evgeniy Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgeniy Stratonikov 2021-08-04 11:24:02 +03:00
parent b989504d74
commit 3218b74ea5
3 changed files with 66 additions and 3 deletions

View file

@ -7,6 +7,7 @@ import (
"math/big"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/encoding/bigint"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
@ -33,8 +34,20 @@ func NEP17BalanceFromBytes(b []byte) (*NEP17Balance, error) {
}
// Bytes returns serialized NEP17Balance.
func (s *NEP17Balance) Bytes() []byte {
return balanceToBytes(s)
func (s *NEP17Balance) Bytes(buf []byte) []byte {
if cap(buf) < 4+bigint.MaxBytesLen {
buf = make([]byte, 4, 4+bigint.MaxBytesLen)
} else {
buf = buf[:4]
}
buf[0] = byte(stackitem.StructT)
buf[1] = 1
buf[2] = byte(stackitem.IntegerT)
data := bigint.ToPreallocatedBytes(&s.Balance, buf[4:])
buf[3] = byte(len(data)) // max is 33, so we are ok here
buf = append(buf, data...)
return buf
}
func balanceFromBytes(b []byte, item stackitem.Convertible) error {