-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathRubyFixnum.java
More file actions
1587 lines (1357 loc) · 53 KB
/
RubyFixnum.java
File metadata and controls
1587 lines (1357 loc) · 53 KB
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) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 David Corbin <dcorbin@users.sourceforge.net>
* Copyright (C) 2006 Antti Karanta <antti.karanta@napa.fi>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* 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;
import java.math.BigInteger;
import org.jcodings.specific.USASCIIEncoding;
import org.jruby.api.Convert;
import org.jruby.api.Create;
import org.jruby.api.JRubyAPI;
import org.jruby.compiler.Constantizable;
import org.jruby.runtime.Block;
import org.jruby.runtime.Builtins;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.JavaSites;
import org.jruby.runtime.Signature;
import org.jruby.runtime.SimpleHash;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.marshal.MarshalLoader;
import org.jruby.runtime.opto.OptoFactory;
import org.jruby.util.ConvertBytes;
import org.jruby.util.StringSupport;
import org.jruby.util.cli.Options;
import org.jruby.util.io.RubyInputStream;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.asFloat;
import static org.jruby.api.Convert.toInt;
import static org.jruby.api.Convert.toLong;
import static org.jruby.api.Create.newArray;
import static org.jruby.api.Create.newSharedString;
import static org.jruby.api.Create.newString;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.api.Error.zeroDivisionError;
import static org.jruby.util.Numeric.f_odd_p;
import static org.jruby.util.Numeric.int_pow;
/**
* Implementation of the Integer (Fixnum internal) class.
*/
public abstract class RubyFixnum extends RubyInteger implements Constantizable, Appendable, SimpleHash {
public static RubyClass createFixnumClass(ThreadContext context, RubyClass fixnum) {
var cache = context.runtime.fixnumCache;
for (int i = 0; i < cache.length; i++) {
cache[i] = newFixnumForCache(fixnum, i - CACHE_OFFSET);
}
return fixnum;
}
private static class LongFixnum extends RubyFixnum {
final long value;
public LongFixnum(RubyClass fixnum, long value) {
super(fixnum);
this.value = value;
}
@Override
public long getValue() {
return value;
}
}
private static class IntFixnum extends RubyFixnum {
final int value;
public IntFixnum(RubyClass fixnum, int value) {
super(fixnum);
this.value = value;
}
@Override
public long getValue() {
return value;
}
}
private static class ShortFixnum extends RubyFixnum {
final short value;
public ShortFixnum(RubyClass fixnum, short value) {
super(fixnum);
this.value = value;
}
@Override
public long getValue() {
return value;
}
}
private static class ByteFixnum extends RubyFixnum {
final byte value;
public ByteFixnum(RubyClass fixnum, byte value) {
super(fixnum);
this.value = value;
}
@Override
public long getValue() {
return value;
}
}
private static final int BIT_SIZE = 64;
public static final long SIGN_BIT = Long.MIN_VALUE;
public static final long MAX = Long.MAX_VALUE;
public static final long MIN = Long.MIN_VALUE;
private static final BigInteger MIN_NEGATED = BigInteger.valueOf(Long.MIN_VALUE).negate();
public static final long MAX_MARSHAL_FIXNUM = (1L << 30) - 1; // 0x3fff_ffff
public static final long MIN_MARSHAL_FIXNUM = - (1L << 30); // -0x4000_0000
public static final boolean USE_CACHE = Options.USE_FIXNUM_CACHE.load();
public static final int CACHE_OFFSET;
static {
int cacheRange = 0;
if (USE_CACHE) {
cacheRange = Options.FIXNUM_CACHE_RANGE.load();
if (cacheRange < 0) cacheRange = 0;
}
CACHE_OFFSET = cacheRange;
}
private static IRubyObject fixCoerce(ThreadContext context, IRubyObject x) {
do {
x = Convert.toInteger(context, x);
} while (!(x instanceof RubyFixnum) && !(x instanceof RubyBignum));
return x;
}
@Deprecated(since = "10.0.3.0", forRemoval = true)
public RubyFixnum(Ruby runtime) {
this(runtime, 0);
}
@Deprecated(since = "10.0.3.0", forRemoval = true)
public RubyFixnum(Ruby runtime, long value) {
super(runtime.getFixnum());
this.setFrozen(true);
}
private RubyFixnum(RubyClass klazz) {
super(klazz);
this.setFrozen(true);
}
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.FIXNUM;
}
/**
* @see org.jruby.compiler.Constantizable
*/
@Override
public Object constant() {
Object constant = null;
final long value = this.getValue();
if (value < CACHE_OFFSET && value >= -CACHE_OFFSET) {
Object[] fixnumConstants = metaClass.runtime.fixnumConstants;
constant = fixnumConstants[(int) value + CACHE_OFFSET];
if (constant == null) {
constant = OptoFactory.newConstantWrapper(IRubyObject.class, this);
fixnumConstants[(int) value + CACHE_OFFSET] = constant;
}
}
return constant;
}
/**
* short circuit for Fixnum key comparison
*/
@Override
public final boolean eql(IRubyObject other) {
return other instanceof RubyFixnum && getValue() == ((RubyFixnum) other).getValue();
}
@Override
public IRubyObject equal_p(ThreadContext context, IRubyObject obj) {
long value = this.getValue();
if (fixnumable(value)) return asBoolean(context, this == obj || eql(obj));
return super.equal_p(context, obj);
}
/**
* Determine whether the given long value is in fixnum range.
*
* @param value the value in question
* @return true if the value is in fixnum range, false otherwise
*/
private static boolean fixnumable(long value) {
return value <= Long.MAX_VALUE / 2 && value >= Long.MIN_VALUE / 2;
}
@Override
public boolean isImmediate() {
return true;
}
public RubyClass singletonClass(ThreadContext context) {
throw typeError(context, "can't define singleton");
}
@Override
public Class<?> getJavaClass() {
return long.class;
}
@Override
@JRubyAPI
public BigInteger asBigInteger(ThreadContext context) {
return BigInteger.valueOf(getValue());
}
@Override
@JRubyAPI
public double asDouble(ThreadContext context) {
return getValue();
}
@Override
@JRubyAPI
public int asInt(ThreadContext context) { return (int) getValue(); }
@Override
@JRubyAPI
public long asLong(ThreadContext context) {
return getValue();
}
@Override
@Deprecated(since = "10.0.0.0")
public double getDoubleValue() {
return getValue();
}
@Override
@Deprecated(since = "10.0.0.0")
public long getLongValue() {
return getValue();
}
/**
* When you know you are working directly with a Fixnum you can get
* the long value it represents without using {@link org.jruby.RubyNumeric#asLong(ThreadContext)}.
*
* @return the long value
*/
@JRubyAPI
public abstract long getValue();
@Override
@JRubyAPI
public int signum(ThreadContext context) { return Long.signum(getValue()); }
@Override
public RubyInteger negate(ThreadContext context) {
return negate(context, getValue());
}
public static RubyFixnum newFixnum(Ruby runtime, long value) {
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
// long is never in cache range
return new LongFixnum(runtime.getInteger(), value);
}
return newFixnum(runtime, (int) value);
}
public static RubyFixnum newFixnum(Ruby runtime, int value) {
if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) {
// integer is never in cache range
// disabled to avoid polymorphism and because it doesn't save size (https://github.com/jruby/jruby/pull/9379)
// return new IntFixnum(runtime.getInteger(), value);
return new LongFixnum(runtime.getInteger(), value);
}
return newFixnum(runtime, (short) value);
}
public static RubyFixnum newFixnum(Ruby runtime, short value) {
if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) {
return USE_CACHE && isInCacheRange(value) ? cachedFixnum(runtime, value) : new ShortFixnum(runtime.getInteger(), value);
}
return newFixnum(runtime, (byte) value);
}
public static RubyFixnum newFixnum(Ruby runtime, byte value) {
// using ShortFixnum until there's value in using ByteFixnum
return USE_CACHE && isInCacheRange(value) ? cachedFixnum(runtime, value) : new ShortFixnum(runtime.getInteger(), value);
}
private static RubyFixnum newFixnumForCache(RubyClass fixnum, int value) {
if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) {
// disabled to avoid polymorphism and because it doesn't save size (https://github.com/jruby/jruby/pull/9379)
//return new IntFixnum(fixnum, value);
return new LongFixnum(fixnum, value);
} else if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) {
return new ShortFixnum(fixnum, (short) value);
}
// using ShortFixnum until there's value in using ByteFixnum
return new ShortFixnum(fixnum, (byte) value);
}
private static boolean isInCacheRange(int value) {
return value <= CACHE_OFFSET - 1 && value >= -CACHE_OFFSET;
}
private static RubyFixnum cachedFixnum(Ruby runtime, int value) {
// This truncates to int but we determine above that it's in cache range
return runtime.fixnumCache[value + CACHE_OFFSET];
}
public static RubyFixnum zero(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 0 ? runtime.fixnumCache[CACHE_OFFSET] : new ShortFixnum(runtime.getInteger(), (byte) 0);
}
public static RubyFixnum one(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 1 ? runtime.fixnumCache[CACHE_OFFSET + 1] : new ShortFixnum(runtime.getInteger(), (byte) 1);
}
public static RubyFixnum two(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 2 ? runtime.fixnumCache[CACHE_OFFSET + 2] : new ShortFixnum(runtime.getInteger(), (byte) 2);
}
public static RubyFixnum three(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 3 ? runtime.fixnumCache[CACHE_OFFSET + 3] : new ShortFixnum(runtime.getInteger(), (byte) 3);
}
public static RubyFixnum four(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 4 ? runtime.fixnumCache[CACHE_OFFSET + 4] : new ShortFixnum(runtime.getInteger(), (byte) 4);
}
public static RubyFixnum five(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return CACHE_OFFSET > 5 ? runtime.fixnumCache[CACHE_OFFSET + 5] : new ShortFixnum(runtime.getInteger(), (byte) 5);
}
public static RubyFixnum minus_one(Ruby runtime) {
// using ShortFixnum until there's value in using ByteFixnum
return -CACHE_OFFSET <= -1 ? runtime.fixnumCache[CACHE_OFFSET - 1] : new ShortFixnum(runtime.getInteger(), (byte) -1);
}
public RubyFixnum hash(ThreadContext context) {
return asFixnum(context, longHashCode());
}
@Override
public final int hashCode() {
return (int) longHashCode();
}
@Override
public long longHashCode() {
return Helpers.multAndMix(Ruby.getHashSeed0(), getValue());
}
/* ================
* Instance Methods
* ================
*/
@Override
public IRubyObject times(ThreadContext context, Block block) {
if (block.isGiven()) {
final long value = this.getValue();
boolean checkArity = block.type.checkArity;
if (block.getSignature() == Signature.NO_ARGUMENTS) {
if (checkArity) {
// must pass arg
final IRubyObject nil = context.nil;
for (long i = 0; i < value; i++) {
block.yieldSpecific(context, nil);
}
} else {
// no arg needed
for (long i = 0; i < value; i++) {
block.yieldSpecific(context);
}
}
} else {
for (long i = 0; i < value; i++) {
block.yield(context, asFixnum(context, i));
}
}
return this;
}
return RubyEnumerator.enumeratorizeWithSize(context, this, "times", RubyInteger::timesSize);
}
/** rb_fix_ceil
*
*/
@Override
public IRubyObject ceil(ThreadContext context, IRubyObject arg){
long ndigits = toLong(context, arg);
if (ndigits >= 0) return this;
RubyNumeric f = int_pow(context, 10, -ndigits);
if (f instanceof RubyFixnum fixnum) {
long x = getValue(), y = fixnum.getValue();
boolean neg = x < 0;
if (neg) x = -x;
else x += y - 1;
x = (x / y) * y;
if (neg) x = -x;
return asFixnum(context, x);
}
return integerCeil(context, f);
}
/** rb_fix_floor
*
*/
@Override
public IRubyObject floor(ThreadContext context, IRubyObject arg){
long ndigits = toLong(context, arg);
if (ndigits >= 0) return this;
RubyInteger f = (RubyInteger) int_pow(context, 10, -ndigits);
if (f instanceof RubyFixnum fixnum) {
long x = getValue(), y = fixnum.getValue();
boolean neg = x < 0;
if (neg) x = -x + y - 1;
x = x / y * y;
if (neg) x = -x;
return asFixnum(context, x);
}
return integerFloor(context, f);
}
/** rb_fix_truncate
*
*/
@Override
public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
long self = this.getValue();
if (self > 0) {
return floor(context, arg);
} else if (self < 0) {
return ceil(context, arg);
} else {
return this;
}
}
/** rb_fix_digits
*
*/
@Override
public RubyArray digits(ThreadContext context, IRubyObject baseArg) {
long value = this.getValue();
if (value < 0) throw context.runtime.newMathDomainError("out of domain");
var base = Convert.toInteger(context, baseArg);
if (base instanceof RubyBignum bigBase) {
return RubyBignum.newBignum(context.runtime, value).digits(context, bigBase);
}
long longBase = ((RubyFixnum) base).getValue();
if (longBase < 0) throw argumentError(context, "negative radix");
if (longBase < 2) throw argumentError(context, "invalid radix: " + longBase);
if (value == 0) return newArray(context, asFixnum(context, 0));
RubyArray<?> res = Create.allocArray(context, (int) (Math.log(value) / Math.log(longBase)) + 1);
do {
res.append(context, asFixnum(context, value % longBase));
value /= longBase;
} while (value > 0);
return res;
}
/** fix_to_s
*
*/
@Deprecated(since = "10.0.0.0")
public RubyString to_s(IRubyObject[] args) {
var context = getCurrentContext();
return switch (args.length) {
case 0 -> to_s(context);
case 1 -> to_s(context, args[0]);
default -> throw argumentError(context, args.length, 1);
};
}
@Override
public RubyString to_s(ThreadContext context) {
return longToString(context, getValue(), 10);
}
@Override
public RubyString to_s(ThreadContext context, IRubyObject arg0) {
int base = toInt(context, arg0);
if (base < 2 || base > 36) throw argumentError(context, "illegal radix " + base);
return longToString(context, getValue(), base);
}
private RubyString longToString(ThreadContext context, long value, int base) {
return base == 10 && value >= -256 && value < 256 ?
newSharedString(context, ConvertBytes.byteToSharedByteList((short) value), USASCIIEncoding.INSTANCE) :
newString(context, ConvertBytes.longToByteList(value, base), USASCIIEncoding.INSTANCE);
}
/** fix_uminus
*
*/
@Override
public IRubyObject op_uminus(ThreadContext context) {
return negate(context, getValue());
}
private static RubyInteger negate(ThreadContext context, final long value) {
return value == MIN ?
RubyBignum.newBignum(context.runtime, MIN_NEGATED) :
asFixnum(context, -value);
}
/** fix_plus
*
*/
@Override
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
// TODO: Add builtin check for production use:
// if (!Builtins.checkIntegerPlus(context)) {
// return RuntimeHelpers.invokeSuper(context, this, other, Block.NULL_BLOCK);
// }
// This provides 5x faster method dispatch when Integer#+ is not redefined.
if (other instanceof RubyFixnum fixnum) {
return op_plus(context, fixnum.getValue());
}
return addOther(context, other);
}
@Override
public IRubyObject op_plus(ThreadContext context, long other) {
long value = this.getValue();
long result = value + other;
if (addOverflowed(other, value, result)) {
return addAsBignum(context, value, other);
}
return asFixnum(context, result);
}
private static boolean addOverflowed(long other, long value, long result) {
return ((value ^ result) & (other ^ result)) < 0;
}
public IRubyObject op_plus(ThreadContext context, double other) {
return asFloat(context, (double) getValue() + other);
}
public IRubyObject op_plus_one(ThreadContext context) {
long value = this.getValue();
if (value == MAX) {
return addAsBignum(context, value, BigInteger.ONE);
}
return asFixnum(context, value + 1);
}
public IRubyObject op_plus_two(ThreadContext context) {
long value = this.getValue();
if (value >= MAX - 2) {
return addAsBignum(context, value, BigInteger.TWO);
}
return asFixnum(context, value + 2);
}
private static RubyInteger addAsBignum(ThreadContext context, long value, long other) {
return RubyBignum.bignorm(context.runtime, BigInteger.valueOf(value).add(BigInteger.valueOf(other)));
}
private static RubyInteger addAsBignum(ThreadContext context, long value, BigInteger other) {
return RubyBignum.bignorm(context.runtime, BigInteger.valueOf(value).add(other));
}
private IRubyObject addOther(ThreadContext context, IRubyObject other) {
return switch (other) {
case RubyBignum bignum -> bignum.op_plus(context, getValue());
case RubyFloat flote -> op_plus(context, flote.value);
default -> coerceBin(context, sites(context).op_plus, other);
};
}
/** fix_minus
*
*/
@Override
public IRubyObject op_minus(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum fixnum) {
return op_minus(context, fixnum.getValue());
}
return subtractOther(context, other);
}
@Override
public IRubyObject op_minus(ThreadContext context, long other) {
long value = this.getValue();
long result = value - other;
if (((value ^ other) & (value ^ result)) < 0) {
return subtractAsBignum(context, other);
}
return asFixnum(context, result);
}
public IRubyObject op_minus(ThreadContext context, double other) {
return asFloat(context, (double) getValue() - other);
}
/**
* @param context
* @return RubyInteger
*/
public IRubyObject op_minus_one(ThreadContext context) {
long value = this.getValue();
if (value == MIN) {
return subtractAsBignum(context, BigInteger.ONE);
}
return asFixnum(context, value - 1);
}
/**
* @param context
* @return RubyInteger
*/
public IRubyObject op_minus_two(ThreadContext context) {
long value = this.getValue();
if (value <= MIN + 1) {
return subtractAsBignum(context, 2);
}
return asFixnum(context, value - 2);
}
private RubyInteger subtractAsBignum(ThreadContext context, long other) {
return RubyBignum.bignorm(context.runtime, BigInteger.valueOf(getValue()).subtract(BigInteger.valueOf(other)));
}
private RubyInteger subtractAsBignum(ThreadContext context, BigInteger other) {
return RubyBignum.bignorm(context.runtime, BigInteger.valueOf(getValue()).subtract(other));
}
private IRubyObject subtractOther(ThreadContext context, IRubyObject other) {
return switch(other) {
case RubyBignum bignum -> RubyBignum.bignorm(context.runtime, BigInteger.valueOf(getValue()).subtract(((RubyBignum) other).value));
case RubyFloat flote -> op_minus(context, flote.value);
default -> coerceBin(context, sites(context).op_minus, other);
};
}
/** fix_mul
*
*/
@Override
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
return other instanceof RubyFixnum fixnum ?
op_mul(context, fixnum.getValue()) :
multiplyOther(context, other);
}
private IRubyObject multiplyOther(ThreadContext context, IRubyObject other) {
if (other instanceof RubyBignum bignum) return bignum.op_mul(context, this.getValue());
if (other instanceof RubyFloat flote) return op_mul(context, flote.value);
return coerceBin(context, sites(context).op_times, other);
}
@Override
public IRubyObject op_mul(ThreadContext context, long other) {
long value = this.getValue();
long low = value * other;
long high = Math.multiplyHigh(value, other);
if ((high == 0 && low >= 0) // result is zero or positive and < MAX
|| (high == -1 && low < 0)) { // result is negative and >= MIN
return asFixnum(context, low);
}
// overflow, use Bignum
return multiplyAsBignum(context, value, other);
}
private static RubyInteger multiplyAsBignum(ThreadContext context, long value, long other) {
return RubyBignum.bignorm(context.runtime, BigInteger.valueOf(value).multiply(BigInteger.valueOf(other)));
}
public IRubyObject op_mul(ThreadContext context, double other) {
return context.runtime.newFloat((double) getValue() * other);
}
/** fix_div
* here is terrible MRI gotcha:
* 1.div 3.0$ -> 0
* 1 / 3.0 $ -> 0.3333333333333333
*
* MRI is also able to do it in one place by looking at current frame in rb_num_coerce_bin:
* rb_funcall(x, ruby_frame->orig_func, 1, y);
*
* also note that RubyFloat doesn't override Numeric.div
*/
@Override
public IRubyObject idiv(ThreadContext context, IRubyObject other) {
checkZeroDivisionError(context, other);
if (other instanceof RubyFixnum) {
return idivLong(context, getValue(), ((RubyFixnum) other).getValue());
}
return coerceBin(context, sites(context).div, other);
}
@Override
public IRubyObject idiv(ThreadContext context, long other) {
return idivLong(context, getValue(), other);
}
@Override
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return idivLong(context, getValue(), ((RubyFixnum) other).getValue());
}
return coerceBin(context, sites(context).op_quo, other);
}
public IRubyObject op_div(ThreadContext context, long other) {
return idivLong(context, getValue(), other);
}
@Override
public RubyBoolean odd_p(ThreadContext context) {
return (getValue() & 1) != 0 ? context.tru : context.fals;
}
@Override
public RubyBoolean even_p(ThreadContext context) {
return (getValue() & 1) == 0 ? context.tru : context.fals;
}
public IRubyObject pred(ThreadContext context) {
return op_minus_one(context);
}
public IRubyObject idiv(ThreadContext context, IRubyObject other, CallSite site) {
if (other instanceof RubyFixnum) {
return idivLong(context, getValue(), ((RubyFixnum) other).getValue());
}
return coerceBin(context, site, other);
}
private RubyInteger idivLong(ThreadContext context, long x, long y) {
if (y == 0) throw context.runtime.newZeroDivisionError();
long result;
if (y > 0) {
if (x >= 0) {
result = x / y; // x >= 0, y > 0;
} else {
result = (x + 1) / y - 1; // x < 0, y > 0; // OOPS "=" was omitted
}
} else if (x > 0) {
result = (x - 1) / y - 1; // x > 0, y < 0;
} else if (y == -1) {
if (x == MIN) return RubyBignum.newBignum(context.runtime, MIN_NEGATED);
result = -x;
} else {
result = x / y; // x <= 0, y < 0;
}
return asFixnum(context, result);
}
/** fix_mod
*
*/
@Override
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return moduloFixnum(context, (RubyFixnum) other);
}
checkZeroDivisionError(context, other);
return coerceBin(context, sites(context).op_mod, other);
}
@Override
public IRubyObject op_mod(ThreadContext context, long other) {
return moduloFixnum(context, other);
}
@Override
public IRubyObject modulo(ThreadContext context, IRubyObject other) {
return op_mod(context, other);
}
@Override
IRubyObject modulo(ThreadContext context, long other) {
return op_mod(context, other);
}
private IRubyObject moduloFixnum(ThreadContext context, RubyFixnum other) {
return moduloFixnum(context, other.getValue());
}
private IRubyObject moduloFixnum(ThreadContext context, long other) {
// Java / and % are not the same as ruby
long x = getValue();
long y = other;
if (y == 0) throw context.runtime.newZeroDivisionError();
long mod = x % y;
if (mod < 0 && y > 0 || mod > 0 && y < 0) {
mod += y;
}
return asFixnum(context, mod);
}
/** fix_divmod
*
*/
@Override
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return divmodFixnum(context, (RubyFixnum) other);
}
checkZeroDivisionError(context, other);
return coerceBin(context, sites(context).divmod, other);
}
private IRubyObject divmodFixnum(ThreadContext context, RubyFixnum other) {
final long x = this.getValue();
final long y = other.getValue();
if (y == 0) throw context.runtime.newZeroDivisionError();
long mod; final RubyInteger integerDiv;
if (y == -1) {
if (x == MIN) {
integerDiv = RubyBignum.newBignum(context.runtime, MIN_NEGATED);
} else {
integerDiv = Convert.asFixnum(context, -x);
}
mod = 0;
} else {
long div = x / y;
// Next line avoids using the slow: mod = x % y,
// and I believe there is no possibility of integer overflow.
mod = x - y * div;
if (mod < 0 && y > 0 || mod > 0 && y < 0) {
div -= 1; // horrible sudden thought: might this overflow? probably not?
mod += y;
}
integerDiv = Convert.asFixnum(context, div);
}
IRubyObject fixMod = Convert.asFixnum(context, mod);
return newArray(context, integerDiv, fixMod);
}
/** fix_pow
*
*/
@Override
public IRubyObject op_pow(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return powerFixnum(context, (RubyFixnum) other);
} else if (other instanceof RubyBignum) {
return powerOther(context, other);
} else if (other instanceof RubyFloat flote) {
double d_other = flote.asDouble(context);
if (getValue() < 0 && (d_other != Math.round(d_other))) {
RubyComplex complex = RubyComplex.newComplexRaw(context.runtime, this);
return numFuncall(context, complex, sites(context).op_exp_complex, other);
}
}
return coerceBin(context, sites(context).op_exp, other);
}
public IRubyObject op_pow(ThreadContext context, long other) {
return powerFixnum(context, asFixnum(context, other));
}
private IRubyObject powerOther(ThreadContext context, IRubyObject other) {
final Ruby runtime = context.runtime;
final long a = this.getValue();
if (other instanceof RubyBignum) {
if (a == 1) return RubyFixnum.one(runtime);
if (a == -1) {
return ((RubyBignum) other).even_p(context).isTrue() ? RubyFixnum.one(runtime) : RubyFixnum.minus_one(runtime);
}
if (sites(context).op_lt_bignum.call(context, other, other, RubyFixnum.zero(runtime)).isTrue()) {
RubyRational rational = RubyRational.newRationalRaw(runtime, this);
return numFuncall(context, rational, sites(context).op_exp_rational, other);
}
if (a == 0) return RubyFixnum.zero(runtime);
return RubyBignum.newBignum(runtime, RubyBignum.long2big(a)).op_pow(context, other);
}
if (other instanceof RubyFloat) {
double b = ((RubyFloat) other).value;
if (b == 0.0 || a == 1) return runtime.newFloat(1.0);
if (a == 0) return runtime.newFloat(b < 0 ? 1.0 / 0.0 : 0.0);
return RubyFloat.newFloat(runtime, Math.pow(a, b));
}
return coerceBin(context, sites(context).op_exp, other);
}
// MRI: fix_pow
private RubyNumeric powerFixnum(ThreadContext context, RubyFixnum other) {
long a = getValue();
long b = other.getValue();
if (a == 1) return asFixnum(context, 1);
if (a == -1) return asFixnum(context, (b % 2) != 0 ? -1 : 1);
if (b < 0) return fixPowInverted(context, -b);
if (b == 0) return asFixnum(context, 1);
if (b == 1) return this;
if (a == 0) return asFixnum(context, 0);
return int_pow(context, a, b);
}
// MRI: fix_pow_inverted
private RubyNumeric fixPowInverted(ThreadContext context, long minusb) {
if (getValue() == 0) {
throw zeroDivisionError(context);
} else {
IRubyObject y = op_pow(context, minusb); // rb_int_pow but we know we are a fixnum
if (y instanceof RubyFloat flote) {
double d = Math.pow((double) getValue(), flote.value);
return asFloat(context, 1.0 / d);
} else {
return RubyRational.newRationalRaw(context.runtime, asFixnum(context, 1), y);
}
}
}
// MRI: int_pow_tmp1
protected IRubyObject intPowTmp1(ThreadContext context, RubyInteger y, long mm, boolean negaFlg) {
long xx = this.getValue();
long tmp = 1L;
long yy;
var one = asFixnum(context, 1);
for (/*NOP*/; !(y instanceof RubyFixnum); y = (RubyInteger) sites(context).op_rshift.call(context, y, y, one)) {
if (f_odd_p(context, y)) tmp = (tmp * xx) % mm;
xx = (xx * xx) % mm;
}
for (yy = y.asLong(context); yy != 0L; yy >>= 1L) {
if ((yy & 1L) != 0L) tmp = (tmp * xx) % mm;
xx = (xx * xx) % mm;
}
if (negaFlg && (tmp != 0)) tmp -= mm;
return asFixnum(context, tmp);
}