Skip to content

Commit fb9bf7a

Browse files
committed
Merge pull request #21259 from dreis2211
* pr/21259: Further optimize StringSequence.startsWith Optimize StringSequence.startsWith Closes gh-21259
2 parents 7634901 + 4a8492d commit fb9bf7a

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/StringSequence.java

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2019 the original author or authors.
2+
* Copyright 2012-2020 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -98,23 +98,17 @@ int indexOf(String str, int fromIndex) {
9898
return this.source.indexOf(str, this.start + fromIndex) - this.start;
9999
}
100100

101-
boolean startsWith(CharSequence prefix) {
101+
boolean startsWith(String prefix) {
102102
return startsWith(prefix, 0);
103103
}
104104

105-
boolean startsWith(CharSequence prefix, int offset) {
105+
boolean startsWith(String prefix, int offset) {
106106
int prefixLength = prefix.length();
107-
if (length() - prefixLength - offset < 0) {
107+
int length = length();
108+
if (length - prefixLength - offset < 0) {
108109
return false;
109110
}
110-
int prefixOffset = 0;
111-
int sourceOffset = offset;
112-
while (prefixLength-- != 0) {
113-
if (charAt(sourceOffset++) != prefix.charAt(prefixOffset++)) {
114-
return false;
115-
}
116-
}
117-
return true;
111+
return this.source.startsWith(prefix, this.start + offset);
118112
}
119113

120114
@Override

spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,18 @@ void startsWithOffsetWhenShorterAndDoesNotStartWith() {
203203
assertThat(new StringSequence("xab").startsWith("c", 1)).isFalse();
204204
}
205205

206+
@Test
207+
void startsWithOnSubstringTailWhenMatch() {
208+
StringSequence subSequence = new StringSequence("xabc").subSequence(1);
209+
assertThat(subSequence.startsWith("abc")).isTrue();
210+
assertThat(subSequence.startsWith("abcd")).isFalse();
211+
}
212+
213+
@Test
214+
void startsWithOnSubstringMiddleWhenMatch() {
215+
StringSequence subSequence = new StringSequence("xabc").subSequence(1, 3);
216+
assertThat(subSequence.startsWith("ab")).isTrue();
217+
assertThat(subSequence.startsWith("abc")).isFalse();
218+
}
219+
206220
}

0 commit comments

Comments
 (0)