Skip to content

Commit

Permalink
[Truffle] Fix formatting of Bignum
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisseaton committed May 16, 2015
1 parent eb3c9bd commit 5c1ee15
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
import org.jruby.truffle.nodes.core.BignumNodes;
import org.jruby.truffle.pack.nodes.PackNode;
import org.jruby.truffle.pack.parser.FormatDirective;
import org.jruby.truffle.runtime.RubyContext;
import org.jruby.truffle.runtime.core.RubyBasicObject;
import org.jruby.util.ByteList;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

@NodeChildren({
@NodeChild(value = "value", type = PackNode.class),
Expand Down Expand Up @@ -46,6 +50,43 @@ public ByteList format(long value) {
return doFormat(value);
}

@CompilerDirectives.TruffleBoundary
@Specialization(guards = "isRubyBignum(value)")
public ByteList format(RubyBasicObject value) {
final BigInteger bigInteger = BignumNodes.getBigIntegerValue(value);

String formatted;

switch (format) {
case 'd':
case 'i':
case 'u':
formatted = bigInteger.toString();
break;

case 'x':
formatted = bigInteger.toString(16).toLowerCase(Locale.ENGLISH);
break;

case 'X':
formatted = bigInteger.toString(16).toUpperCase(Locale.ENGLISH);
break;

default:
throw new UnsupportedOperationException();
}

while (formatted.length() < spacePadding) {
formatted = " " + formatted;
}

while (formatted.length() < zeroPadding) {
formatted = "0" + formatted;
}

return new ByteList(formatted.getBytes(StandardCharsets.US_ASCII));
}

@CompilerDirectives.TruffleBoundary
protected ByteList doFormat(Object value) {
// TODO CS 3-May-15 write this without building a string and formatting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
import com.oracle.truffle.api.frame.VirtualFrame;
import org.jruby.truffle.pack.nodes.PackNode;
import org.jruby.truffle.runtime.RubyContext;
import org.jruby.truffle.runtime.core.RubyBasicObject;

import java.math.BigInteger;

@NodeChildren({
@NodeChild(value = "value", type = PackNode.class),
Expand All @@ -37,6 +40,11 @@ public long toInteger(VirtualFrame frame, long value) {
return value;
}

@Specialization(guards = "isRubyBignum(value)")
public RubyBasicObject toInteger(VirtualFrame frame, RubyBasicObject value) {
return value;
}

@Specialization
public long toInteger(VirtualFrame frame, double value) {
return (long) value;
Expand Down

0 comments on commit 5c1ee15

Please sign in to comment.