mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-25 22:26:42 +00:00
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.
This commit is contained in:
parent
0f036f6209
commit
81c76e07dc
1 changed files with 10 additions and 5 deletions
|
|
@ -116,14 +116,19 @@ func FirstBitSet(v *big.Int) int {
|
||||||
//
|
//
|
||||||
// Returns the bytes of a big integer with the size specified by **base**
|
// Returns the bytes of a big integer with the size specified by **base**
|
||||||
// Attempts to pad the byte array with zeros.
|
// 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 {
|
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 {
|
if blen > bpb {
|
||||||
return num.Bytes()
|
return bytes
|
||||||
}
|
}
|
||||||
|
padBuf := make([]byte, bpb)
|
||||||
return append(ret[:len(ret)-len(num.Bytes())], num.Bytes()...)
|
return append(padBuf[:bpb-blen], bytes...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Big copy
|
// Big copy
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue