-
Notifications
You must be signed in to change notification settings - Fork 13
/
mixinnet_number.go
88 lines (74 loc) · 1.48 KB
/
mixinnet_number.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package mixin
import (
"math"
"math/big"
"strconv"
"strings"
"github.com/fox-one/msgpack"
"github.com/shopspring/decimal"
)
const Precision = 8
var Zero Integer
type (
Integer struct {
i big.Int
}
)
func init() {
msgpack.RegisterExt(0, (*Integer)(nil))
Zero = NewInteger(0)
}
func NewInteger(x uint64) (v Integer) {
p := new(big.Int).SetUint64(x)
d := big.NewInt(int64(math.Pow(10, Precision)))
v.i.Mul(p, d)
return
}
func NewIntegerFromDecimal(d decimal.Decimal) (v Integer) {
if d.Sign() <= 0 {
panic(d)
}
s := d.Mul(decimal.New(1, Precision)).StringFixed(0)
v.i.SetString(s, 10)
return
}
func NewIntegerFromString(x string) (v Integer) {
d, err := decimal.NewFromString(x)
if err != nil {
panic(err)
}
if d.Sign() <= 0 {
panic(x)
}
s := d.Mul(decimal.New(1, Precision)).StringFixed(0)
v.i.SetString(s, 10)
return
}
func (x Integer) String() string {
s := x.i.String()
p := len(s) - Precision
if p > 0 {
return s[:p] + "." + s[p:]
}
return "0." + strings.Repeat("0", -p) + s
}
func (x Integer) MarshalMsgpack() ([]byte, error) {
return x.i.Bytes(), nil
}
func (x *Integer) UnmarshalMsgpack(data []byte) error {
x.i.SetBytes(data)
return nil
}
func (x Integer) MarshalJSON() ([]byte, error) {
s := x.String()
return []byte(strconv.Quote(s)), nil
}
func (x *Integer) UnmarshalJSON(b []byte) error {
unquoted, err := strconv.Unquote(string(b))
if err != nil {
return err
}
i := NewIntegerFromString(unquoted)
x.i.SetBytes(i.i.Bytes())
return nil
}