/
RubyBigDecimal.java
2362 lines (1949 loc) · 92.7 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 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.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-v20.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.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jruby.*;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.common.IRubyWarnings;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.JavaSites;
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.ByteList;
import org.jruby.util.Numeric;
import org.jruby.util.SafeDoubleParser;
import org.jruby.util.StringSupport;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class RubyBigDecimal extends RubyNumeric {
@JRubyConstant
public final static int ROUND_DOWN = RoundingMode.DOWN.ordinal();
@JRubyConstant
public final static int ROUND_CEILING = RoundingMode.CEILING.ordinal();
@JRubyConstant
public final static int ROUND_UP = RoundingMode.UP.ordinal();
@JRubyConstant
public final static int ROUND_HALF_DOWN = RoundingMode.HALF_DOWN.ordinal();
@JRubyConstant
public final static int ROUND_HALF_EVEN = RoundingMode.HALF_EVEN.ordinal();
@JRubyConstant
public final static int ROUND_HALF_UP = RoundingMode.HALF_UP.ordinal();
@JRubyConstant
public final static int ROUND_FLOOR = RoundingMode.FLOOR.ordinal();
@JRubyConstant
public final static int SIGN_POSITIVE_INFINITE = 3;
@JRubyConstant
public final static int SIGN_POSITIVE_ZERO = 1;
@JRubyConstant
public final static int SIGN_NEGATIVE_FINITE = -2;
@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 SIGN_NEGATIVE_INFINITE = -3;
@JRubyConstant
public final static int SIGN_NEGATIVE_ZERO = -1;
@JRubyConstant
public final static int EXCEPTION_INFINITY = 1;
@JRubyConstant
public final static int EXCEPTION_OVERFLOW = 1; // Note: This is same as EXCEPTION_INFINITY in MRI now
@JRubyConstant
public final static int EXCEPTION_NaN = 2;
@JRubyConstant
public final static int EXCEPTION_UNDERFLOW = 4;
@JRubyConstant
public final static int EXCEPTION_ZERODIVIDE = 16;
@JRubyConstant
public final static int EXCEPTION_ALL = 255;
private static final ByteList VERSION = ByteList.create("1.3.4");
// (MRI-like) internals
private static final short VP_DOUBLE_FIG = 16;
// #elif SIZEOF_BDIGITS >= 4
// # define RMPD_COMPONENT_FIGURES 9
private static final short RMPD_COMPONENT_FIGURES = 9;
// rmpd_component_figures(void) { return RMPD_COMPONENT_FIGURES; }
// #define VpBaseFig() rmpd_component_figures()
private static final short BASE_FIG = RMPD_COMPONENT_FIGURES;
// Static constants
private static final double SQRT_10 = 3.162277660168379332;
private static final long NEGATIVE_ZERO_LONG_BITS = Double.doubleToLongBits(-0.0);
public static RubyClass createBigDecimal(Ruby runtime) {
RubyClass bigDecimal = runtime.defineClass("BigDecimal", runtime.getNumeric(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
bigDecimal.setConstant("VERSION", RubyString.newStringShared(runtime, VERSION));
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);
bigDecimal.getSingletonClass().undefineMethod("allocate");
//RubyModule bigMath = runtime.defineModule("BigMath");
// NOTE: BigMath.exp and BigMath.pow should be implemented as native
// for now @see jruby/bigdecimal.rb
bigDecimal.defineConstant("NAN", newNaN(runtime));
bigDecimal.defineConstant("INFINITY", newInfinity(runtime, 1));
bigDecimal.setReifiedClass(RubyBigDecimal.class);
return bigDecimal;
}
private boolean isNaN;
private int infinitySign; // 0 (for finite), -1, +1
private int zeroSign; // -1, +1 (if zero, otherwise 0)
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;
this.value = BigDecimal.ZERO;
this.flags |= FROZEN_F;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value) {
super(runtime, runtime.getClass("BigDecimal"));
this.isNaN = false;
this.infinitySign = 0;
this.zeroSign = 0;
this.value = value;
this.flags |= FROZEN_F;
}
public RubyBigDecimal(Ruby runtime, RubyClass klass, BigDecimal value) {
super(runtime, klass);
this.isNaN = false;
this.infinitySign = 0;
this.zeroSign = 0;
this.value = value;
this.flags |= FROZEN_F;
}
public RubyBigDecimal(Ruby runtime, BigDecimal value, int infinitySign) {
this(runtime, value, infinitySign, 0);
}
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;
this.flags |= FROZEN_F;
}
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;
this.flags |= FROZEN_F;
}
RubyBigDecimal(Ruby runtime, RubyClass klass, BigDecimal value, int zeroSign, int infinitySign, boolean isNaN) {
super(runtime, klass);
this.isNaN = isNaN;
this.infinitySign = infinitySign;
this.zeroSign = zeroSign;
this.value = value;
this.flags |= FROZEN_F;
}
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.BIGDECIMAL;
}
public static class BigDecimalKernelMethods {
@JRubyMethod(name = "BigDecimal", module = true, visibility = Visibility.PRIVATE) // required = 1, optional = 1
public static IRubyObject newBigDecimal(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return newInstance(context, context.runtime.getClass("BigDecimal"), arg, true, true);
}
@JRubyMethod(name = "BigDecimal", module = true, visibility = Visibility.PRIVATE) // required = 1, optional = 1
public static IRubyObject newBigDecimal(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
Ruby runtime = context.runtime;
RubyClass bigDecimal = runtime.getClass("BigDecimal");
IRubyObject maybeOpts = ArgsUtil.getOptionsArg(runtime, arg1, false);
if (maybeOpts.isNil()) {
return newInstance(context, bigDecimal, arg0, arg1, true, true);
}
IRubyObject exObj = ArgsUtil.extractKeywordArg(context, "exception", maybeOpts);
boolean exception = exObj.isNil() ? true : exObj.isTrue();
return newInstance(context, bigDecimal, arg0, true, exception);
}
@JRubyMethod(name = "BigDecimal", module = true, visibility = Visibility.PRIVATE) // required = 1, optional = 1
public static IRubyObject newBigDecimal(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject opts) {
Ruby runtime = context.runtime;
IRubyObject maybeOpts = ArgsUtil.getOptionsArg(runtime, opts, false);
if (maybeOpts.isNil()) {
throw runtime.newArgumentError(3, 1, 2);
}
IRubyObject exObj = ArgsUtil.extractKeywordArg(context, "exception", maybeOpts);
boolean exception = exObj.isNil() ? true : exObj.isTrue();
return newInstance(context, context.runtime.getClass("BigDecimal"), arg0, arg1, true, exception);
}
}
@JRubyMethod
public IRubyObject _dump(ThreadContext context) {
return RubyString.newUnicodeString(context.runtime, "0:").append(asString());
}
@JRubyMethod
public IRubyObject _dump(ThreadContext context, IRubyObject unused) {
return RubyString.newUnicodeString(context.runtime, "0:").append(asString());
}
@JRubyMethod(meta = true)
public static RubyBigDecimal _load(ThreadContext context, IRubyObject recv, IRubyObject from) {
String precisionAndValue = from.convertToString().asJavaString();
String value = precisionAndValue.substring(precisionAndValue.indexOf(':') + 1);
return newInstance(context, recv, RubyString.newString(context.runtime, value));
}
@JRubyMethod(meta = true)
public static IRubyObject double_fig(ThreadContext context, IRubyObject recv) {
return context.runtime.newFixnum(VP_DOUBLE_FIG);
}
/**
* Retrieve vpPrecLimit.
*/
@JRubyMethod(meta = true)
public static IRubyObject limit(ThreadContext context, IRubyObject recv) {
return ((RubyModule) recv).searchInternalModuleVariable("vpPrecLimit");
}
/**
* Set new vpPrecLimit if Fixnum and return the old value.
*/
@JRubyMethod(meta = true)
public static IRubyObject limit(ThreadContext context, IRubyObject recv, IRubyObject arg) {
IRubyObject old = limit(context, recv);
if (arg == context.nil) return old;
if (!(arg instanceof RubyFixnum)) throw context.runtime.newTypeError(arg, context.runtime.getFixnum());
if (0 > ((RubyFixnum)arg).getLongValue()) throw context.runtime.newArgumentError("argument must be positive");
((RubyModule) recv).setInternalModuleVariable("vpPrecLimit", arg);
return old;
}
@JRubyMethod(meta = true)
public static IRubyObject save_limit(ThreadContext context, IRubyObject recv, Block block) {
return modeExecute(context, (RubyModule) recv, block, "vpPrecLimit");
}
@JRubyMethod(meta = true)
public static IRubyObject save_exception_mode(ThreadContext context, IRubyObject recv, Block block) {
return modeExecute(context, (RubyModule) recv, block, "vpExceptionMode");
}
@JRubyMethod(meta = true)
public static IRubyObject save_rounding_mode(ThreadContext context, IRubyObject recv, Block block) {
return modeExecute(context, (RubyModule) recv, block, "vpRoundingMode");
}
@JRubyMethod(meta = true)
public static IRubyObject interpret_loosely(ThreadContext context, IRubyObject recv, IRubyObject str) {
return newInstance(context, recv, str, false, true);
}
private static IRubyObject modeExecute(final ThreadContext context, final RubyModule BigDecimal,
final Block block, final String intVariableName) {
IRubyObject current = BigDecimal.searchInternalModuleVariable(intVariableName);
try {
return block.yieldSpecific(context);
}
finally {
BigDecimal.setInternalModuleVariable(intVariableName, current);
}
}
@JRubyMethod(required = 1, optional = 1, meta = true)
public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
// 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.
RubyModule c = (RubyModule)recv;
args = Arity.scanArgs(context.runtime, args, 1, 1);
IRubyObject mode = args[0];
IRubyObject value = args[1];
if (!(mode instanceof RubyFixnum)) {
throw context.runtime.newTypeError("wrong argument type " + mode.getMetaClass() + " (expected Fixnum)");
}
long longMode = ((RubyFixnum)mode).getLongValue();
if ((longMode & EXCEPTION_ALL) != 0) {
if (value.isNil()) return c.searchInternalModuleVariable("vpExceptionMode");
if (!(value instanceof RubyBoolean)) throw context.runtime.newArgumentError("second argument must be true or false");
long newExceptionMode = c.searchInternalModuleVariable("vpExceptionMode").convertToInteger().getLongValue();
boolean enable = value.isTrue();
if ((longMode & EXCEPTION_INFINITY) != 0) {
newExceptionMode = enable ? newExceptionMode | EXCEPTION_INFINITY : newExceptionMode & ~(EXCEPTION_INFINITY);
}
if ((longMode & EXCEPTION_NaN) != 0) {
newExceptionMode = enable ? newExceptionMode | EXCEPTION_NaN : newExceptionMode & ~(EXCEPTION_NaN);
}
if ((longMode & EXCEPTION_UNDERFLOW) != 0) {
newExceptionMode = enable ? newExceptionMode | EXCEPTION_UNDERFLOW : newExceptionMode & ~(EXCEPTION_UNDERFLOW);
}
if ((longMode & EXCEPTION_ZERODIVIDE) != 0) {
newExceptionMode = enable ? newExceptionMode | EXCEPTION_ZERODIVIDE : newExceptionMode & ~(EXCEPTION_ZERODIVIDE);
}
RubyFixnum fixnumMode = RubyFixnum.newFixnum(runtime, newExceptionMode);
c.setInternalModuleVariable("vpExceptionMode", fixnumMode);
return fixnumMode;
}
if (longMode == ROUND_MODE) {
if (value == context.nil) {
return c.searchInternalModuleVariable("vpRoundingMode");
}
RoundingMode javaRoundingMode = javaRoundingModeFromRubyRoundingMode(context, value);
RubyFixnum roundingMode = runtime.newFixnum(javaRoundingMode.ordinal());
c.setInternalModuleVariable("vpRoundingMode", roundingMode);
return roundingMode;
}
throw runtime.newTypeError("first argument for BigDecimal#mode invalid");
}
// The Fixnum cast should be fine because these are internal variables and user code cannot change them.
private static long bigDecimalVar(Ruby runtime, String variableName) {
return ((RubyFixnum) runtime.getClass("BigDecimal").searchInternalModuleVariable(variableName)).getLongValue();
}
private static RoundingMode getRoundingMode(Ruby runtime) {
return RoundingMode.values()[(int) bigDecimalVar(runtime, "vpRoundingMode")];
}
private static boolean isNaNExceptionMode(Ruby runtime) {
return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_NaN) != 0;
}
private static boolean isInfinityExceptionMode(Ruby runtime) {
return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_INFINITY) != 0;
}
private static boolean isOverflowExceptionMode(Ruby runtime) {
return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_OVERFLOW) != 0;
}
private static boolean isUnderflowExceptionMode(Ruby runtime) {
return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_UNDERFLOW) != 0;
}
private static boolean isZeroDivideExceptionMode(Ruby runtime) {
return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_ZERODIVIDE) != 0;
}
private static RubyBigDecimal cannotBeCoerced(ThreadContext context, IRubyObject value, boolean must) {
if (must) {
throw context.runtime.newTypeError(
errMessageType(context, value) + " can't be coerced into BigDecimal"
);
}
return null;
}
private static String errMessageType(ThreadContext context, IRubyObject value) {
if (value == null || value == context.nil) return "nil";
if (value.isImmediate()) return RubyObject.inspect(context, value).toString();
return value.getMetaClass().getBaseName();
}
private static BigDecimal toBigDecimal(final RubyInteger value) {
if (value instanceof RubyFixnum) {
return BigDecimal.valueOf(RubyNumeric.num2long(value));
}
return new BigDecimal(value.getBigIntegerValue());
}
private static RubyBigDecimal getVpRubyObjectWithPrecInner(ThreadContext context, RubyRational value, RoundingMode mode) {
BigDecimal numerator = toBigDecimal(value.getNumerator());
BigDecimal denominator = toBigDecimal(value.getDenominator());
int len = numerator.precision() + denominator.precision(); // 0
int pow = len / 4; // 0
MathContext mathContext = new MathContext((pow + 1) * 4, mode);
return new RubyBigDecimal(context.runtime, numerator.divide(denominator, mathContext));
}
private RubyBigDecimal getVpValueWithPrec(ThreadContext context, IRubyObject value, boolean must) {
if (value instanceof RubyFloat) {
double doubleValue = ((RubyFloat) value).getDoubleValue();
if (Double.isInfinite(doubleValue)) {
throw context.runtime.newFloatDomainError(doubleValue < 0 ? "-Infinity" : "Infinity");
}
if (Double.isNaN(doubleValue)) {
throw context.runtime.newFloatDomainError("NaN");
}
MathContext mathContext = new MathContext(RubyFloat.DIG + 1, getRoundingMode(context.runtime));
return new RubyBigDecimal(context.runtime, new BigDecimal(doubleValue, mathContext));
}
if (value instanceof RubyRational) {
return div2Impl(context, ((RubyRational) value).getNumerator(), ((RubyRational) value).getDenominator(), this.value.precision() * BASE_FIG);
}
return getVpValue(context, value, must);
}
private static RubyBigDecimal getVpValue(ThreadContext context, IRubyObject value, boolean must) {
switch (((RubyBasicObject) value).getNativeClassIndex()) {
case BIGDECIMAL:
return (RubyBigDecimal) value;
case FIXNUM:
return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyFixnum) value, MathContext.UNLIMITED);
case BIGNUM:
return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyBignum) value, MathContext.UNLIMITED);
case FLOAT:
return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyFloat) value, new MathContext(RubyFloat.DIG));
case RATIONAL:
return newInstance(context, (RubyRational) value, new MathContext(RubyFloat.DIG));
}
return cannotBeCoerced(context, value, must);
}
@JRubyMethod(meta = true)
public static IRubyObject induced_from(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return getVpValue(context, arg, true);
}
private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyBigDecimal arg) {
return new RubyBigDecimal(runtime, (RubyClass) recv, arg.value, arg.zeroSign, arg.infinitySign, arg.isNaN);
}
private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyFixnum arg, MathContext mathContext) {
final long value = arg.getLongValue();
if (value == 0) return newZero(runtime, 1);
return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
}
private static RubyBigDecimal newInstance(ThreadContext context, RubyRational arg, MathContext mathContext) {
if (arg.getNumerator().isZero()) return newZero(context.runtime, 1);
BigDecimal num = toBigDecimal(arg.getNumerator());
BigDecimal den = toBigDecimal(arg.getDenominator());
BigDecimal value;
try {
value = num.divide(den, mathContext);
} catch (ArithmeticException e){
value = num.divide(den, MathContext.DECIMAL64);
}
return new RubyBigDecimal(context.runtime, value);
}
private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyFloat arg, MathContext mathContext) {
// precision can be no more than float digits
if (mathContext.getPrecision() > RubyFloat.DIG + 1) throw runtime.newArgumentError("precision too large");
RubyBigDecimal res = newFloatSpecialCases(runtime, arg);
if (res != null) return res;
return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(arg.getDoubleValue(), mathContext));
}
private static RubyBigDecimal newFloatSpecialCases(Ruby runtime, RubyFloat val) {
if (val.isNaN()) return newNaN(runtime);
if (val.isInfinite()) return newInfinity(runtime, val.getDoubleValue() == Double.POSITIVE_INFINITY ? 1 : -1);
if (val.isZero()) return newZero(runtime, Double.doubleToLongBits(val.getDoubleValue()) == NEGATIVE_ZERO_LONG_BITS ? -1 : 1);
return null;
}
private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyBignum arg, MathContext mathContext) {
final BigInteger value = arg.getBigIntegerValue();
if (value.equals(BigInteger.ZERO)) return newZero(runtime, 1);
return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
}
private static IRubyObject newInstance(ThreadContext context, RubyClass recv, RubyString arg, MathContext mathContext, boolean strict, boolean exception) {
// Convert String to Java understandable format (for BigDecimal).
char[] str = arg.decodeString().toCharArray();
int s = 0; int e = str.length - 1;
if (e == 0) {
switch (str[0]) {
case '0':
return newZero(context.runtime, 1);
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return new RubyBigDecimal(context.runtime, recv, BigDecimal.valueOf(str[0] - '0'));
}
}
// 0. toString().trim() :
while (s <= e && str[s] <= ' ') s++; // l-trim
while (s <= e && str[e] <= ' ') e--; // r-trim
int sign = 1;
switch ( s <= e ? str[s] : ' ' ) {
case '_' :
if (!strict) return context.nil;
throw invalidArgumentError(context, arg);
case 'N' :
if ( contentEquals("NaN", str, s, e) ) return newNaN(context.runtime);
break;
case 'I' :
if ( contentEquals("Infinity", str, s, e) ) return newInfinity(context.runtime, 1);
break;
case '-' :
if ( contentEquals("-Infinity", str, s, e) ) return newInfinity(context.runtime, -1);
sign = -1;
break;
case '+' :
if ( contentEquals("+Infinity", str, s, e) ) return newInfinity(context.runtime, +1);
break;
}
int i = s; int off = 0; boolean dD = false;
int exp = -1; int lastSign = -1;
// 1. MRI allows d and D as exponent separators
// 2. MRI allows underscores anywhere
loop: while (i + off <= e) {
switch (str[i + off]) {
case 'd': case 'D': // replaceFirst("[dD]", "E")
if (dD) {
e = i - 1; continue; // not first - (trailing) junk
}
else {
str[i] = 'E'; dD = true;
if (exp == -1) exp = i;
else {
e = i - 1; continue; // (trailing) junk - DONE
}
i++; continue;
}
case '_':
if ((i + off) == e || Character.isDigit(str[i + off + 1])) {
str[i] = str[i + off];
off++;
continue;
}
if (!strict) {
e = i + off;
break loop;
}
throw invalidArgumentError(context, arg);
// 3. MRI ignores the trailing junk
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
break;
case '-': case '+':
lastSign = i; break;
case 'e': case 'E':
if (exp == -1) exp = i;
else {
e = i - 1; continue; // (trailing) junk - DONE
}
break;
default : // (trailing) junk - DONE
e = i - 1; continue;
}
str[i] = str[i+off];
i++;
}
// scan remaining chars and error if too much junk left
i = e + 1;
if (i < str.length) {
while (i < str.length && Character.isWhitespace(str[i++]));
if (i < str.length && strict) {
throw invalidArgumentError(context, arg);
}
}
e -= off;
if ( exp != -1 ) {
if (exp == e || (exp + 1 == e && (str[exp + 1] == '-' || str[exp + 1] == '+'))) {
if (!strict) return context.nil;
throw invalidArgumentError(context, arg);
}
else if (isExponentOutOfRange(str, exp + 1, e)) {
// Handle infinity (Integer.MIN_VALUE + 1) < expValue < Integer.MAX_VALUE
if (isZeroBase(str, s, exp)) return newZero(context.runtime, sign); // unless its a HUGE zero
return newInfinity(context.runtime, sign);
}
}
else if ( lastSign > s ) {
e = lastSign - 1; // ignored tail junk e.g. "5-6" -> "-6"
}
BigDecimal decimal;
try {
decimal = new BigDecimal(str, s, e - s + 1, mathContext);
}
catch (ArithmeticException ex) {
return checkOverUnderFlow(context.runtime, ex, false, strict, exception);
}
catch (NumberFormatException ex) {
return handleInvalidArgument(context, arg, strict, exception);
}
// MRI behavior: -0 and +0 are two different things
if (decimal.signum() == 0) return newZero(context.runtime, sign);
return new RubyBigDecimal(context.runtime, recv, decimal);
}
private static IRubyObject handleInvalidArgument(ThreadContext context, RubyString arg, boolean strict, boolean exception) {
if (!strict) {
return newZero(context.runtime, 1);
}
if (!exception) {
return context.nil;
}
throw invalidArgumentError(context, arg);
}
private static RaiseException invalidArgumentError(ThreadContext context, RubyString arg) {
return context.runtime.newArgumentError("invalid value for BigDecimal(): \"" + arg + "\"");
}
private static boolean contentEquals(final String str1, final char[] str2, final int s2, final int e2) {
final int len = str1.length();
if (len == e2 - s2 + 1) {
for (int i=0; i<len; i++) {
if (str1.charAt(i) != str2[s2+i]) return false;
}
return true;
}
return false;
}
private static boolean isZeroBase(final char[] str, final int off, final int end) {
for (int i=off; i<end; i++) {
if (str[i] != '0') return false;
}
return true;
}
private static boolean isExponentOutOfRange(final char[] str, final int off, final int end) {
int num = 0;
int sign = 1;
final char ch0 = str[off];
if (ch0 == '-') {
sign = -1;
} else if (ch0 != '+') {
num = '0' - ch0;
}
int i = off + 1;
final int max = (sign == 1) ? -Integer.MAX_VALUE : Integer.MIN_VALUE + 1;
final int multmax = max / 10;
while (i <= end) {
int d = str[i++] - '0';
if (num < multmax) {
return true;
}
num *= 10;
if (num < (max + d)) {
return true;
}
num -= d;
}
return false;
}
@Deprecated
public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
final ThreadContext context = recv.getRuntime().getCurrentContext();
switch (args.length) {
case 1: return newInstance(context, recv, args[0]);
case 2: return newInstance(context, recv, args[0], args[1]);
}
throw new IllegalArgumentException("unexpected argument count: " + args.length);
}
@Deprecated // no to be used in user-lang
@JRubyMethod(name = "new", meta = true)
public static IRubyObject new_(ThreadContext context, IRubyObject recv, IRubyObject arg) {
context.runtime.getWarnings().warn(IRubyWarnings.ID.DEPRECATED_METHOD, "BigDecimal.new is deprecated; use BigDecimal() method instead.");
return BigDecimalKernelMethods.newBigDecimal(context, recv, arg);
}
@Deprecated // no to be used in user-lang
@JRubyMethod(name = "new", meta = true)
public static IRubyObject new_(ThreadContext context, IRubyObject recv, IRubyObject arg, IRubyObject mathArg) {
context.runtime.getWarnings().warn(IRubyWarnings.ID.DEPRECATED_METHOD, "BigDecimal.new is deprecated; use BigDecimal() method instead.");
return BigDecimalKernelMethods.newBigDecimal(context, recv, arg, mathArg);
}
@Deprecated // no to be used in user-lang
@JRubyMethod(name = "new", meta = true)
public static IRubyObject new_(ThreadContext context, IRubyObject recv, IRubyObject arg, IRubyObject mathArg, IRubyObject opts) {
context.runtime.getWarnings().warn(IRubyWarnings.ID.DEPRECATED_METHOD, "BigDecimal.new is deprecated; use BigDecimal() method instead.");
return BigDecimalKernelMethods.newBigDecimal(context, recv, arg, mathArg, opts);
}
public static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return (RubyBigDecimal) newInstance(context, recv, arg, true, true);
}
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject arg, boolean strict, boolean exception) {
switch (((RubyBasicObject) arg).getNativeClassIndex()) {
case RATIONAL:
return handleMissingPrecision(context, "Rational", strict, exception);
case FLOAT:
RubyBigDecimal res = newFloatSpecialCases(context.runtime, (RubyFloat) arg);
if (res != null) return res;
return handleMissingPrecision(context, "Float", strict, exception);
case FIXNUM:
return newInstance(context.runtime, recv, (RubyFixnum) arg, MathContext.UNLIMITED);
case BIGNUM:
return newInstance(context.runtime, recv, (RubyBignum) arg, MathContext.UNLIMITED);
case BIGDECIMAL:
return newInstance(context.runtime, recv, (RubyBigDecimal) arg);
}
IRubyObject maybeString = arg.checkStringType();
if (maybeString.isNil()) {
if (!strict) return newZero(context.runtime, 1);
if (!exception) return context.nil;
throw context.runtime.newTypeError("no implicit conversion of " + arg.inspect() + "into to String");
}
return newInstance(context, (RubyClass) recv, maybeString.convertToString(), MathContext.UNLIMITED, strict, exception);
}
private static IRubyObject handleMissingPrecision(ThreadContext context, String name, boolean strict, boolean exception) {
if (!strict) return newZero(context.runtime, 1);
if (!exception) return context.nil;
throw context.runtime.newArgumentError("can't omit precision for a " + name + ".");
}
public static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, IRubyObject arg, IRubyObject mathArg) {
return (RubyBigDecimal) newInstance(context, recv, arg, mathArg, true, true);
}
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject arg, IRubyObject mathArg, boolean strict, boolean exception) {
int digits = (int) mathArg.convertToInteger().getLongValue();
if (digits < 0) {
if (!strict) return newZero(context.runtime, 1);
if (!exception) return context.nil;
throw context.runtime.newArgumentError("argument must be positive");
}
MathContext mathContext = new MathContext(digits);
switch (((RubyBasicObject) arg).getNativeClassIndex()) {
case RATIONAL:
return newInstance(context, (RubyRational) arg, mathContext);
case FLOAT:
return newInstance(context.runtime, recv, (RubyFloat) arg, mathContext);
case FIXNUM:
return newInstance(context.runtime, recv, (RubyFixnum) arg, mathContext);
case BIGNUM:
return newInstance(context.runtime, recv, (RubyBignum) arg, mathContext);
case BIGDECIMAL:
return newInstance(context.runtime, recv, (RubyBigDecimal) arg);
}
return newInstance(context, (RubyClass) recv, arg.convertToString(), MathContext.UNLIMITED, strict, exception);
}
private static RubyBigDecimal newZero(final Ruby runtime, final int sign) {
return new RubyBigDecimal(runtime, BigDecimal.ZERO, 0, sign < 0 ? -1 : 1);
}
private static RubyBigDecimal newNaN(final Ruby runtime) {
if ( isNaNExceptionMode(runtime) ) {
throw newNaNFloatDomainError(runtime);
}
return new RubyBigDecimal(runtime, BigDecimal.ZERO, true);
}
private static RaiseException newNaNFloatDomainError(final Ruby runtime) {
return runtime.newFloatDomainError("Computation results to 'NaN'(Not a Number)");
}
private static RubyBigDecimal newInfinity(final Ruby runtime, final int sign) {
if ( isInfinityExceptionMode(runtime) ) {
throw newInfinityFloatDomainError(runtime, sign);
}
return new RubyBigDecimal(runtime, BigDecimal.ZERO, sign < 0 ? -1 : 1, 0);
}
private static RaiseException newInfinityFloatDomainError(final Ruby runtime, final int sign) {
return runtime.newFloatDomainError("Computation results to " + (sign < 0 ? "'-Infinity'" : "'Infinity'"));
}
private RubyBigDecimal setResult() {
return setResult(0);
}
private RubyBigDecimal setResult(int prec) {
if (prec == 0) prec = getPrecLimit(getRuntime());
int exponent;
if (prec > 0 && this.value.scale() > (prec - (exponent = getExponent()))) {
this.value = this.value.setScale(prec - exponent, RoundingMode.HALF_UP);
this.absStripTrailingZeros = null;
}
return this;
}
private transient BigDecimal absStripTrailingZeros; // cached re-used 'normalized' value
private BigDecimal absStripTrailingZeros() {
BigDecimal absStripTrailingZeros = this.absStripTrailingZeros;
if (absStripTrailingZeros == null) {
return this.absStripTrailingZeros = value.abs().stripTrailingZeros();
}
return absStripTrailingZeros;
}
@Override
@JRubyMethod
public RubyFixnum hash() {
return getRuntime().newFixnum(absStripTrailingZeros().hashCode() * value.signum());
}
@Override
@JRubyMethod(name = "initialize_copy", visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(IRubyObject original) {
if (this == original) return this;
checkFrozen();
if (!(original instanceof RubyBigDecimal)) {
throw getRuntime().newTypeError("wrong argument class");
}
RubyBigDecimal orig = (RubyBigDecimal) original;
this.isNaN = orig.isNaN;
this.infinitySign = orig.infinitySign;
this.zeroSign = orig.zeroSign;
this.value = orig.value;
return this;
}
@JRubyMethod(name = {"%", "modulo"}, required = 1)
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
RubyBigDecimal val = getVpValueWithPrec(context, other, false);
if (val == null) return callCoerced(context, sites(context).op_mod, other, true);
if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) return newNaN(context.runtime);
if (val.isZero()) throw context.runtime.newZeroDivisionError();
if (isInfinity()) return newNaN(context.runtime);
if (val.isInfinity()) return this;
if (isZero()) return newZero(context.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(context.runtime, modulo).setResult();
}
@Deprecated
public IRubyObject op_mod19(ThreadContext context, IRubyObject arg) {
return op_mod(context, arg);
}
@Override
@JRubyMethod(name = "remainder", required = 1)
public IRubyObject remainder(ThreadContext context, IRubyObject arg) {
return remainderInternal(context, getVpValueWithPrec(context, arg, false), arg);
}
@Deprecated
public IRubyObject remainder19(ThreadContext context, IRubyObject arg) {
return remainder(context, arg);
}
private IRubyObject remainderInternal(ThreadContext context, RubyBigDecimal val, IRubyObject arg) {
if (isInfinity() || isNaN()) return newNaN(context.runtime);
if (val == null) return callCoerced(context, sites(context).remainder, arg, true);
if (val.isInfinity() || val.isNaN() || val.isZero()) return newNaN(context.runtime);
// Java and MRI definitions of remainder are the same.
return new RubyBigDecimal(context.runtime, value.remainder(val.value)).setResult();
}
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(ThreadContext context, IRubyObject arg) {
RubyBigDecimal val = getVpValueWithPrec(context, arg, false);
if (val == null) return callCoerced(context, sites(context).op_times, arg, true);
return multImpl(context.runtime, val);
}
@Deprecated
public IRubyObject op_mul19(ThreadContext context, IRubyObject arg) {
return op_mul(context, arg);
}
@JRubyMethod(name = "mult", required = 2)
public IRubyObject mult2(ThreadContext context, IRubyObject b, IRubyObject n) {
final int mx = getPrecisionInt(context.runtime, n);
if (mx == 0) return op_mul(context, b);
RubyBigDecimal val = getVpValueWithPrec(context, b, false);
if (val == null) { // TODO: what about n arg?
return callCoerced(context, sites(context).op_times, b, true);
}
return multImpl(context.runtime, val).setResult(mx);
}
private RubyBigDecimal multImpl(final Ruby runtime, RubyBigDecimal val) {
if ( isNaN() || val.isNaN() ) return newNaN(runtime);
if ( isZero() || val.isZero() ) {
if ((isInfinity() && val.isZero()) || (isZero() && val.isInfinity())) return newNaN(runtime);