Skip to content

Commit 3056d38

Browse files
committed
1 parent a8ba15f commit 3056d38

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

src/main/java/org/truffleruby/core/rope/LazyIntRope.java

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,29 +27,43 @@ public LazyIntRope(int value) {
2727
protected LazyIntRope(int value, Encoding encoding, int length) {
2828
super(encoding, CodeRange.CR_7BIT, length, length, null);
2929
this.value = value;
30-
assert Integer.toString(value).length() == length;
30+
assert Integer.toString(value).length() == length : value + " " + length;
3131
}
3232

33-
private static int length(int value) {
34-
final int sign;
33+
private static final int[] LENGTH_TABLE = {
34+
9,
35+
99,
36+
999,
37+
9999,
38+
99999,
39+
999999,
40+
9999999,
41+
99999999,
42+
999999999,
43+
2147483647 };
3544

36-
if (value < 0) {
37-
/* We can't represent -Integer.MIN_VALUE, and we're about to multiple by 10 to add the space needed for the
38-
* negative character, so handle both of those out-of-range cases. */
45+
private static int length(int value) {
46+
if (CompilerDirectives.injectBranchProbability(CompilerDirectives.UNLIKELY_PROBABILITY, value == 0)) {
47+
return 1;
48+
}
3949

40-
if (value <= -1000000000) {
41-
return 11;
42-
}
50+
final int sign;
4351

44-
value = -value;
52+
if (CompilerDirectives.injectBranchProbability(CompilerDirectives.UNLIKELY_PROBABILITY, value < 0)) {
4553
sign = 1;
54+
value = -value;
4655
} else {
4756
sign = 0;
4857
}
4958

50-
return sign + (value < 1E5
51-
? value < 1E2 ? value < 1E1 ? 1 : 2 : value < 1E3 ? 3 : value < 1E4 ? 4 : 5
52-
: value < 1E7 ? value < 1E6 ? 6 : 7 : value < 1E8 ? 8 : value < 1E9 ? 9 : 10);
59+
final int bits = 31 - Integer.numberOfLeadingZeros(value);
60+
int digits = ((77 * bits) >>> 8);
61+
62+
if (value > LENGTH_TABLE[digits]) {
63+
digits += 1;
64+
}
65+
66+
return sign + digits + 1;
5367
}
5468

5569
@Override

0 commit comments

Comments
 (0)