Skip to content

Commit

Permalink
Calculate correct column width for data with line breaks
Browse files Browse the repository at this point in the history
  • Loading branch information
freva committed May 16, 2021
1 parent 85012e0 commit 1c090d4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/com/github/freva/asciitable/AsciiTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ private static int[] getColWidths(Column[] columns, String[][] data) {

for (String[] dataRow : data) {
for (int col = 0; col < dataRow.length; col++) {
result[col] = Math.max(result[col], dataRow[col] == null ? 0 : dataRow[col].length());
result[col] = Math.max(result[col], dataRow[col] == null ? 0 : LineUtils.maxLineLength(dataRow[col]));
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/github/freva/asciitable/LineUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ public static Stream<String> lines(String str) {
false);
}

public static int maxLineLength(String str) {
int max = 0;
LineIterator lineIterator = new LineIterator(str);
while (lineIterator.hasNext()) {
int start = lineIterator.getPosition();
max = Math.max(max, lineIterator.getLineEndPositionAndAdvanceToNextLine() - start);
}
return max;
}

private static class LineIterator implements Iterator<String> {
private final String str;
private int position = 0;
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/com/github/freva/asciitable/AsciiTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,18 @@ public void testObjectDataArray() {
assertEquals(expected, actual);
}

@Test
public void calculatesCorrectColumnWidthWithLineBreak() {
String[][] data = {{"String", "First line\nSecond line"}};
String actual = AsciiTable.getTable(data);
String expected = String.join(System.lineSeparator(),
"+--------+-------------+\n" +
"| String | First line |",
"| | Second line |",
"+--------+-------------+");
assertEquals(expected, actual);
}

@Test(expected = IllegalArgumentException.class)
public void testValidateTooFewBorderChars() {
String[] headers = {"Lorem", "Ipsum", "Dolor", "Sit"};
Expand Down

0 comments on commit 1c090d4

Please sign in to comment.