classlib: fix bug with precision in Formatter

This commit is contained in:
Alexey Andreev 2024-07-11 18:26:12 +02:00
parent 025801d385
commit e53af544a0
2 changed files with 6 additions and 1 deletions

View File

@ -516,7 +516,7 @@ public final class TFormatter implements Closeable, Flushable {
} }
private void formatGivenString(boolean upperCase, String str) throws IOException { private void formatGivenString(boolean upperCase, String str) throws IOException {
if (precision > 0) { if (precision > 0 && precision < str.length()) {
str = str.substring(0, precision); str = str.substring(0, precision);
} }

View File

@ -89,6 +89,11 @@ public class FormatterTest {
assertEquals("0:2:-1", new Formatter().format("%2s", new A()).toString()); assertEquals("0:2:-1", new Formatter().format("%2s", new A()).toString());
assertEquals("0:2:3", new Formatter().format("%2.3s", new A()).toString()); assertEquals("0:2:3", new Formatter().format("%2.3s", new A()).toString());
assertEquals("1:3:-1", new Formatter().format("%-3s", new A()).toString()); assertEquals("1:3:-1", new Formatter().format("%-3s", new A()).toString());
assertEquals("abcde", new Formatter().format("%-3.5s", "abcdefg").toString());
assertEquals("abcd", new Formatter().format("%-3.5s", "abcd").toString());
assertEquals("ab ", new Formatter().format("%-3.5s", "ab").toString());
assertEquals(" ab", new Formatter().format("%3.5s", " ab").toString());
} }
static class A implements Formattable { static class A implements Formattable {