-
Notifications
You must be signed in to change notification settings - Fork 5
/
big_int.go
63 lines (54 loc) · 1.07 KB
/
big_int.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package int256
import (
"math/big"
"github.com/holiman/uint256"
)
var negativeOneBigInt = big.NewInt(-1)
var zero = big.NewInt(0)
func (z *Int) ToBig() *big.Int {
b := z.abs.ToBig()
if z.neg {
return b.Mul(b, negativeOneBigInt)
}
return b
}
func MustFromBig(x *big.Int) *Int {
big, overflow := FromBig(x)
if overflow {
panic("cannot parsing from big.Int")
}
return big
}
func FromBig(x *big.Int) (*Int, bool) {
num := x
neg := false
if x.Cmp(zero) == -1 {
num = new(big.Int).Mul(x, negativeOneBigInt)
neg = true
}
abs, overflow := uint256.FromBig(num)
/*
type Int [4]uint64
Currently, uint26 has maxWord is 4
bigInt has len(words) that can great than 4. So we can receive overflow error.
words := b.Bits()
overflow := len(words) > maxWords
ref from uint256 code
https://github.com/holiman/uint256/blob/master/conversion.go#L202
*/
if overflow {
abs, err := uint256.FromDecimal(x.String())
if err != nil {
return nil, overflow
}
neg = x.Sign() < 0
return &Int{
abs,
neg,
}, true
}
return &Int{
abs,
neg,
}, false
}