-
Notifications
You must be signed in to change notification settings - Fork 5
/
bint.go
414 lines (336 loc) · 7.77 KB
/
bint.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package udecimal
import (
"bytes"
"fmt"
"math/big"
"strings"
)
const (
// maxDigitU64 is the maximum digits of a number
// that can be safely stored in a uint64.
maxDigitU64 = 19
)
var (
bigZero = big.NewInt(0)
bigOne = big.NewInt(1)
bigTen = big.NewInt(10)
)
// bint represents a whole decimal number without a decimal point.
// The value is always positive and is stored in a 128-bit unsigned integer.
// If the value exceeds the 128-bit limit, it falls back to using big.Int.
type bint struct {
// fall back, in case the value is our of u128 range
bigInt *big.Int
// Stores small numbers with high performance and zero allocation operations.
// The value range is 0 <= u128 <= 2^128 - 1
u128 u128
}
func (u *bint) overflow() bool {
return u.bigInt != nil
}
func bintFromBigInt(b *big.Int) bint {
return bint{bigInt: b}
}
func bintFromU128(u u128) bint {
return bint{u128: u}
}
func bintFromU64(u uint64) bint {
return bint{u128: u128{lo: u}}
}
func (u bint) GetBig() *big.Int {
if u.overflow() {
return new(big.Int).Set(u.bigInt)
}
return u.u128.ToBigInt()
}
func (u bint) IsZero() bool {
if !u.overflow() {
return u.u128.IsZero()
}
return u.bigInt.Cmp(bigZero) == 0
}
func (u bint) Cmp(v bint) int {
if !u.overflow() && !v.overflow() {
return u.u128.Cmp(v.u128)
}
return u.GetBig().Cmp(v.GetBig())
}
func errInvalidFormat(s []byte) error {
return fmt.Errorf("%w: can't parse '%s' to Decimal", ErrInvalidFormat, s)
}
func parseBint(s []byte) (bool, bint, uint8, error) {
if len(s) == 0 {
return false, bint{}, 0, ErrEmptyString
}
if len(s) > maxStrLen {
return false, bint{}, 0, ErrMaxStrLen
}
// if s has less than 41 characters, it can fit into u128
// 41 chars = maxLen(u128) + dot + sign = 39 + 1 + 1
if len(s) <= 41 {
neg, bint, prec, err := parseBintFromU128(s)
if err == nil || err != errOverflow {
return neg, bint, prec, err
}
// overflow, try to parse into big.Int
}
// parse into big.Int
var (
width = len(s)
intString string
prec, pos int
neg bool
value = s
)
switch s[0] {
case '.':
return false, bint{}, 0, errInvalidFormat(s)
case '-':
neg = true
value = s[1:]
pos++
case '+':
pos++
default:
// do nothing
}
// prevent "+" or "-"
if pos == width {
return false, bint{}, 0, errInvalidFormat(s)
}
// prevent "-.123" or "+.123"
if s[pos] == '.' {
return false, bint{}, 0, errInvalidFormat(s)
}
pIndex := -1
vLen := len(value)
for i := 0; i < vLen; i++ {
if value[i] == '.' {
if pIndex > -1 {
// input has more than 1 decimal point
return false, bint{}, 0, errInvalidFormat(s)
}
pIndex = i
}
}
switch {
case pIndex == -1:
// There is no decimal point, we can just parse the original string as an int
intString = string(value)
case pIndex >= vLen-1:
// prevent "123." or "-123."
return false, bint{}, 0, errInvalidFormat(s)
default:
b := strings.Builder{}
_, err := b.Write(value[:pIndex])
if err != nil {
return false, bint{}, 0, err
}
_, err = b.Write(value[pIndex+1:])
if err != nil {
return false, bint{}, 0, err
}
// intString = value[:pIndex] + value[pIndex+1:]
intString = b.String()
prec = len(value[pIndex+1:])
}
if prec > int(defaultPrec) {
return false, bint{}, 0, ErrPrecOutOfRange
}
dValue := new(big.Int)
_, ok := dValue.SetString(intString, 10)
if !ok {
return false, bint{}, 0, errInvalidFormat(s)
}
// the value should always be positive, as we already extracted the sign
if dValue.Sign() == -1 {
return false, bint{}, 0, errInvalidFormat(s)
}
//nolint:gosec // prec <= maxPrec (19) and can be safely converted to uint8
return neg, bintFromBigInt(dValue), uint8(prec), nil
}
func parseBintFromU128(s []byte) (bool, bint, uint8, error) {
width := len(s)
var (
pos int
neg bool
)
switch s[0] {
case '.':
return false, bint{}, 0, errInvalidFormat(s)
case '-':
neg = true
pos++
case '+':
pos++
default:
// do nothing
}
// prevent "+" or "-"
if pos == width {
return false, bint{}, 0, errInvalidFormat(s)
}
// prevent "-.123" or "+.123"
if s[pos] == '.' {
return false, bint{}, 0, errInvalidFormat(s)
}
var (
err error
coef u128
prec uint8
)
if len(s[pos:]) <= maxDigitU64 {
coef, prec, err = parseSmallToU128(s[pos:])
} else {
coef, prec, err = parseLargeToU128(s[pos:])
}
if err == ErrInvalidFormat {
return neg, bint{}, 0, errInvalidFormat(s)
}
return neg, bint{u128: coef}, prec, err
}
func parseSmallToU128(s []byte) (u128, uint8, error) {
var (
coef uint64
prec uint8
)
for i := 0; i < len(s); i++ {
if s[i] == '.' {
// return err if we encounter the '.' more than once
if prec != 0 {
return u128{}, 0, ErrInvalidFormat
}
//nolint:gosec // len(s) <= maxDigitU64 and len(s)-i-1 >= 0, can be safely converted to uint8
prec = uint8(len(s) - i - 1)
// prevent "123." or "-123."
if prec == 0 {
return u128{}, 0, ErrInvalidFormat
}
if prec > defaultPrec {
return u128{}, 0, ErrPrecOutOfRange
}
continue
}
if s[i] < '0' || s[i] > '9' {
return u128{}, 0, ErrInvalidFormat
}
coef = coef*10 + uint64(s[i]-'0')
}
if coef == 0 {
return u128{}, 0, nil
}
return u128{lo: coef}, prec, nil
}
func parseLargeToU128(s []byte) (u128, uint8, error) {
// find '.' position
l := len(s)
pos := bytes.IndexByte(s, '.')
if pos == 0 || pos == l-1 {
// prevent ".123" or "123."
return u128{}, 0, ErrInvalidFormat
}
if pos == -1 {
// no decimal point
coef, err := digitToU128(s)
if err != nil {
return u128{}, 0, err
}
return coef, 0, nil
}
// now 0 < pos < l-1
//nolint:gosec // l < maxStrLen, so 0 < l-pos-1 < 256, can be safely converted to uint8
prec := uint8(l - pos - 1)
if prec > defaultPrec {
return u128{}, 0, ErrPrecOutOfRange
}
// number has a decimal point, split into 2 parts: integer and fraction
intPart, err := digitToU128(s[:pos])
if err != nil {
return u128{}, 0, err
}
// because max prec is 19,
// factionPart can't be larger than 10^19-1 and will fit into uint64 (fractionPart.hi == 0)
fractionPart, err := digitToU128(s[pos+1:])
if err != nil {
return u128{}, 0, err
}
// combine
coef, err := intPart.Mul64(pow10[uint64(prec)].lo)
if err != nil {
return u128{}, 0, err
}
coef, err = coef.Add64(fractionPart.lo)
if err != nil {
return u128{}, 0, err
}
return coef, prec, nil
}
func digitToU128(s []byte) (u128, error) {
if len(s) <= maxDigitU64 {
var u uint64
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return u128{}, ErrInvalidFormat
}
u = u*10 + uint64(s[i]-'0')
}
return u128{lo: u}, nil
}
// number is too large
var (
u u128
err error
)
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return u128{}, ErrInvalidFormat
}
u, err = u.Mul64(10)
if err != nil {
return u128{}, err
}
u, err = u.Add64(uint64(s[i] - '0'))
if err != nil {
return u128{}, err
}
}
return u, nil
}
// GT returns true if u > v
func (u bint) GT(v bint) bool {
return u.Cmp(v) == 1
}
func (u bint) Add(v bint) bint {
if !u.overflow() && !v.overflow() {
c, err := u.u128.Add(v.u128)
if err == nil {
return bint{u128: c}
}
// overflow, fallback to big.Int
}
return bintFromBigInt(new(big.Int).Add(u.GetBig(), v.GetBig()))
}
func (u bint) Sub(v bint) (bint, error) {
if !u.overflow() && !v.overflow() {
c, err := u.u128.Sub(v.u128)
if err == nil {
return bint{u128: c}, nil
}
}
uBig := u.GetBig()
vBig := v.GetBig()
// make sure the result is always positive
if uBig.Cmp(vBig) < 0 {
return bint{}, errOverflow
}
return bintFromBigInt(new(big.Int).Sub(uBig, vBig)), nil
}
func (u bint) Mul(v bint) bint {
if !u.overflow() && !v.overflow() {
c, err := u.u128.Mul(v.u128)
if err == nil {
return bint{u128: c}
}
}
return bintFromBigInt(new(big.Int).Mul(u.GetBig(), v.GetBig()))
}