Skip to content

Commit cc2b0cd

Browse files
andrykonchineregon
authored andcommitted
[GR-18163] Use Ruby implementation of Integer#pow for int modulus values
PullRequest: truffleruby/4275
2 parents 954bfcf + ad937b2 commit cc2b0cd

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

src/main/ruby/truffleruby/core/integer.rb

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -129,19 +129,22 @@ def nobits?(mask)
129129
(self & mask) == 0
130130
end
131131

132-
def pow(e, m = undefined)
133-
return self ** e if Primitive.undefined?(m)
132+
def pow(exponent, modulus = undefined)
133+
return self ** exponent if Primitive.undefined?(modulus)
134134

135-
raise TypeError, '2nd argument not allowed unless a 1st argument is integer' unless Primitive.is_a?(e, Integer)
136-
raise TypeError, '2nd argument not allowed unless all arguments are integers' unless Primitive.is_a?(m, Integer)
137-
raise RangeError, '1st argument cannot be negative when 2nd argument specified' if e.negative?
135+
raise TypeError, '2nd argument not allowed unless a 1st argument is integer' unless Primitive.is_a?(exponent, Integer)
136+
raise TypeError, '2nd argument not allowed unless all arguments are integers' unless Primitive.is_a?(modulus, Integer)
137+
raise RangeError, '1st argument cannot be negative when 2nd argument specified' if exponent.negative?
138138

139-
if Primitive.integer_fits_into_long?(m)
140-
Truffle::IntegerOperations.modular_exponentiation(self, e, m)
139+
# Ruby implementation is much faster than Java implementation for modulus <= 2^32,
140+
# and Java is much faster for modulus > 2^32.
141+
if Primitive.integer_fits_into_int?(modulus)
142+
Truffle::IntegerOperations.modular_exponentiation(self, exponent, modulus)
141143
else
142-
Primitive.mod_pow(self, e, m)
144+
Primitive.mod_pow(self, exponent, modulus)
143145
end
144146
end
147+
Truffle::Graal.always_split instance_method(:pow)
145148

146149
def times
147150
return to_enum(:times) { self } unless block_given?

src/main/ruby/truffleruby/core/truffle/integer_operations.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,6 @@ def self.modular_exponentiation(base, exponent, modulus)
6262
result -= modulus if negative
6363
result
6464
end
65+
Truffle::Graal.always_split method(:modular_exponentiation)
6566
end
6667
end

0 commit comments

Comments
 (0)