Skip to content

Commit 8c91446

Browse files
authored
Fix overflow in BoundedDelimitedStringCollector (elastic#141849)
The comment lies, the overflow happens before up-casting to `long`.
1 parent 479ffcb commit 8c91446

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

server/src/main/java/org/elasticsearch/common/Strings.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ public static final class BoundedDelimitedStringCollector {
594594
public BoundedDelimitedStringCollector(StringBuilder stringBuilder, String delimiter, int appendLimit) {
595595
this.stringBuilder = stringBuilder;
596596
this.delimiter = delimiter;
597-
this.lengthLimit = stringBuilder.length() + appendLimit; // long to avoid overflow
597+
this.lengthLimit = (long) stringBuilder.length() + appendLimit; // long to avoid overflow
598598
}
599599

600600
/**

server/src/test/java/org/elasticsearch/common/BoundedDelimitedStringCollectorTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,18 @@ public void testCollectionToDelimitedStringWithLimitNoTruncation() {
131131
assertThat(testHarness.getResult(strings, delimiter, limit), equalTo(fullDescription));
132132
}
133133

134+
public void testLimitOverflow() {
135+
final var stringBuilder = new StringBuilder("nonempty prefix");
136+
final var collector = new Strings.BoundedDelimitedStringCollector(
137+
stringBuilder,
138+
"",
139+
Integer.MAX_VALUE - between(0, stringBuilder.length() - 1)
140+
);
141+
142+
collector.appendItem(", item");
143+
collector.finish();
144+
145+
assertEquals("nonempty prefix, item", stringBuilder.toString());
146+
}
147+
134148
}

0 commit comments

Comments
 (0)