-
Notifications
You must be signed in to change notification settings - Fork 62
/
big.go
1818 lines (1639 loc) · 40.3 KB
/
big.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package decimal
import (
"bytes"
"encoding"
"encoding/json"
"fmt"
"io"
"math"
"math/big"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/ericlagergren/decimal/internal/arith"
"github.com/ericlagergren/decimal/internal/c"
)
const (
// Radix is the base in which decimal arithmetic is
// performed.
Radix = 10
// IsCanonical is true since Big decimals are always
// normalized.
IsCanonical = true
)
// Big is a floating-point, arbitrary-precision
//
// It is represented as a number and a scale. A scale greater
// than zero indicates the number of decimal digits after the
// radix. Otherwise, the number is multiplied by 10 to the power
// of the negation of the scale. More formally,
//
// Big = number × 10**-scale
//
// with MinScale <= scale <= MaxScale. A Big may also be ±0,
// ±Infinity, or ±NaN (either quiet or signaling). Non-NaN Big
// values are ordered, defined as the result of x.Cmp(y).
//
// Additionally, each Big value has a contextual object which
// governs arithmetic operations.
type Big struct {
// Context is the decimal's unique contextual object.
Context Context
// unscaled is only used if the decimal is too large to fit
// in compact.
unscaled big.Int
// compact is use if the value fits into an uint64. The scale
// does not affect whether this field is used. If a decimal
// has 20 or fewer digits, this field will be used.
compact uint64
// exp is the negated scale, meaning
//
// number × 10**exp = number × 10**-scale
//
exp int
// precision is the current precision.
precision int
// form indicates whether a decimal is a finite number, an
// infinity, or a NaN value and whether it's signed or not.
form form
}
var (
_ fmt.Formatter = (*Big)(nil)
_ fmt.Scanner = (*Big)(nil)
_ fmt.Stringer = (*Big)(nil)
_ json.Unmarshaler = (*Big)(nil)
_ encoding.TextUnmarshaler = (*Big)(nil)
_ decomposer = (*Big)(nil)
)
// form indicates whether a decimal is a finite number, an
// infinity, or a nan value and whether it's signed or not.
type form uint8
const (
// Particular bits:
//
// 0: sign bit
// 1: infinity
// 2: signaling nan
// 3: quiet nan
// 4-7: unused
finite form = 0 // default, all zeros; do not re-order this constant.
signbit form = 1 << 0 // do not assign this; used to check for signedness.
pinf form = 1 << 1 // may compare with ==, &, etc.
ninf form = pinf | signbit // may compare with ==, &, etc.
inf form = pinf // do not assign this; used to check for either infinity.
snan form = 1 << 2 // compare with bitwise & only due to ssnan
qnan form = 1 << 3 // compare with bitwise & only due to sqnan
ssnan form = snan | signbit // primarily for printing, signbit
sqnan form = qnan | signbit // primarily for printing, signbit
nan form = snan | qnan // do not assign this; used to check for either NaN.
special = inf | nan // do not assign this; used to check for a special value.
)
func (f form) String() string {
// GDA versions. Go needs to be handled manually.
switch f {
case finite:
return "finite"
case finite | signbit:
return "-finite"
case snan:
return "sNaN"
case snan | signbit:
return "-sNaN"
case qnan:
return "NaN"
case qnan | signbit:
return "-NaN"
case pinf:
return "Infinity"
case ninf:
return "-Infinity"
default:
return fmt.Sprintf("unknown form: %0.8b", f)
}
}
// Payload is a NaN value's payload.
type Payload uint64
//go:generate stringer -type Payload -linecomment
const (
absvalue Payload = iota + 1 // absolute value of NaN
acos // acos with NaN as an operand
addinfinf // addition of infinities with opposing signs
addition // addition with NaN as an operand
asin // asin with NaN as an operand
atan // atan with NaN as an operand
atan2 // atan2 with NaN as an operand
comparison // comparison with NaN as an operand
cos // cos with NaN as an operand
division // division with NaN as an operand
exp // exp with NaN as an operand
invctxomode // operation with an invalid OperatingMode
invctxpgtu // operation with a precision greater than MaxPrecision
invctxpltz // operation with a precision less than zero
invctxrmode // operation with an invalid RoundingMode
invctxsgtu // operation with a scale greater than MaxScale
invctxsltu // operation with a scale lesser than MinScale
log // log with NaN as an operand
log10 // log10 with NaN as an operand
mul0inf // multiplication of zero with infinity
multiplication // multiplication with NaN as an operand
negation // negation with NaN as an operand
nextminus // next-minus with NaN as an operand
nextplus // next-plus with NaN as an operand
quantinf // quantization of an infinity
quantization // quantization with NaN as an operand
quantminmax // quantization exceeds minimum or maximum scale
quantprec // quantization exceeds working precision
quo00 // division of zero by zero
quoinfinf // division of infinity by infinity
quointprec // result of integer division was larger than the desired precision
quorem_ // integer division or remainder has too many digits
quotermexp // division with unlimited precision has a non-terminating decimal expansion
reduction // reduction with NaN as an operand
reminfy // remainder of infinity
remprec // result of remainder operation was larger than the desired precision
remx0 // remainder by zero
sin // sin with NaN as an operand
subinfinf // subtraction of infinities with opposing signs
subtraction // subtraction with NaN as an operand
)
// An ErrNaN is used when a decimal operation would lead to a NaN under IEEE-754
// rules. An ErrNaN implements the error interface.
type ErrNaN struct {
Msg string
}
func (e ErrNaN) Error() string {
return e.Msg
}
var _ error = ErrNaN{}
// Canonical sets z to the canonical form of z.
//
// Since Big values are always canonical, it's identical to Copy.
func (z *Big) Canonical(x *Big) *Big {
return z.Copy(x)
}
// CheckNaNs checks if either x or y is NaN.
//
// If so, it follows the rules of NaN handling set forth in the
// GDA specification. The argument y may be nil. It reports
// whether either condition is a NaN.
func (z *Big) CheckNaNs(x, y *Big) bool {
return z.invalidContext(z.Context) || z.checkNaNs(x, y, 0)
}
func (z *Big) checkNaNs(x, y *Big, op Payload) bool {
var yform form
if y != nil {
yform = y.form
}
f := (x.form | yform) & nan
if f == 0 {
return false
}
form := qnan
var cond Condition
if f&snan != 0 {
cond = InvalidOperation
if x.form&snan != 0 {
form |= (x.form & signbit)
} else {
form |= (y.form & signbit)
}
} else if x.form&nan != 0 {
form |= (x.form & signbit)
} else {
form |= (y.form & signbit)
}
z.setNaN(cond, form, op)
return true
}
func (z *Big) xflow(exp int, over, neg bool) *Big {
// over == overflow
// neg == intermediate result < 0
if over {
// TODO(eric): actually choose the largest finite number in the current
// precision. This is legacy now.
//
// NOTE(eric): in some situations, the decimal library tells us to set
// z to "the largest finite number that can be represented in the
// current precision..." Use signed Infinity instead.
//
// Because of the logic above, every rounding mode works out to the
// following.
if neg {
z.form = ninf
} else {
z.form = pinf
}
z.Context.Conditions |= Overflow | Inexact | Rounded
return z
}
var sign form
if neg {
sign = signbit
}
z.setZero(sign, exp)
z.Context.Conditions |= Underflow | Inexact | Rounded | Subnormal
return z
}
// These methods are here to prevent typos.
func (x *Big) isCompact() bool { return x.compact != c.Inflated }
func (x *Big) isInflated() bool { return !x.isCompact() }
func (x *Big) isSpecial() bool { return x.form&special != 0 }
// isZero reports whether x is zero.
//
// Only use after checking for specials.
func (x *Big) isZero() bool {
if debug {
if x.isSpecial() {
panic("isZero called on a special value")
}
}
return x.compact == 0
}
// adjusted returns the adjusted exponent.
//
// The adjusted exponent is the exponent of x when expressed in
// scientific notation with one digit before the radix.
func (x *Big) adjusted() int {
return (x.exp + x.Precision()) - 1
}
// etiny returns the minimum exponent of a subnormal result.
func (c Context) etiny() int {
return c.emin() - (c.precision() - 1)
}
// etop returns the maximum exponent of an overflow result.
func (c Context) etop() int {
return c.emax() - (c.precision() - 1)
}
// Abs sets z to the absolute value of x and returns z.
func (z *Big) Abs(x *Big) *Big {
return z.Context.Abs(z, x)
}
// Add sets z to x + y and returns z.
func (z *Big) Add(x, y *Big) *Big {
return z.Context.Add(z, x, y)
}
// Class returns the "class" of x, which is one of the following:
//
// sNaN
// NaN
// -Infinity
// -Normal
// -Subnormal
// -Zero
// +Zero
// +Subnormal
// +Normal
// +Infinity
//
func (x *Big) Class() string {
if x.IsNaN(0) {
if x.IsNaN(+1) {
return "NaN"
}
return "sNaN"
}
if x.Signbit() {
if x.IsInf(0) {
return "-Infinity"
}
if x.isZero() {
return "-Zero"
}
if x.IsSubnormal() {
return "-Subnormal"
}
return "-Normal"
}
if x.IsInf(0) {
return "+Infinity"
}
if x.isZero() {
return "+Zero"
}
if x.IsSubnormal() {
return "+Subnormal"
}
return "+Normal"
}
// Cmp compares x and y and returns:
//
// -1 if x < y
// 0 if x == y
// +1 if x > y
//
// It does not modify x or y. The result is undefined if either
// x or y are NaN.
//
// For an abstract comparison with NaN values, see CmpTotal.
func (x *Big) Cmp(y *Big) int {
if debug {
x.validate()
y.validate()
}
return cmp(x, y, false)
}
// CmpAbs compares |x| and |y| and returns:
//
// -1 if |x| < |y|
// 0 if |x| == |y|
// +1 if |x| > |y|
//
// It does not modify x or y. The result is undefined if either
// x or y are NaN.
//
// For an abstract comparison with NaN values, see
// CmpTotalAbs.
func (x *Big) CmpAbs(y *Big) int {
if debug {
x.validate()
y.validate()
}
return cmp(x, y, true)
}
func cmpInt(x *Big, y int64) int {
switch {
case x.Signbit() && y >= 0:
return -1
case !x.Signbit() && y < 0:
return +1
default:
return cmpAbsInt(x, y)
}
}
func cmpAbsInt(x *Big, y int64) int {
u := uint64(y)
// Same scales, so compare straight across.
if x.exp == 0 {
// If the scales are the same and x x is not compact,
// then by definition it's larger than y.
if !x.isCompact() {
return +1
}
return arith.Cmp(x.compact, u)
}
// Signs are the same and the scales differ. Compare the
// lengths of their integral parts; if they differ in length
// one number is larger.
// E.g.: 1234.01
// 1230011
xl := x.adjusted()
yl := arith.Length(u) - 1
if xl != yl {
if xl < yl {
return -1
}
return +1
}
// The length of the integral parts match. Rescale x, then
// compare straight across.
t, ok := scalex(x.compact, x.exp)
if !ok {
if x.exp > 0 {
// Overflow.
return +1
}
// Underflow.
return -1
}
return arith.Cmp(t, u)
}
// cmp is the implementation for both Cmp and CmpAbs.
func cmp(x, y *Big, abs bool) int {
if x == y {
return 0
}
// NaN cmp x
// z cmp NaN
// NaN cmp NaN
if (x.form|y.form)&nan != 0 {
return 0
}
// Fast path: Catches non-finite forms like zero and ±Inf,
// possibly signed.
xs := x.ord(abs)
ys := y.ord(abs)
if xs != ys {
if xs > ys {
return +1
}
return -1
}
switch xs {
case 0, +2, -2:
return 0
default:
r := cmpabs(x, y)
if xs < 0 && !abs {
r = -r
}
return r
}
}
// ord returns similar to Sign except -Inf is -2 and +Inf is +2.
func (x *Big) ord(abs bool) int {
if x.form&inf != 0 {
if x.form == pinf || abs {
return +2
}
return -2
}
r := x.Sign()
if abs && r < 0 {
r = -r
}
return r
}
func cmpabs(x, y *Big) int {
// Same scales means we can compare straight across.
if x.exp == y.exp {
if x.isCompact() {
if y.isCompact() {
return arith.Cmp(x.compact, y.compact)
}
return -1 // y.isInflateed
}
if y.isCompact() {
return +1 // !x.isCompact
}
return x.unscaled.CmpAbs(&y.unscaled)
}
// Signs are the same and the scales differ. Compare the
// lengths of their integral parts; if they differ in length
// one number is larger.
// E.g.: 1234.01
// 123.011
xl := x.adjusted()
yl := y.adjusted()
if xl != yl {
if xl < yl {
return -1
}
return +1
}
diff := int64(x.exp) - int64(y.exp)
shift := uint64(arith.Abs(diff))
if arith.Safe(shift) && x.isCompact() && y.isCompact() {
p, _ := arith.Pow10(shift)
if diff < 0 {
return arith.CmpShift(x.compact, y.compact, p)
}
return -arith.CmpShift(y.compact, x.compact, p)
}
xw, yw := x.unscaled.Bits(), y.unscaled.Bits()
if x.isCompact() {
xw = arith.Words(x.compact)
}
if y.isCompact() {
yw = arith.Words(y.compact)
}
var tmp big.Int
if diff < 0 {
yw = arith.MulBigPow10(&tmp, tmp.SetBits(copybits(yw)), shift).Bits()
} else {
xw = arith.MulBigPow10(&tmp, tmp.SetBits(copybits(xw)), shift).Bits()
}
return arith.CmpBits(xw, yw)
}
// CmpTotal compares x and y in a manner similar to the Big.Cmp,
// but allows ordering of all abstract representations.
//
// In particular, this means NaN values have a defined ordering.
// From lowest to highest the ordering is:
//
// -NaN
// -sNaN
// -Infinity
// -127
// -1.00
// -1
// -0.000
// -0
// +0
// +1.2300
// +1.23
// +1E+9
// +Infinity
// +sNaN
// +NaN
//
func (x *Big) CmpTotal(y *Big) int {
if debug {
x.validate()
y.validate()
}
xs := x.ordTotal(false)
ys := y.ordTotal(false)
if xs != ys {
if xs > ys {
return +1
}
return -1
}
if xs != 0 {
return 0
}
return x.Cmp(y)
}
// CmpTotalAbs is like CmpTotal but instead compares the absolute
// values of x and y.
func (x *Big) CmpTotalAbs(y *Big) int {
if debug {
x.validate()
y.validate()
}
xs := x.ordTotal(true)
ys := y.ordTotal(true)
if xs != ys {
if xs > ys {
return +1
}
return -1
}
if xs != 0 {
return 0
}
return x.CmpAbs(y)
}
func (x *Big) ordTotal(abs bool) (r int) {
// -2 == -qnan
// -1 == -snan
// 0 == not nan
// +1 == snan
// +2 == qnan
if x.IsNaN(0) {
if x.IsNaN(+1) { // qnan
r = +2
} else {
r = +1
}
if !abs && x.Signbit() {
r = -r
}
}
return r
}
// Copy sets z to a copy of x and returns z.
func (z *Big) Copy(x *Big) *Big {
if debug {
x.validate()
}
if z != x {
sign := x.form & signbit
z.copyAbs(x)
z.form |= sign
}
return z
}
// copyAbs sets z to a copy of |x| and returns z.
func (z *Big) copyAbs(x *Big) *Big {
if z != x {
z.precision = x.Precision()
z.exp = x.exp
z.compact = x.compact
if x.IsFinite() && x.isInflated() {
z.unscaled.Set(&x.unscaled)
}
}
z.form = x.form & ^signbit
return z
}
// CopyAbs is like Abs, but no flags are changed and the result
// is not rounded.
func (z *Big) CopyAbs(x *Big) *Big {
if debug {
x.validate()
}
return z.copyAbs(x)
}
// CopyNeg is like Neg, but no flags are changed and the result
// is not rounded.
func (z *Big) CopyNeg(x *Big) *Big {
if debug {
x.validate()
}
xform := x.form // in case z == x
z.copyAbs(x)
z.form = xform ^ signbit
return z
}
// CopySign sets z to x with the sign of y and returns z.
//
// It accepts NaN values.
func (z *Big) CopySign(x, y *Big) *Big {
if debug {
x.validate()
y.validate()
}
// Pre-emptively capture signbit in case z == y.
sign := y.form & signbit
z.copyAbs(x)
z.form |= sign
return z
}
// Float64 returns x as a float64 and a bool indicating whether
// x can fit into a float64 without truncation, overflow, or
// underflow.
//
// Special values are considered exact; however, special values
// that occur because the magnitude of x is too large to be
// represented as a float64 are not.
func (x *Big) Float64() (f float64, ok bool) {
if debug {
x.validate()
}
if !x.IsFinite() {
switch x.form {
case pinf, ninf:
return math.Inf(int(x.form & signbit)), true
case snan, qnan:
return math.NaN(), true
case ssnan, sqnan:
return math.Copysign(math.NaN(), -1), true
}
}
const (
maxMantissa = 1<<53 + 1 // largest exact mantissa
)
parse := false
switch xc := x.compact; {
case !x.isCompact():
parse = true
case x.isZero():
f = 0
ok = true
case x.exp == 0:
f = float64(xc)
ok = xc < maxMantissa || (xc&(xc-1)) == 0
case x.exp > 0:
f = float64(x.compact) * math.Pow10(x.exp)
ok = x.compact < maxMantissa && !math.IsInf(f, 0) && !math.IsNaN(f)
case x.exp < 0:
f = float64(x.compact) / math.Pow10(-x.exp)
ok = x.compact < maxMantissa && !math.IsInf(f, 0) && !math.IsNaN(f)
default:
parse = true
}
if parse {
f, _ = strconv.ParseFloat(x.String(), 64)
ok = !math.IsInf(f, 0) && !math.IsNaN(f)
}
if x.form&signbit != 0 {
f = math.Copysign(f, -1)
}
return f, ok
}
// Float sets z, which may be nil, to x and returns z.
//
// The result is undefined if z is a NaN value.
func (x *Big) Float(z *big.Float) *big.Float {
if debug {
x.validate()
}
if z == nil {
z = new(big.Float)
}
switch x.form {
case finite, finite | signbit:
if x.isZero() {
z.SetUint64(0)
} else {
z.SetRat(x.Rat(nil))
}
case pinf, ninf:
z.SetInf(x.form == pinf)
default: // snan, qnan, ssnan, sqnan:
z.SetUint64(0)
}
return z
}
// Format implements the fmt.Formatter interface.
//
// The following verbs are supported:
//
// %s: -dddd.dd or -d.dddd±edd, depending on x
// %d: same as %s
// %v: same as %s
// %e: -d.dddd±edd
// %E: -d.dddd±Edd
// %f: -dddd.dd
// %g: same as %f
//
// While width is honored in the same manner as the fmt package (the minimum
// width of the formatted number), precision is the number of significant digits
// in the decimal number. Given %f, however, precision is the number of digits
// following the radix.
//
// Format honors all flags (such as '+' and ' ') in the same manner as the fmt
// package, except for '#'. Unless used in conjunction with %v, %q, or %p, the
// '#' flag will be ignored; decimals have no defined hexadeximal or octal
// representation.
//
// %+v, %#v, %T, %#p, and %p all honor the formats specified in the fmt
// package's documentation.
func (x *Big) Format(s fmt.State, c rune) {
if debug {
x.validate()
}
prec, hasPrec := s.Precision()
if !hasPrec {
prec = x.Precision()
}
width, hasWidth := s.Width()
if !hasWidth {
width = noWidth
}
var (
hash = s.Flag('#')
dash = s.Flag('-')
lpZero = s.Flag('0')
lpSpace = width != noWidth && !dash && !lpZero
plus = s.Flag('+')
space = s.Flag(' ')
f = formatter{prec: prec, width: width}
e = sciE[x.Context.OperatingMode]
)
// If we need to left pad then we need to first write our
// string into an
// empty buffer.
tmpbuf := lpZero || lpSpace
if tmpbuf {
b := new(strings.Builder)
b.Grow(x.Precision())
f.w = b
} else {
f.w = stateWrapper{s}
}
if plus {
f.sign = '+'
} else if space {
f.sign = ' '
}
// noE is a placeholder for formats that do not use scientific notation
// and don't require 'e' or 'E'
const noE = 0
switch c {
case 's', 'd':
f.format(x, normal, e)
case 'q':
// The fmt package's docs specify that the '+' flag
// "guarantee[s] ASCII-only output for %q (%+q)"
f.sign = 0
// Since no other escaping is needed we can do it ourselves and save
// whatever overhead running it through fmt.Fprintf would incur.
quote := byte('"')
if hash {
quote = '`'
}
f.WriteByte(quote)
f.format(x, normal, e)
f.WriteByte(quote)
case 'e', 'E':
f.format(x, sci, byte(c))
case 'f', 'F':
if !hasPrec {
prec = 0
} else {
// %f's precision means "number of digits after the radix"
if x.exp > 0 {
f.prec += (x.exp + x.Precision())
} else {
if adj := x.exp + x.Precision(); adj > -f.prec {
f.prec += adj
} else {
f.prec = -f.prec
}
}
}
f.format(x, plain, noE)
case 'g', 'G':
// %g's precision means "number of significant digits"
f.format(x, plain, noE)
// Make sure we return from the following two cases.
case 'v':
// %v == %s
if !hash && !plus {
f.format(x, normal, e)
break
}
// This is the easiest way of doing it. Note we can't use type Big Big,
// even though it's declared inside a function. Go thinks it's recursive.
// At least the fields are checked at compile time.
type Big struct {
Context Context
unscaled big.Int
compact uint64
exp int
precision int
form form
}
specs := ""
if dash {
specs += "-"
} else if lpZero {
specs += "0"
}
if hash {
specs += "#"
} else if plus {
specs += "+"
} else if space {
specs += " "
}
fmt.Fprintf(s, "%"+specs+"v", (*Big)(x))
return
default:
fmt.Fprintf(s, "%%!%c(*Big=%s)", c, x.String())
return
}
// Need padding out to width.
if f.n < int64(width) {
switch pad := int64(width) - f.n; {
case dash:
io.CopyN(s, spaceReader{}, pad)
case lpZero:
io.CopyN(s, zeroReader{}, pad)
case lpSpace:
io.CopyN(s, spaceReader{}, pad)
}
}
if tmpbuf {
// fmt's internal state type implements stringWriter I think.
io.WriteString(s, f.w.(*strings.Builder).String())
}
}
// FMA sets z to (x * y) + u without any intermediate rounding.
func (z *Big) FMA(x, y, u *Big) *Big {
return z.Context.FMA(z, x, y, u)
}
// Int sets z, which may be nil, to x, truncating the fractional
// portion (if any) and returns z.
//
// If x is an infinity or a NaN value the result is undefined.
func (x *Big) Int(z *big.Int) *big.Int {
if debug {
x.validate()
}
if z == nil {
z = new(big.Int)
}
if !x.IsFinite() {
return z
}
if x.isCompact() {
z.SetUint64(x.compact)
} else {
z.Set(&x.unscaled)
}
if x.Signbit() {
z.Neg(z)
}
if x.exp == 0 {
return z
}
return bigScalex(z, z, x.exp)
}
// Int64 returns x as an int64, truncating towards zero.
//
// The bool result indicates whether the conversion to an int64
// was successful.
func (x *Big) Int64() (int64, bool) {
if debug {
x.validate()
}
if !x.IsFinite() {
return 0, false
}