Skip to content

Commit a10c0a7

Browse files
author
Zach Olstein
committed
Fix string formatting of numbers outside int range
Prior to this patch, string '%' formatting would produce incorrect results on numbers outside the 32-bit integer range. Before formatting these values the StringFormatter would convert the values down to ints. To fix this, we can format these values as BigIntegers. This will have some performance impact, but can be optimized later by introducing a code path to format primative long values and possibly by conditionally down-casting BigIntegers to ints or longs when safe to use those (presumedly faster) code paths.
1 parent ddf5923 commit a10c0a7

File tree

1 file changed

+4
-3
lines changed
  • graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/formatting

1 file changed

+4
-3
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/formatting/StringFormatter.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
1616
import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError;
1717

18-
import com.oracle.graal.python.util.BiFunction;
18+
import java.math.BigInteger;
19+
import java.util.function.BiFunction;
1920

2021
import com.oracle.graal.python.builtins.PythonBuiltinClassType;
2122
import com.oracle.graal.python.builtins.objects.PNone;
@@ -393,10 +394,10 @@ public Object format(Object args1, CallNode callNode, BiFunction<Object, String,
393394
fi.format((Integer) argAsNumber);
394395
} else if (argAsNumber instanceof Long) {
395396
f = fi = new IntegerFormatter.Traditional(core, buffer, spec);
396-
fi.format(((Long) argAsNumber).intValue());
397+
fi.format((BigInteger.valueOf((Long) argAsNumber)));
397398
} else if (argAsNumber instanceof PInt) {
398399
f = fi = new IntegerFormatter.Traditional(core, buffer, spec);
399-
fi.format(((PInt) argAsNumber).intValue());
400+
fi.format(((PInt) argAsNumber).getValue());
400401
} else if (arg instanceof String && ((String) arg).length() == 1) {
401402
f = ft = new TextFormatter(core, buffer, spec);
402403
ft.format((String) arg);

0 commit comments

Comments
 (0)