-
Notifications
You must be signed in to change notification settings - Fork 18
/
big_int.go
126 lines (95 loc) · 2.12 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright 2022 Fluidity Money. All rights reserved. Use of this
// source code is governed by a GPL-style license that can be found in the
// LICENSE.md file.
package misc
// big_int contains exceedingly large numbers, wrapping big.Int
import (
sqlDriver "database/sql/driver"
"encoding/json"
"fmt"
"math/big"
)
// BigInt contains big.Int and has some extra functions to support storage
// in the database with the type NUMERIC(78, 0).
type BigInt struct {
big.Int
}
func BigIntFromString(s string) (*BigInt, error) {
var int BigInt
if _, success := int.SetString(s, 10); !success {
return nil, fmt.Errorf(
"Failed to set the bigint! Bad string number!",
)
}
return &int, nil
}
func BigIntFromInt64(x int64) BigInt {
var int BigInt
int.SetInt64(x)
return int
}
func BigIntFromUint64(x uint64) BigInt {
var int BigInt
int.SetUint64(x)
return int
}
func NewBigIntFromInt(x big.Int) BigInt {
return BigInt{x}
}
func (i *BigInt) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return fmt.Errorf(
"failed to unmarshal a JSON marshalled byte array of %v to a string! %v",
b,
err,
)
}
int, err := BigIntFromString(str)
if err != nil {
return fmt.Errorf(
"failed to unharsmal a BigInt of %v! %v",
str,
err,
)
}
*i = *int
return nil
}
func (i BigInt) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
func (int BigInt) Value() (sqlDriver.Value, error) {
return int.String(), nil
}
// Scan types into BigInt, supporting NUMERIC(78, 0), int64, uint64
func (int *BigInt) Scan(v interface{}) error {
if v == nil {
return nil
}
switch v.(type) {
case int64:
n := BigIntFromInt64(v.(int64))
*int = n
case uint64:
n := BigIntFromUint64(v.(uint64))
*int = n
case []uint8:
uint8 := v.([]uint8)
int_, err := BigIntFromString(string(uint8))
if err != nil {
return fmt.Errorf(
"Failed to scan uint8[] using the BigIntFromString function! %v",
err,
)
}
*int = *int_
default:
return fmt.Errorf(
"Failed to scan type %T content %v into the BigInt type!",
v,
v,
)
}
return nil
}