forked from jruby/jruby
/
RubyBigDecimal.java
2178 lines (1865 loc) · 80.6 KB
/
RubyBigDecimal.java
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
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2009 Joseph LaFata <joe@quibb.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.bigdecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jruby.CompatVersion;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyInteger;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyRational;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.Numeric;
import org.jruby.util.SafeDoubleParser;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
@JRubyClass(name="BigDecimal", parent="Numeric")
public class RubyBigDecimal extends RubyNumeric {
private static final ObjectAllocator BIGDECIMAL_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyBigDecimal(runtime, klass);
}
};
@JRubyConstant
public final static int ROUND_DOWN = BigDecimal.ROUND_DOWN;
@JRubyConstant
public final static int ROUND_CEILING = BigDecimal.ROUND_CEILING;
@JRubyConstant
public final static int ROUND_UP = BigDecimal.ROUND_UP;
@JRubyConstant
public final static int ROUND_HALF_DOWN = BigDecimal.ROUND_HALF_DOWN;
@JRubyConstant
public final static int ROUND_HALF_EVEN = BigDecimal.ROUND_HALF_EVEN;
@JRubyConstant
public final static int ROUND_HALF_UP = BigDecimal.ROUND_HALF_UP;
@JRubyConstant
public final static int ROUND_FLOOR = BigDecimal.ROUND_FLOOR;
@JRubyConstant
public final static int SIGN_POSITIVE_INFINITE = 3;
@JRubyConstant
public final static int EXCEPTION_OVERFLOW = 8;
@JRubyConstant
public final static int SIGN_POSITIVE_ZERO = 1;
@JRubyConstant
public final static int EXCEPTION_ALL = 255;
@JRubyConstant
public final static int SIGN_NEGATIVE_FINITE = -2;
@JRubyConstant
public final static int EXCEPTION_UNDERFLOW = 4;
@JRubyConstant
public final static int SIGN_NaN = 0;
@JRubyConstant
public final static int BASE = 10000;
@JRubyConstant
public final static int ROUND_MODE = 256;
@JRubyConstant
public final static int SIGN_POSITIVE_FINITE = 2;
@JRubyConstant
public final static int EXCEPTION_INFINITY = 1;
@JRubyConstant
public final static int SIGN_NEGATIVE_INFINITE = -3;
@JRubyConstant
public final static int EXCEPTION_ZERODIVIDE = 1;
@JRubyConstant
public final static int SIGN_NEGATIVE_ZERO = -1;
@JRubyConstant
public final static int EXCEPTION_NaN = 2;
// Static constants
private static final BigDecimal TWO = new BigDecimal(2);
private static final double SQRT_10 = 3.162277660168379332;
public static RubyClass createBigDecimal(Ruby runtime) {
RubyClass bigDecimal = runtime.defineClass("BigDecimal", runtime.getNumeric(), BIGDECIMAL_ALLOCATOR);
runtime.getKernel().defineAnnotatedMethods(BigDecimalKernelMethods.class);
bigDecimal.setInternalModuleVariable("vpPrecLimit", RubyFixnum.zero(runtime));
bigDecimal.setInternalModuleVariable("vpExceptionMode", RubyFixnum.zero(runtime));
bigDecimal.setInternalModuleVariable("vpRoundingMode", runtime.newFixnum(ROUND_HALF_UP));
bigDecimal.defineAnnotatedMethods(RubyBigDecimal.class);
bigDecimal.defineAnnotatedConstants(RubyBigDecimal.class);
if (runtime.is1_9()) {
RubyModule bigMath = runtime.defineModule("BigMath");
// TODO: BigMath.exp and BigMath.pow in native code
bigDecimal.defineConstant("NAN", newNaN(runtime));
bigDecimal.defineConstant("INFINITY", newInfinity(runtime, 1));
}
return bigDecimal;
}
private final boolean isNaN;
private final int infinitySign;
private final int zeroSign;
private BigDecimal value;
public BigDecimal getValue() {
return value;
}
public RubyBigDecimal(Ruby runtime, RubyClass klass) {
super(runtime, klass);
this.isNaN = false;
this.infinitySign = 0;
this.zeroSign = 0;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value) {
super(runtime, runtime.getClass("BigDecimal"));
this.isNaN = false;
this.infinitySign = 0;
this.zeroSign = 0;
this.value = value;
}
public RubyBigDecimal(Ruby runtime, RubyClass klass, BigDecimal value) {
super(runtime, klass);
this.isNaN = false;
this.infinitySign = 0;
this.zeroSign = 0;
this.value = value;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value, int infinitySign) {
super(runtime, runtime.getClass("BigDecimal"));
this.isNaN = false;
this.infinitySign = infinitySign;
this.zeroSign = 0;
this.value = value;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value, int infinitySign, int zeroSign) {
super(runtime, runtime.getClass("BigDecimal"));
this.isNaN = false;
this.infinitySign = infinitySign;
this.zeroSign = zeroSign;
this.value = value;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value, boolean isNan) {
super(runtime, runtime.getClass("BigDecimal"));
this.isNaN = isNan;
this.infinitySign = 0;
this.zeroSign = 0;
this.value = value;
}
public RubyBigDecimal(Ruby runtime, RubyBigDecimal rbd) {
this(runtime, runtime.getClass("BigDecimal"), rbd);
}
public RubyBigDecimal(Ruby runtime, RubyClass klass, RubyBigDecimal rbd) {
super(runtime, klass);
this.isNaN = rbd.isNaN;
this.infinitySign = rbd.infinitySign;
this.zeroSign = rbd.zeroSign;
this.value = rbd.value;
}
public static class BigDecimalKernelMethods {
@JRubyMethod(name = "BigDecimal", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject newBigDecimal(IRubyObject recv, IRubyObject[] args) {
return RubyBigDecimal.newBigDecimal(recv, args, Block.NULL_BLOCK);
}
}
public static RubyBigDecimal newBigDecimal(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return newInstance(recv.getRuntime().getClass("BigDecimal"), args);
}
@JRubyMethod(name = "ver", meta = true)
public static IRubyObject ver(IRubyObject recv) {
return recv.getRuntime().newString("1.0.1");
}
@JRubyMethod(name = "_dump", optional = 1)
public IRubyObject dump(IRubyObject[] args, Block unusedBlock) {
RubyString precision = RubyString.newUnicodeString(getRuntime(), "0:");
return precision.append(asString());
}
@JRubyMethod(name = "_load", required = 1, meta = true)
public static RubyBigDecimal load(IRubyObject recv, IRubyObject from, Block block) {
RubyBigDecimal rubyBigDecimal = (RubyBigDecimal) (((RubyClass)recv).allocate());
String precisionAndValue = from.convertToString().asJavaString();
String value = precisionAndValue.substring(precisionAndValue.indexOf(":")+1);
rubyBigDecimal.value = new BigDecimal(value);
return rubyBigDecimal;
}
@JRubyMethod(name = "double_fig", meta = true)
public static IRubyObject double_fig(IRubyObject recv) {
return recv.getRuntime().newFixnum(20);
}
@JRubyMethod(name = "limit", optional = 1, meta = true)
public static IRubyObject limit(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
RubyModule c = (RubyModule)recv;
IRubyObject nCur = c.searchInternalModuleVariable("vpPrecLimit");
if (args.length > 0) {
IRubyObject arg = args[0];
if (!arg.isNil()) {
if (!(arg instanceof RubyFixnum)) {
throw runtime.newTypeError(arg, runtime.getFixnum());
}
if (0 > ((RubyFixnum)arg).getLongValue()) {
throw runtime.newArgumentError("argument must be positive");
}
c.setInternalModuleVariable("vpPrecLimit", arg);
}
}
return nCur;
}
@JRubyMethod(name = "save_limit", meta = true)
public static IRubyObject save_limit(ThreadContext context, IRubyObject recv, Block block) {
RubyModule c = (RubyModule)recv;
IRubyObject nCur = c.searchInternalModuleVariable("vpPrecLimit");
IRubyObject ret;
try {
ret = block.yieldSpecific(context);
} finally {
c.setInternalModuleVariable("vpPrecLimit", nCur);
}
return ret;
}
@JRubyMethod(name = "save_exception_mode", meta = true)
public static IRubyObject save_exception_mode(ThreadContext context, IRubyObject recv, Block block) {
RubyModule c = (RubyModule)recv;
IRubyObject nCur = c.searchInternalModuleVariable("vpExceptionMode");
IRubyObject ret;
try {
ret = block.yieldSpecific(context);
} finally {
c.setInternalModuleVariable("vpExceptionMode", nCur);
}
return ret;
}
@JRubyMethod(name = "save_rounding_mode", meta = true)
public static IRubyObject save_rounding_mode(ThreadContext context, IRubyObject recv, Block block) {
RubyModule c = (RubyModule)recv;
IRubyObject nCur = c.searchInternalModuleVariable("vpRoundingMode");
IRubyObject ret;
try {
ret = block.yieldSpecific(context);
} finally {
c.setInternalModuleVariable("vpRoundingMode", nCur);
}
return ret;
}
@JRubyMethod(name = "mode", required = 1, optional = 1, meta = true)
public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
// FIXME: I doubt any of the constants referenced in this method
// are ever redefined -- should compare to the known values, rather
// than do an expensive constant lookup.
Ruby runtime = recv.getRuntime();
RubyClass clazz = runtime.getClass("BigDecimal");
RubyModule c = (RubyModule)recv;
args = Arity.scanArgs(runtime, args, 1, 1);
IRubyObject mode = args[0];
IRubyObject value = args[1];
if (!(mode instanceof RubyFixnum)) {
throw runtime.newTypeError("wrong argument type " + mode.getMetaClass() + " (expected Fixnum)");
}
long longMode = ((RubyFixnum)mode).getLongValue();
long EXCEPTION_ALL = ((RubyFixnum)clazz.getConstant("EXCEPTION_ALL")).getLongValue();
if ((longMode & EXCEPTION_ALL) != 0) {
if (value.isNil()) {
return c.searchInternalModuleVariable("vpExceptionMode");
}
if (!(value.isNil()) && !(value instanceof RubyBoolean)) {
throw runtime.newArgumentError("second argument must be true or false");
}
RubyFixnum currentExceptionMode = (RubyFixnum)c.searchInternalModuleVariable("vpExceptionMode");
RubyFixnum newExceptionMode = new RubyFixnum(runtime, currentExceptionMode.getLongValue());
RubyFixnum EXCEPTION_INFINITY = (RubyFixnum)clazz.getConstant("EXCEPTION_INFINITY");
if ((longMode & EXCEPTION_INFINITY.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_INFINITY)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_INFINITY).getLongValue()));
}
RubyFixnum EXCEPTION_NaN = (RubyFixnum)clazz.getConstant("EXCEPTION_NaN");
if ((longMode & EXCEPTION_NaN.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_NaN)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_NaN).getLongValue()));
}
RubyFixnum EXCEPTION_UNDERFLOW = (RubyFixnum)clazz.getConstant("EXCEPTION_UNDERFLOW");
if ((longMode & EXCEPTION_UNDERFLOW.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_UNDERFLOW)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_UNDERFLOW).getLongValue()));
}
RubyFixnum EXCEPTION_OVERFLOW = (RubyFixnum)clazz.getConstant("EXCEPTION_OVERFLOW");
if ((longMode & EXCEPTION_OVERFLOW.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_OVERFLOW)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_OVERFLOW).getLongValue()));
}
c.setInternalModuleVariable("vpExceptionMode", newExceptionMode);
return newExceptionMode;
}
long ROUND_MODE = ((RubyFixnum)clazz.getConstant("ROUND_MODE")).getLongValue();
if (longMode == ROUND_MODE) {
if (value.isNil()) {
return c.searchInternalModuleVariable("vpRoundingMode");
}
RoundingMode javaRoundingMode = javaRoundingModeFromRubyRoundingMode(runtime, value);
RubyFixnum roundingMode = runtime.newFixnum(javaRoundingMode.ordinal());
c.setInternalModuleVariable("vpRoundingMode", roundingMode);
return c.searchInternalModuleVariable("vpRoundingMode");
}
throw runtime.newTypeError("first argument for BigDecimal#mode invalid");
}
private static RoundingMode getRoundingMode(Ruby runtime) {
RubyFixnum roundingMode = (RubyFixnum)runtime.getClass("BigDecimal")
.searchInternalModuleVariable("vpRoundingMode");
return RoundingMode.valueOf((int)roundingMode.getLongValue());
}
private static boolean isNaNExceptionMode(Ruby runtime) {
RubyFixnum currentExceptionMode = (RubyFixnum)runtime.getClass("BigDecimal")
.searchInternalModuleVariable("vpExceptionMode");
RubyFixnum EXCEPTION_NaN = (RubyFixnum)runtime.getClass("BigDecimal")
.getConstant("EXCEPTION_NaN");
return (currentExceptionMode.getLongValue() & EXCEPTION_NaN.getLongValue()) != 0;
}
private static boolean isInfinityExceptionMode(Ruby runtime) {
RubyFixnum currentExceptionMode = (RubyFixnum)runtime.getClass("BigDecimal")
.searchInternalModuleVariable("vpExceptionMode");
RubyFixnum EXCEPTION_INFINITY = (RubyFixnum)runtime.getClass("BigDecimal")
.getConstant("EXCEPTION_INFINITY");
return (currentExceptionMode.getLongValue() & EXCEPTION_INFINITY.getLongValue()) != 0;
}
private static boolean isOverflowExceptionMode(Ruby runtime) {
RubyFixnum currentExceptionMode = (RubyFixnum)runtime.getClass("BigDecimal")
.searchInternalModuleVariable("vpExceptionMode");
RubyFixnum EXCEPTION_OVERFLOW = (RubyFixnum)runtime.getClass("BigDecimal")
.getConstant("EXCEPTION_OVERFLOW");
return (currentExceptionMode.getLongValue() & EXCEPTION_OVERFLOW.getLongValue()) != 0;
}
private static RubyBigDecimal cannotBeCoerced(ThreadContext context, IRubyObject v, boolean must) {
if (must) {
String err;
if (v == null) {
err = "nil";
} else if (v.isImmediate()) {
err = RubyObject.inspect(context, v).toString();
} else {
err = v.getMetaClass().getBaseName();
}
throw context.runtime.newTypeError(err + " can't be coerced into BigDecimal");
}
return null;
}
private static RubyBigDecimal unableToCoerceWithoutPrec(ThreadContext context, IRubyObject v, boolean must) {
if (must) {
throw context.runtime.newArgumentError(v.getMetaClass().getBaseName() + " can't be coerced into BigDecimal without a precision");
}
return null;
}
private static RubyBigDecimal getVpValue19(ThreadContext context, IRubyObject v, boolean must) {
long precision;
if (v instanceof RubyFloat) {
precision = 0;
} else if (v instanceof RubyRational) {
precision = 0;
} else {
precision = -1;
}
return getVpValueWithPrec19(context, v, precision, must);
}
private static IRubyObject getVpRubyObjectWithPrec19Inner(ThreadContext context, RubyRational r, long precision, boolean must) {
BigDecimal numerator = BigDecimal.valueOf(RubyNumeric.num2long(r.numerator(context)));
BigDecimal denominator = BigDecimal.valueOf(RubyNumeric.num2long(r.denominator(context)));
int len = numerator.precision() + denominator.precision();
int pow = len / 4;
MathContext mathContext = new MathContext((pow + 1) * 4, getRoundingMode(context.runtime));
return new RubyBigDecimal(context.runtime, numerator.divide(denominator, mathContext));
}
private static RubyBigDecimal getVpValueWithPrec19(ThreadContext context, IRubyObject value, long precision, boolean must) {
while (true) {
if (value instanceof RubyFloat) {
if (precision > Long.MAX_VALUE) cannotBeCoerced(context, value, must);
RubyFloat f = (RubyFloat)value;
value = new RubyBigDecimal(context.runtime, BigDecimal.valueOf(f.getDoubleValue()));
continue;
} else if (value instanceof RubyRational) {
if (precision < 0) return unableToCoerceWithoutPrec(context, value, must);
value = getVpRubyObjectWithPrec19Inner(context, (RubyRational) value, precision, must);
continue;
} else if (value instanceof RubyBigDecimal) {
return (RubyBigDecimal) value;
} else if (value instanceof RubyFixnum || value instanceof RubyBignum) {
String s = value.toString();
return newInstance(value.getRuntime().getClass("BigDecimal"), new IRubyObject[]{value.getRuntime().newString(s)});
}
return cannotBeCoerced(context, value, must);
}
}
private static RubyBigDecimal getVpValue(IRubyObject v, boolean must) {
if (v instanceof RubyBigDecimal) {
return (RubyBigDecimal)v;
} else if (v instanceof RubyFixnum || v instanceof RubyBignum) {
String s = v.toString();
return newInstance(v.getRuntime().getClass("BigDecimal"), new IRubyObject[]{v.getRuntime().newString(s)});
}
return cannotBeCoerced(v.getRuntime().getCurrentContext(), v, must);
}
@JRubyMethod(name = "induced_from", required = 1, meta = true)
public static IRubyObject induced_from(IRubyObject recv, IRubyObject arg) {
return getVpValue(arg, true);
}
private final static Pattern INFINITY_PATTERN = Pattern.compile("^([+-])?Infinity$");
private final static Pattern NUMBER_PATTERN
= Pattern.compile("^([+-]?\\d*\\.?\\d*([eE][+-]?)?\\d*).*");
@JRubyMethod(name = "new", required = 1, optional = 1, meta = true)
public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
BigDecimal decimal;
Ruby runtime = recv.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
if (args.length == 0) {
decimal = new BigDecimal(0);
} else {
MathContext context = MathContext.UNLIMITED;
if (args.length == 2) {
int digits = (int)args[1].convertToInteger().getLongValue();
if (digits < 0) {
throw runtime.newArgumentError("argument must be positive");
}
context = new MathContext(digits);
}
if (runtime.is1_9()) {
if (args[0] instanceof RubyBigDecimal) {
return new RubyBigDecimal(runtime, (RubyClass)recv, ((RubyBigDecimal)args[0]));
} else if (args[0] instanceof RubyFloat || args[0] instanceof RubyRational) {
if (args.length != 2) {
// float input must be accompanied by precision
throw runtime.newArgumentError("can't omit precision for a rational");
}
if (args[0] instanceof RubyFloat) {
// precision can be no more than float digits
if (context.getPrecision() > RubyFloat.DIG + 1) {
throw runtime.newArgumentError("precision too large");
}
return new RubyBigDecimal(runtime, (RubyClass)recv, new BigDecimal(((RubyFloat)args[0]).getDoubleValue(), context));
} else {
RubyRational rat = (RubyRational)args[0];
BigDecimal num = new BigDecimal(rat.numerator(ctx).convertToInteger().getLongValue());
BigDecimal den = new BigDecimal(rat.denominator(ctx).convertToInteger().getLongValue());
BigDecimal value = num.divide(den, context);
return new RubyBigDecimal(runtime, value);
}
} else if (args[0] instanceof RubyFixnum) {
return new RubyBigDecimal(runtime, (RubyClass)recv, new BigDecimal(((RubyFixnum)args[0]).getLongValue(), context));
} else if (args[0] instanceof RubyBignum) {
return new RubyBigDecimal(runtime, (RubyClass)recv, new BigDecimal(((RubyBignum)args[0]).getBigIntegerValue(), context));
}
// fall through to String coercion below
}
String strValue = args[0].convertToString().toString();
strValue = strValue.trim();
if ("NaN".equals(strValue)) {
return newNaN(runtime);
}
Matcher m = INFINITY_PATTERN.matcher(strValue);
if (m.matches()) {
int sign = 1;
String signGroup = m.group(1);
if ("-".equals(signGroup)) {
sign = -1;
}
return newInfinity(runtime, sign);
}
// Clean-up string representation so that it could be understood
// by Java's BigDecimal. Not terribly efficient for now.
// 1. MRI allows d and D as exponent separators
strValue = strValue.replaceFirst("[dD]", "E");
// 2. MRI allows underscores anywhere
strValue = strValue.replaceAll("_", "");
// 3. MRI ignores the trailing junk
strValue = NUMBER_PATTERN.matcher(strValue).replaceFirst("$1");
try {
decimal = new BigDecimal(strValue, context);
} catch(NumberFormatException e) {
if (isOverflowExceptionMode(runtime)) {
throw runtime.newFloatDomainError("exponent overflow");
}
decimal = new BigDecimal(0);
}
if (decimal.signum() == 0) {
// MRI behavior: -0 and +0 are two different things
if (strValue.matches("^\\s*-.*")) {
return newZero(runtime, -1);
} else {
return newZero(runtime, 1);
}
}
}
return new RubyBigDecimal(runtime, (RubyClass)recv, decimal);
}
private static RubyBigDecimal newZero(Ruby runtime, int sign) {
int zeroSign;
if (sign < 0) {
zeroSign = -1;
} else {
zeroSign = 1;
}
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO, 0, zeroSign);
return rbd;
}
private static RubyBigDecimal newNaN(Ruby runtime) {
if (isNaNExceptionMode(runtime)) throw runtime.newFloatDomainError("Computation results to 'NaN'(Not a Number)");
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO, true);
return rbd;
}
private static RubyBigDecimal newInfinity(Ruby runtime, int sign) {
int infinitySign;
if (sign < 0) {
infinitySign = -1;
} else {
infinitySign = 1;
}
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO, infinitySign);
if (isInfinityExceptionMode(runtime)) throw runtime.newFloatDomainError("Computation results to 'Infinity'");
return rbd;
}
private RubyBigDecimal setResult() {
return setResult(0);
}
private RubyBigDecimal setResult(int scale) {
int prec = RubyFixnum.fix2int(getRuntime().getClass("BigDecimal").searchInternalModuleVariable("vpPrecLimit"));
int prec2 = Math.max(scale, prec);
if (prec2 > 0 && this.value.scale() > (prec2-getExponent())) {
this.value = this.value.setScale(prec2-getExponent(), BigDecimal.ROUND_HALF_UP);
}
return this;
}
@Override
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(value.stripTrailingZeros().hashCode());
}
@JRubyMethod(name = {"%", "modulo"}, required = 1, compat = CompatVersion.RUBY1_8)
public IRubyObject op_mod(ThreadContext context, IRubyObject arg) {
// TODO: full-precision remainder is 1000x slower than MRI!
Ruby runtime = context.runtime;
if (isInfinity() || isNaN()) {
return newNaN(runtime);
}
RubyBigDecimal val = getVpValue(arg, false);
if (val == null) {
return callCoerced(context, "%", arg, true);
}
if (val.isInfinity() || val.isNaN() || val.isZero()) {
return newNaN(runtime);
}
// Java and MRI definitions of modulo are different.
BigDecimal modulo = value.remainder(val.value);
if (modulo.signum() * val.value.signum() < 0) {
modulo = modulo.add(val.value);
}
return new RubyBigDecimal(runtime, modulo).setResult();
}
@JRubyMethod(name = {"%", "modulo"}, required = 1, compat = CompatVersion.RUBY1_9)
public IRubyObject op_mod19(ThreadContext context, IRubyObject other) {
// TODO: full-precision divmod is 1000x slower than MRI!
Ruby runtime = context.runtime;
RubyBigDecimal val = getVpValue19(context, other, false);
if (val == null) {
return callCoerced(context, "%", other, true);
}
if (isNaN() || val.isNaN() || (isInfinity() && val.isInfinity())) {
return newNaN(runtime);
}
if (val.isZero()) {
throw context.runtime.newZeroDivisionError();
}
if (isInfinity()) {
return newNaN(runtime);
}
if (val.isInfinity()) {
return this;
}
if (isZero()) {
return newZero(runtime, value.signum());
}
// Java and MRI definitions of modulo are different.
BigDecimal modulo = value.remainder(val.value);
if (modulo.signum() * val.value.signum() < 0) {
modulo = modulo.add(val.value);
}
return new RubyBigDecimal(runtime, modulo).setResult();
}
@Override
@JRubyMethod(name = "remainder", required = 1, compat = CompatVersion.RUBY1_8)
public IRubyObject remainder(ThreadContext context, IRubyObject arg) {
RubyBigDecimal val = getVpValue(arg, false);
return remainderInternal(context, val, arg);
}
@JRubyMethod(name = "remainder", required = 1, compat = CompatVersion.RUBY1_9)
public IRubyObject remainder19(ThreadContext context, IRubyObject arg) {
RubyBigDecimal val = getVpValue19(context, arg, false);
return remainderInternal(context, val, arg);
}
private IRubyObject remainderInternal(ThreadContext context, RubyBigDecimal val, IRubyObject arg) {
// TODO: full-precision remainder is 1000x slower than MRI!
Ruby runtime = context.runtime;
if (isInfinity() || isNaN()) {
return newNaN(runtime);
}
if (val == null) {
return callCoerced(context, "remainder", arg, true);
}
if (val.isInfinity() || val.isNaN() || val.isZero()) {
return newNaN(runtime);
}
// Java and MRI definitions of remainder are the same.
return new RubyBigDecimal(runtime, value.remainder(val.value)).setResult();
}
@JRubyMethod(name = "*", required = 1, compat = CompatVersion.RUBY1_8)
public IRubyObject op_mul(ThreadContext context, IRubyObject arg) {
return mult2(context, arg, getRuntime().getClass("BigDecimal")
.searchInternalModuleVariable("vpPrecLimit"));
}
@JRubyMethod(name = "*", required = 1, compat = CompatVersion.RUBY1_9)
public IRubyObject op_mul19(ThreadContext context, IRubyObject arg) {
return mult219(context, arg, getRuntime().getClass("BigDecimal")
.searchInternalModuleVariable("vpPrecLimit"));
}
@JRubyMethod(name = "mult", required = 2, compat = CompatVersion.RUBY1_8)
public IRubyObject mult2(ThreadContext context, IRubyObject b, IRubyObject n) {
RubyBigDecimal val = getVpValue(b, false);
return multInternal(context, val, b, n);
}
@JRubyMethod(name = "mult", required = 2, compat = CompatVersion.RUBY1_9)
public IRubyObject mult219(ThreadContext context, IRubyObject b, IRubyObject n) {
RubyBigDecimal val = getVpValue19(context, b, false);
if (val == null) return cannotBeCoerced(context, val, true);
return multInternal(context, val, b, n);
}
private IRubyObject multInternal(ThreadContext context, RubyBigDecimal val, IRubyObject b, IRubyObject n) {
Ruby runtime = context.runtime;
if (val == null) {
// TODO: what about n arg?
return callCoerced(context, "*", b);
}
int digits = RubyNumeric.fix2int(n);
if (isNaN() || val.isNaN()) {
return newNaN(runtime);
}
if ((isInfinity() && val.isZero()) || (isZero() && val.isInfinity())) {
return newNaN(runtime);
}
if (isZero() || val.isZero()) {
int sign1 = isZero()? zeroSign : value.signum();
int sign2 = val.isZero() ? val.zeroSign : val.value.signum();
return newZero(runtime, sign1 * sign2);
}
if (isInfinity() || val.isInfinity()) {
int sign1 = isInfinity() ? infinitySign : value.signum();
int sign2 = val.isInfinity() ? val.infinitySign : val.value.signum();
return newInfinity(runtime, sign1 * sign2);
}
BigDecimal res = value.multiply(val.value);
if (res.precision() > digits) {
// TODO: rounding mode should not be hard-coded. See #mode.
res = res.round(new MathContext(digits, RoundingMode.HALF_UP));
}
return new RubyBigDecimal(runtime, res).setResult();
}
@JRubyMethod(name = {"**", "power"}, required = 1, compat = CompatVersion.RUBY1_8)
public IRubyObject op_pow(IRubyObject arg) {
if (!(arg instanceof RubyFixnum)) {
throw getRuntime().newTypeError("wrong argument type " + arg.getMetaClass() + " (expected Fixnum)");
}
if (isNaN() || isInfinity()) {
return newNaN(getRuntime());
}
int times = RubyNumeric.fix2int(arg.convertToInteger());
if (times < 0) {
if (isZero()) {
return newInfinity(getRuntime(), value.signum());
}
// Note: MRI has a very non-trivial way of calculating the precision,
// so we use very simple approximation here:
int precision = (-times + 4) * (getAllDigits().length() + 4);
return new RubyBigDecimal(getRuntime(),
value.pow(times, new MathContext(precision, RoundingMode.HALF_UP)));
} else {
return new RubyBigDecimal(getRuntime(), value.pow(times));
}
}
@JRubyMethod(name = {"**", "power"}, required = 1, compat = CompatVersion.RUBY1_9)
public IRubyObject op_pow19(IRubyObject exp) {
if (!(exp instanceof RubyFixnum)) {
throw getRuntime().newTypeError("wrong argument type " + exp.getMetaClass() + " (expected Fixnum)");
}
Ruby runtime = getRuntime();
ThreadContext context = runtime.getCurrentContext();
if (isNaN()) {
return newNaN(runtime);
}
if (isInfinity()) {
if (Numeric.f_negative_p(context, exp)) {
if (infinitySign < 0) {
if (Numeric.f_integer_p(context, exp).isTrue()) {
if (is_even(exp)) {
/* (-Infinity) ** (-even_integer) -> +0 */
return newZero(runtime, 1);
} else {
/* (-Infinity) ** (-odd_integer) -> -0 */
return newZero(runtime, -1);
}
} else {
/* (-Infinity) ** (-non_integer) -> -0 */
return newZero(runtime, -1);
}
} else {
return newZero(runtime, 0);
}
} else {
if (infinitySign < 0) {
if (Numeric.f_integer_p(context, exp).isTrue()) {
if (is_even(exp)) {
return newInfinity(runtime, 1);
} else {
return newInfinity(runtime, -1);
}
} else {
throw runtime.newMathDomainError("a non-integral exponent for a negative base");
}
} else {
return newInfinity(runtime, 1);
}
}
}
int times = RubyNumeric.fix2int(exp.convertToInteger());
if (times < 0) {
if (isZero()) {
return newInfinity(getRuntime(), value.signum());
}
// Note: MRI has a very non-trivial way of calculating the precision,
// so we use very simple approximation here:
int precision = (-times + 4) * (getAllDigits().length() + 4);
return new RubyBigDecimal(getRuntime(),
value.pow(times, new MathContext(precision, RoundingMode.HALF_UP)));
} else {
return new RubyBigDecimal(getRuntime(), value.pow(times));
}
}
@JRubyMethod(name = "+", compat = CompatVersion.RUBY1_8)
public IRubyObject op_plus(ThreadContext context, IRubyObject b) {
RubyBigDecimal val = getVpValue(b, false);
return addInternal(context, val, b, getRuntime().getClass("BigDecimal")
.searchInternalModuleVariable("vpPrecLimit"));
}
@JRubyMethod(name = "+", compat = CompatVersion.RUBY1_9)
public IRubyObject op_plus19(ThreadContext context, IRubyObject b) {
RubyBigDecimal val = getVpValue19(context, b, false);
return addInternal(context, val, b, getRuntime().getClass("BigDecimal")
.searchInternalModuleVariable("vpPrecLimit"));
}
@JRubyMethod(name = "add", compat = CompatVersion.RUBY1_8)
public IRubyObject add2(ThreadContext context, IRubyObject b, IRubyObject digits) {
RubyBigDecimal val = getVpValue(b, false);
return addInternal(context, val, b, digits);
}
@JRubyMethod(name = "add", compat = CompatVersion.RUBY1_9)
public IRubyObject add219(ThreadContext context, IRubyObject b, IRubyObject digits) {
RubyBigDecimal val = getVpValue19(context, b, false);
return addInternal(context, val, b, digits);
}
private IRubyObject addInternal(ThreadContext context, RubyBigDecimal val, IRubyObject b, IRubyObject digits) {
Ruby runtime = context.runtime;
int prec = getPositiveInt(context, digits);
if (val == null) {
// TODO:
// MRI behavior: Call "+" or "add", depending on the call.
// But this leads to exceptions when Floats are added. See:
// http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/17374
// return callCoerced(context, op, b, true); -- this is MRI behavior.
// We'll use ours for now, thus providing an ability to add Floats.
return callCoerced(context, "+", b, true);
}
RubyBigDecimal res = handleAddSpecialValues(val);
if (res != null) {
return res;
}
RoundingMode roundMode = getRoundingMode(runtime);
return new RubyBigDecimal(runtime, value.add(
val.value, new MathContext(prec, roundMode))); // TODO: why this: .setResult();
}
private int getPositiveInt(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.runtime;
if (arg instanceof RubyFixnum) {
int value = RubyNumeric.fix2int(arg);
if (value < 0) {
throw runtime.newArgumentError("argument must be positive");
}
return value;
} else {
throw runtime.newTypeError(arg, runtime.getFixnum());
}
}
private RubyBigDecimal handleAddSpecialValues(RubyBigDecimal val) {
if (isNaN() || val.isNaN) {
return newNaN(getRuntime());
}
int sign = infinitySign * val.infinitySign;
if (sign > 0) {
return isInfinity() ? this : val;
}
if (sign < 0) {
return newNaN(getRuntime());
}
if (sign == 0) {
sign = infinitySign + val.infinitySign;
if (sign != 0) {
return newInfinity(getRuntime(), sign);
}
}
return null;
}
@Override
@JRubyMethod(name = "+@")
public IRubyObject op_uplus() {
return this;
}
@JRubyMethod(name = "-", required = 1, compat = CompatVersion.RUBY1_8)
public IRubyObject op_minus(ThreadContext context, IRubyObject b) {