From 81c76e07dcb64526d85266598c5835361faef0d8 Mon Sep 17 00:00:00 2001 From: Joubin Muhammad Houshyar Date: Wed, 8 Jun 2016 14:07:37 -0400 Subject: [PATCH] common: enhanced performance for BytesToBig * allocate padded buffer only if padding is possible * get bytes only once: each call to big.Int.Bytes() allocates. * nop - be explicit in func comment regarding valid input args. --- common/big.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/common/big.go b/common/big.go index 4ce87ee0c6..5e95224ef0 100644 --- a/common/big.go +++ b/common/big.go @@ -116,14 +116,19 @@ func FirstBitSet(v *big.Int) int { // // Returns the bytes of a big integer with the size specified by **base** // Attempts to pad the byte array with zeros. +// +// Note that input arg **num** is expected to be non-nil; +// nil argument will result in runtime panic. func BigToBytes(num *big.Int, base int) []byte { - ret := make([]byte, base/8) + bytes := num.Bytes() + blen := len(bytes) + bpb := base / 8 - if len(num.Bytes()) > base/8 { - return num.Bytes() + if blen > bpb { + return bytes } - - return append(ret[:len(ret)-len(num.Bytes())], num.Bytes()...) + padBuf := make([]byte, bpb) + return append(padBuf[:bpb-blen], bytes...) } // Big copy