Further optimize StringSequence.startsWith

See gh-21259
This commit is contained in:
Phillip Webb 2020-05-05 18:32:50 -07:00
parent 70ffc70993
commit 4a8492d428
2 changed files with 15 additions and 11 deletions

View File

@ -108,17 +108,7 @@ final class StringSequence implements CharSequence {
if (length - prefixLength - offset < 0) {
return false;
}
if (length == this.source.length()) {
return this.source.startsWith(prefix, offset);
}
int prefixOffset = 0;
int sourceOffset = offset;
while (prefixLength-- != 0) {
if (charAt(sourceOffset++) != prefix.charAt(prefixOffset++)) {
return false;
}
}
return true;
return this.source.startsWith(prefix, this.start + offset);
}
@Override

View File

@ -203,4 +203,18 @@ class StringSequenceTests {
assertThat(new StringSequence("xab").startsWith("c", 1)).isFalse();
}
@Test
void startsWithOnSubstringTailWhenMatch() {
StringSequence subSequence = new StringSequence("xabc").subSequence(1);
assertThat(subSequence.startsWith("abc")).isTrue();
assertThat(subSequence.startsWith("abcd")).isFalse();
}
@Test
void startsWithOnSubstringMiddleWhenMatch() {
StringSequence subSequence = new StringSequence("xabc").subSequence(1, 3);
assertThat(subSequence.startsWith("ab")).isTrue();
assertThat(subSequence.startsWith("abc")).isFalse();
}
}