lotus/chain/types/bigint.go

97 lines
2.0 KiB
Go
Raw Normal View History

package types
import (
"fmt"
"math/big"
2020-02-08 02:18:32 +00:00
big2 "github.com/filecoin-project/specs-actors/actors/abi/big"
2019-09-25 20:52:28 +00:00
2020-02-08 02:18:32 +00:00
"github.com/filecoin-project/lotus/build"
)
const BigIntMaxSerializedLen = 128 // is this big enough? or too big?
var TotalFilecoinInt = FromFil(build.TotalFilecoin)
var EmptyInt = BigInt{}
2020-02-08 02:18:32 +00:00
type BigInt = big2.Int
func NewInt(i uint64) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).SetUint64(i)}
}
2019-09-16 16:47:42 +00:00
func FromFil(i uint64) BigInt {
return BigMul(NewInt(i), NewInt(build.FilecoinPrecision))
}
func BigFromBytes(b []byte) BigInt {
i := big.NewInt(0).SetBytes(b)
2020-03-06 06:46:07 +00:00
return BigInt{Int: i}
}
func BigFromString(s string) (BigInt, error) {
v, ok := big.NewInt(0).SetString(s, 10)
if !ok {
return BigInt{}, fmt.Errorf("failed to parse string as a big int")
}
2020-03-06 06:46:07 +00:00
return BigInt{Int: v}, nil
}
func BigMul(a, b BigInt) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).Mul(a.Int, b.Int)}
}
2019-08-15 02:30:21 +00:00
func BigDiv(a, b BigInt) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).Div(a.Int, b.Int)}
2019-08-15 02:30:21 +00:00
}
func BigMod(a, b BigInt) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).Mod(a.Int, b.Int)}
}
func BigAdd(a, b BigInt) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).Add(a.Int, b.Int)}
}
func BigSub(a, b BigInt) BigInt {
2020-03-06 06:46:07 +00:00
return BigInt{Int: big.NewInt(0).Sub(a.Int, b.Int)}
}
func BigCmp(a, b BigInt) int {
return a.Int.Cmp(b.Int)
}
2020-04-21 19:46:50 +00:00
var byteSizeUnits = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"}
2020-02-08 02:18:32 +00:00
func SizeStr(bi BigInt) string {
r := new(big.Rat).SetInt(bi.Int)
den := big.NewRat(1, 1024)
var i int
2020-04-21 19:46:50 +00:00
for f, _ := r.Float64(); f >= 1024 && i+1 < len(byteSizeUnits); f, _ = r.Float64() {
i++
r = r.Mul(r, den)
}
f, _ := r.Float64()
2020-04-21 19:46:50 +00:00
return fmt.Sprintf("%.3g %s", f, byteSizeUnits[i])
}
var decUnits = []string{"", "K", "M", "G", "T", "P", "E", "Z"}
func DecStr(bi BigInt) string {
r := new(big.Rat).SetInt(bi.Int)
den := big.NewRat(1, 1000)
var i int
for f, _ := r.Float64(); f >= 1000 && i+1 < len(decUnits); f, _ = r.Float64() {
i++
r = r.Mul(r, den)
}
f, _ := r.Float64()
return fmt.Sprintf("%.3g %s", f, decUnits[i])
}