From 3945e8185773c1001ad698f94271a082260aacbe Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Tue, 31 May 2022 12:45:34 +0300 Subject: [PATCH] bigint: don't allocate in ToPreallocatedBytes() for negative numbers In-place modifications are somewhat dangerous, but yet another allocation is quite costly. --- pkg/encoding/bigint/bigint.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pkg/encoding/bigint/bigint.go b/pkg/encoding/bigint/bigint.go index 41f3c599e..26a6849f8 100644 --- a/pkg/encoding/bigint/bigint.go +++ b/pkg/encoding/bigint/bigint.go @@ -112,18 +112,16 @@ func ToPreallocatedBytes(n *big.Int, data []byte) []byte { return data } - var ws []big.Word - if sign == 1 { - ws = n.Bits() - } else { - n1 := new(big.Int).Add(n, bigOne) - if n1.Sign() == 0 { // n == -1 + if sign < 0 { + n.Add(n, bigOne) + defer func() { n.Sub(n, bigOne) }() + if n.Sign() == 0 { // n == -1 return append(data, 0xFF) } - - ws = n1.Bits() } + var ws = n.Bits() + lb := len(ws) * wordSizeBytes if c := cap(data); c < lb { data = make([]byte, lb, lb+1)