lotus/chain/types/bigint.go

101 lines
2.1 KiB
Go
Raw Normal View History

package types
import (
"fmt"
"math/big"
2020-09-07 03:49:10 +00:00
big2 "github.com/filecoin-project/go-state-types/big"
2020-02-08 02:18:32 +00:00
"github.com/filecoin-project/lotus/build"
)
const BigIntMaxSerializedLen = 128 // is this big enough? or too big?
2020-07-27 23:10:13 +00:00
var TotalFilecoinInt = FromFil(build.FilBase)
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 BigDivFloat(num, den BigInt) float64 {
res, _ := new(big.Rat).SetFrac(num.Int, den.Int).Float64()
return res
}
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()
return fmt.Sprintf("%.4g %s", f, byteSizeUnits[i])
2020-04-21 19:46:50 +00:00
}
2020-05-01 12:06:19 +00:00
var deciUnits = []string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"}
2020-04-21 19:46:50 +00:00
2020-05-01 12:06:19 +00:00
func DeciStr(bi BigInt) string {
2020-04-21 19:46:50 +00:00
r := new(big.Rat).SetInt(bi.Int)
2020-05-01 12:06:19 +00:00
den := big.NewRat(1, 1024)
2020-04-21 19:46:50 +00:00
var i int
2020-05-01 12:06:19 +00:00
for f, _ := r.Float64(); f >= 1024 && i+1 < len(deciUnits); f, _ = r.Float64() {
2020-04-21 19:46:50 +00:00
i++
r = r.Mul(r, den)
}
f, _ := r.Float64()
2020-05-01 12:06:19 +00:00
return fmt.Sprintf("%.3g %s", f, deciUnits[i])
}