diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java index 9a5b9fa29bb..355f4176097 100644 --- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java +++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java @@ -71,6 +71,9 @@ public class CharTermAttributeImpl extends AttributeImpl implements CharTermAttr @Override public final CharTermAttribute setLength(int length) { + if (length < 0) { + throw new IllegalArgumentException("length " + length + " must not be negative"); + } if (length > termBuffer.length) throw new IllegalArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.length + ")"); termLength = length; diff --git a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java index 81dd576be08..30821291fc8 100644 --- a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java +++ b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java @@ -42,6 +42,16 @@ public class TestCharTermAttributeImpl extends LuceneTestCase { } } + public void testSetLength() { + CharTermAttributeImpl t = new CharTermAttributeImpl(); + char[] content = "hello".toCharArray(); + t.copyBuffer(content, 0, content.length); + IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { + t.setLength(-1); + }); + assertTrue(expected.getMessage().contains("must not be negative")); + } + public void testGrow() { CharTermAttributeImpl t = new CharTermAttributeImpl(); StringBuilder buf = new StringBuilder("ab");