Skip to content

Commit

Permalink
Showing 3 changed files with 29 additions and 11 deletions.
2 changes: 0 additions & 2 deletions spec/truffle/tags/core/random/bytes_tags.txt

This file was deleted.

Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@
import org.jruby.truffle.Layouts;
import org.jruby.truffle.builtins.Primitive;
import org.jruby.truffle.builtins.PrimitiveArrayArgumentsNode;
import org.jruby.util.ByteList;
import org.jruby.util.Random;

import java.math.BigInteger;
@@ -106,6 +107,33 @@ public DynamicObject randomizerGenSeed(DynamicObject randomizerClass) {
}
}

@Primitive(name = "randomizer_bytes", lowerFixnum = 1)
public static abstract class RandomizerBytesPrimitiveNode extends PrimitiveArrayArgumentsNode {

@TruffleBoundary
@Specialization
public DynamicObject genRandBytes(DynamicObject randomizer, int length) {
final Random random = Layouts.RANDOMIZER.getRandom(randomizer);
final byte[] bytes = new byte[length];
int idx = 0;
for (; length >= 4; length -= 4) {
int r = random.genrandInt32();
for (int i = 0; i < 4; ++i) {
bytes[idx++] = (byte) (r & 0xff);
r >>>= 8;
}
}
if (length > 0) {
int r = random.genrandInt32();
for (int i = 0; i < length; ++i) {
bytes[idx++] = (byte) (r & 0xff);
r >>>= 8;
}
}
return createString(new ByteList(bytes));

This comment has been minimized.

Copy link
@nirvdrum

nirvdrum Jul 26, 2016

Contributor

Does this string have a known encoding? If so, you should use createString(bytes, <whatever the encoding is>) and avoid the ByteList allocation.

This comment has been minimized.

Copy link
@bjfish

bjfish Jul 26, 2016

Contributor

@nirvdrum Fixed at: 784e34b

}
}

@TruffleBoundary
private static int randomInt(Random random) {
return random.genrandInt32();
10 changes: 1 addition & 9 deletions truffle/src/main/ruby/core/random.rb
Original file line number Diff line number Diff line change
@@ -191,14 +191,6 @@ def ==(other)
# Returns a random binary string.
# The argument size specified the length of the result string.
def bytes(length)
length = Rubinius::Type.coerce_to length, Integer, :to_int
s = ''
i = 0
while i < length
s << @randomizer.random_integer(255).chr
i += 1
end

s
Truffle.invoke_primitive :randomizer_bytes, @randomizer, length
end
end

0 comments on commit a32dae5

Please sign in to comment.