Skip to content

Commit 8963dbe

Browse files
committed
fix sprintf WIP
1 parent f65c42a commit 8963dbe

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

src/main/java/org/perlonjava/operators/SprintfOperator.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ public class SprintfOperator {
2121

2222
private static int charsWritten = 0;
2323

24+
// Maximum practical limit for width/precision to prevent memory issues
25+
private static final int MAX_PRACTICAL_FORMAT_SIZE = 2000000000;
26+
2427
/**
2528
* Formats the elements according to the specified format string.
2629
* <p>
@@ -64,7 +67,10 @@ public static RuntimeScalar sprintf(RuntimeScalar runtimeScalar, RuntimeList lis
6467
(spec.precision != null && spec.precision == Integer.MAX_VALUE) ||
6568
(spec.parameterIndex != null && spec.parameterIndex == Integer.MAX_VALUE) ||
6669
(spec.widthArgIndex != null && spec.widthArgIndex == Integer.MAX_VALUE) ||
67-
(spec.precisionArgIndex != null && spec.precisionArgIndex == Integer.MAX_VALUE)) {
70+
(spec.precisionArgIndex != null && spec.precisionArgIndex == Integer.MAX_VALUE) ||
71+
// Check for impractically large width/precision values
72+
(spec.width != null && spec.width > MAX_PRACTICAL_FORMAT_SIZE) ||
73+
(spec.precision != null && spec.precision > MAX_PRACTICAL_FORMAT_SIZE)) {
6874
throw new RuntimeException("Integer overflow in format string for sprintf ");
6975
}
7076

src/main/java/org/perlonjava/operators/sprintf/SprintfNumericFormatter.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,12 @@ public String formatFloatingPoint(double value, String flags, int width,
290290
cleanFlags = cleanFlags.replace("0", "");
291291
}
292292

293+
// Java requires width when using - flag, but Perl doesn't
294+
// Add a minimal width if - flag is present but width is 0
295+
if (cleanFlags.contains("-") && width == 0) {
296+
width = 1; // Minimal width to satisfy Java's formatter
297+
}
298+
293299
// Special handling for %g to remove trailing zeros
294300
if ((conversion == 'g' || conversion == 'G')) {
295301
return formatGFloatingPoint(value, cleanFlags, width, precision, conversion);

0 commit comments

Comments
 (0)