Skip to content

Commit

Permalink
Use single-char variant of String.indexOf() where possible (#105205)
Browse files Browse the repository at this point in the history
* Use single-char variant of String.indexOf() where possible

indexOf(char) is more efficient than searching for the same one-character String.

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
sabi0 and elasticmachine authored Feb 12, 2024
1 parent df4792e commit a50e58d
Show file tree
Hide file tree
Showing 39 changed files with 47 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public static void extendSourceSet(Project project, String parentSourceSetName,
* task execution time.
*/
public static String getProjectPathFromTask(String taskPath) {
int lastDelimiterIndex = taskPath.lastIndexOf(":");
int lastDelimiterIndex = taskPath.lastIndexOf(':');
return lastDelimiterIndex == 0 ? ":" : taskPath.substring(0, lastDelimiterIndex);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,10 @@ public class RestClient implements Closeable {
public static RestClientBuilder builder(String cloudId) {
// there is an optional first portion of the cloudId that is a human readable string, but it is not used.
if (cloudId.contains(":")) {
if (cloudId.indexOf(":") == cloudId.length() - 1) {
if (cloudId.indexOf(':') == cloudId.length() - 1) {
throw new IllegalStateException("cloudId " + cloudId + " must begin with a human readable identifier followed by a colon");
}
cloudId = cloudId.substring(cloudId.indexOf(":") + 1);
cloudId = cloudId.substring(cloudId.indexOf(':') + 1);
}

String decoded = new String(Base64.getDecoder().decode(cloudId), UTF_8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private DomainInfo getRegisteredDomain(IngestDocument d) {
}
return null;
}
if (registeredDomain.indexOf(".") == -1) {
if (registeredDomain.indexOf('.') == -1) {
// we have domain with no matching public suffix, but "." in it
return null;
}
Expand All @@ -117,7 +117,7 @@ private DomainInfo(String eTLD) {
}

private DomainInfo(String registeredDomain, String domain) {
int index = registeredDomain.indexOf(".") + 1;
int index = registeredDomain.indexOf('.') + 1;
if (index > 0 && index < registeredDomain.length()) {
this.domain = domain;
this.eTLD = registeredDomain.substring(index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ private static Map<String, Object> getUriParts(URI uri, URL fallbackUrl) {
if (userInfo != null) {
uriParts.put("user_info", userInfo);
if (userInfo.contains(":")) {
int colonIndex = userInfo.indexOf(":");
int colonIndex = userInfo.indexOf(':');
uriParts.put("username", userInfo.substring(0, colonIndex));
uriParts.put("password", colonIndex < userInfo.length() ? userInfo.substring(colonIndex + 1) : "");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public JavaClassFilesystemResolver(Path root, Map<String, Path> pkgRoots) {
public InputStream openClassFile(String className) throws IOException {
// TODO(stu): handle primitives & not stdlib
if (className.contains(".")) {
int dollarPosition = className.indexOf("$");
int dollarPosition = className.indexOf('$');
if (dollarPosition >= 0) {
className = className.substring(0, dollarPosition);
}
Expand All @@ -131,10 +131,10 @@ public InputStream openClassFile(String className) throws IOException {
Path classPath = root.resolve(path + ".java");
return new FileInputStream(classPath.toFile());
} else {
String packageName = className.substring(0, className.lastIndexOf("."));
String packageName = className.substring(0, className.lastIndexOf('.'));
Path packageRoot = pkgRoots.get(packageName);
if (packageRoot != null) {
Path classPath = packageRoot.resolve(className.substring(className.lastIndexOf(".") + 1) + ".java");
Path classPath = packageRoot.resolve(className.substring(className.lastIndexOf('.') + 1) + ".java");
return new FileInputStream(classPath.toFile());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ private String getProperty(String propertyName) {
for (int i = 0; i < settings.length; i++) {
String setting = settings[i].trim();
if (setting.length() > 0) {
final int idx = setting.indexOf("=");
final int idx = setting.indexOf('=');
if (idx == -1 || idx == 0 || idx == settings[i].length() - 1) {
new IllegalArgumentException("Invalid connection string: " + getConnectString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private static ICUTokenizerConfig getIcuConfig(Environment env, Settings setting
List<String> ruleFiles = settings.getAsList(RULE_FILES);

for (String scriptAndResourcePath : ruleFiles) {
int colonPos = scriptAndResourcePath.indexOf(":");
int colonPos = scriptAndResourcePath.indexOf(':');
if (colonPos == -1 || colonPos == scriptAndResourcePath.length() - 1) {
throw new IllegalArgumentException(RULE_FILES + " should contain comma-separated \"code:rulefile\" pairs");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ static String generateRolloverIndexName(String sourceIndexName) {
String resolvedName = IndexNameExpressionResolver.resolveDateMathExpression(sourceIndexName);
final boolean isDateMath = sourceIndexName.equals(resolvedName) == false;
if (INDEX_NAME_PATTERN.matcher(resolvedName).matches()) {
int numberIndex = sourceIndexName.lastIndexOf("-");
int numberIndex = sourceIndexName.lastIndexOf('-');
assert numberIndex != -1 : "no separator '-' found";
int counter = Integer.parseInt(
sourceIndexName.substring(numberIndex + 1, isDateMath ? sourceIndexName.length() - 1 : sourceIndexName.length())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private static boolean isNestedField(String field, Set<String> nestedParents) {
}

private static boolean isNotMultifield(String field, Set<String> objectFields) {
int lastDotPos = field.lastIndexOf(".");
int lastDotPos = field.lastIndexOf('.');
if (lastDotPos == -1) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2890,7 +2890,7 @@ public static int getRoutingFactor(int sourceNumberOfShards, int targetNumberOfS
* number
*/
public static int parseIndexNameCounter(String indexName) {
int numberIndex = indexName.lastIndexOf("-");
int numberIndex = indexName.lastIndexOf('-');
if (numberIndex == -1) {
throw new IllegalArgumentException("no - separator found in index name [" + indexName + "]");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static boolean isMatchAllPattern(String str) {
}

public static boolean isSuffixMatchPattern(String str) {
return str.length() > 1 && str.indexOf("*") == str.length() - 1;
return str.length() > 1 && str.indexOf('*') == str.length() - 1;
}

/** Return an {@link Automaton} that matches the given pattern. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public final void addDynamic(String name, String prefix, Mapper mapper, Document
// of the mapper name. So for a mapper 'foo.bar.baz', we locate 'foo' and then
// call addDynamic on it with the name 'bar.baz', and next call addDynamic on 'bar' with the name 'baz'.
else {
int firstDotIndex = name.indexOf(".");
int firstDotIndex = name.indexOf('.');
String immediateChild = name.substring(0, firstDotIndex);
String immediateChildFullName = prefix == null ? immediateChild : prefix + "." + immediateChild;
ObjectMapper.Builder parentBuilder = findObjectBuilder(immediateChildFullName, context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,7 @@ static final URI uncheckedToURI(URL url) {

static final String toPackageName(String className) {
assert className.endsWith(".") == false;
int index = className.lastIndexOf(".");
int index = className.lastIndexOf('.');
if (index == -1) {
throw new IllegalStateException("invalid class name:" + className);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public static void checkForFailedPluginRemovals(final Path pluginsDirectory) thr
if (iterator.hasNext()) {
final Path removing = iterator.next();
final String fileName = removing.getFileName().toString();
final String name = fileName.substring(1 + fileName.indexOf("-"));
final String name = fileName.substring(1 + fileName.indexOf('-'));
final String message = String.format(
Locale.ROOT,
"found file [%s] from a failed attempt to remove the plugin [%s]; execute [elasticsearch-plugin remove %2$s]",
Expand Down
2 changes: 1 addition & 1 deletion server/src/main/java/org/elasticsearch/rest/RestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static void decodeQueryString(String s, int fromIndex, Map<String, String
return;
}

int queryStringLength = s.contains("#") ? s.indexOf("#") : s.length();
int queryStringLength = s.contains("#") ? s.indexOf('#') : s.length();

String name = null;
int pos = fromIndex; // Beginning of the unprocessed region
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ private static void parseSearchSource(final SearchSourceBuilder searchSourceBuil
if (sSorts != null) {
String[] sorts = Strings.splitStringByCommaToArray(sSorts);
for (String sort : sorts) {
int delimiter = sort.lastIndexOf(":");
int delimiter = sort.lastIndexOf(':');
if (delimiter != -1) {
String sortField = sort.substring(0, delimiter);
String reverse = sort.substring(delimiter + 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ public CompilationRate(String value) {
"parameter must contain a positive integer and a timevalue, i.e. 10/1m, but was [" + value + "]"
);
}
int idx = value.indexOf("/");
int idx = value.indexOf('/');
String count = value.substring(0, idx);
String time = value.substring(idx + 1);
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ public static RequestComponents parseRequestComponents(final String request) {
final ArrayList<String> queryParameters = new ArrayList<>();
Arrays.stream(Strings.tokenizeToStringArray(queryString, "&")).forEach(param -> {
if (param.startsWith("x-")) {
final int equalPos = param.indexOf("=");
final int equalPos = param.indexOf('=');
customQueryParameters.computeIfAbsent(param.substring(0, equalPos), k -> new ArrayList<>())
.add(param.substring(equalPos + 1));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static Path copyResourceToFile(Class<?> clazz, Path targetFolder, String
throw new RuntimeException("Failed to load " + resourcePath + " from classpath");
}
InputStream inputStream = resourceUrl.openStream();
File outputFile = new File(targetFolder.toFile(), resourcePath.substring(resourcePath.lastIndexOf("/")));
File outputFile = new File(targetFolder.toFile(), resourcePath.substring(resourcePath.lastIndexOf('/')));
Files.copy(inputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return outputFile.toPath();
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ public Request(final long id, final String method, final URI uri, final Map<Stri
final Map<String, String> params = new HashMap<>();
if (uri.getQuery() != null && uri.getQuery().length() > 0) {
for (String param : uri.getQuery().split("&")) {
int i = param.indexOf("=");
int i = param.indexOf('=');
if (i > 0) {
params.put(param.substring(0, i), param.substring(i + 1));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ public record WrongLoggerUsage(String className, String methodName, String logMe
*/
public String getErrorLines() {
String fullClassName = Type.getObjectType(className).getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length());
int innerClassIndex = simpleClassName.indexOf("$");
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1, fullClassName.length());
int innerClassIndex = simpleClassName.indexOf('$');
if (innerClassIndex > 0) {
simpleClassName = simpleClassName.substring(0, innerClassIndex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void execute(ClientYamlTestExecutionContext executionContext) throws IOEx
String key = entry.getKey();
String value = entry.getValue();
if (value.startsWith("#base64EncodeCredentials(") && value.endsWith(")")) {
value = entry.getValue().substring("#base64EncodeCredentials(".length(), entry.getValue().lastIndexOf(")"));
value = entry.getValue().substring("#base64EncodeCredentials(".length(), entry.getValue().lastIndexOf(')'));
String[] idAndPassword = value.split(",");
if (idAndPassword.length == 2) {
String credentials = executionContext.response(idAndPassword[0].trim())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ public static String validateMonotonicallyIncreasingPhaseTimings(Collection<Phas
}
// if multiple phases are cited replace last occurrence of "," with " and"
StringBuilder builder = new StringBuilder();
int last_comma_index = error.lastIndexOf(",");
int last_comma_index = error.lastIndexOf(',');
builder.append(error, 0, last_comma_index);
builder.append(" and");
builder.append(error.substring(last_comma_index + 1));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static Settings addUserSettings(final Settings settings) {
if (settings.get(authHeaderSettingName) == null) {
Optional<String> userOptional = SecurityField.USER_SETTING.get(settings); // TODO migrate to securesetting!
userOptional.ifPresent(userSetting -> {
final int i = userSetting.indexOf(":");
final int i = userSetting.indexOf(':');
if (i < 0 || i == userSetting.length() - 1) {
throw new IllegalArgumentException(
"invalid [" + SecurityField.USER_SETTING.getKey() + "] setting. must be in the form of \"<username>:<password>\""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ private static void validateFallbackClaimSetting(
}

private static void verifyFallbackClaimName(String key, String fallbackClaimName) {
final String claimName = key.substring(key.lastIndexOf(".") + 1);
final String claimName = key.substring(key.lastIndexOf('.') + 1);
verifyNonNullNotEmpty(key, fallbackClaimName, null);
if (claimName.equals(fallbackClaimName)) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public Wid(String watchId, ZonedDateTime executionTime) {

public Wid(String value) {
this.value = value;
int index = value.lastIndexOf("_");
int index = value.lastIndexOf('_');
if (index <= 0) {
throw illegalArgument("invalid watcher execution id [{}]", value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public void close() {
if (columns == null) {
columns = new CsvColumn[entries.length];
for (int i = 0; i < entries.length; i++) {
int split = entries[i].indexOf(":");
int split = entries[i].indexOf(':');
String name, typeName;

if (split < 0) {
Expand Down Expand Up @@ -245,7 +245,7 @@ static String[] multiValuesAwareCsvToStringArray(String csvLine, int lineNumber)
int pos = 0; // current position in the csv String
int commaPos; // current "," character position
int previousCommaPos = 0;
while ((commaPos = csvLine.indexOf(",", pos)) != -1 || pos <= csvLine.length()) {
while ((commaPos = csvLine.indexOf(',', pos)) != -1 || pos <= csvLine.length()) {
if (commaPos > 0 && csvLine.charAt(commaPos - 1) == ESCAPE_CHAR) {// skip the escaped comma
pos = commaPos + 1;// moving on to the next character after comma
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ private static void loadCsvData(
if (columns == null) {
columns = new String[entries.length];
for (int i = 0; i < entries.length; i++) {
int split = entries[i].indexOf(":");
int split = entries[i].indexOf(':');
String name, typeName;

if (split < 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ private Object extractNestedField(SearchHit hit) {
List<String> remainingPath = new ArrayList<>();
// first, search for the "root" DocumentField under which the remaining path of nested document values is
while ((field = hit.field(tempHitname)) == null) {
int indexOfDot = tempHitname.lastIndexOf(".");
int indexOfDot = tempHitname.lastIndexOf('.');
if (indexOfDot < 0) {// there is no such field in the hit
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ public static <E> Class<E> detectSuperTypeForRuleLike(Class<?> c) {
// remove packaging from the name - strategy used for naming rules by default
public static String ruleLikeNaming(Class<?> c) {
String className = c.getName();
int parentPackage = className.lastIndexOf(".");
int parentPackage = className.lastIndexOf('.');
if (parentPackage > 0) {
int grandParentPackage = className.substring(0, parentPackage).lastIndexOf(".");
int grandParentPackage = className.substring(0, parentPackage).lastIndexOf('.');
return (grandParentPackage > 0 ? className.substring(grandParentPackage + 1) : className.substring(parentPackage));
} else {
return className;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static List<Object[]> readScriptSpec(List<URL> urls, Parser parser) throw

public static List<Object[]> readURLSpec(URL source, Parser parser) throws Exception {
String fileName = pathAndName(source.getFile()).v2();
String groupName = fileName.substring(0, fileName.lastIndexOf("."));
String groupName = fileName.substring(0, fileName.lastIndexOf('.'));

Map<String, Integer> testNames = new LinkedHashMap<>();
List<Object[]> testCases = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ public static BufferedReader reader(URL resource) throws IOException {
public static Tuple<String, String> pathAndName(String string) {
String folder = StringUtils.EMPTY;
String file = string;
int lastIndexOf = string.lastIndexOf("/");
int lastIndexOf = string.lastIndexOf('/');
if (lastIndexOf > 0) {
folder = string.substring(0, lastIndexOf - 1);
if (lastIndexOf + 1 < string.length()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public static Map<String, String[]> parseFile(Path path, @Nullable Logger logger
if (line.startsWith("#")) { // comment
continue;
}
int i = line.indexOf(":");
int i = line.indexOf(':');
if (i <= 0 || i == line.length() - 1) {
logger.error("invalid entry in users_roles file [{}], line [{}]. skipping...", path.toAbsolutePath(), lineNr);
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ ServerSet getServerSet() {
ADAuthenticator getADAuthenticator(String username) {
if (username.indexOf('\\') > 0) {
return downLevelADAuthenticator;
} else if (username.indexOf("@") > 0) {
} else if (username.indexOf('@') > 0) {
return upnADAuthenticator;
}
return defaultADAuthenticator;
Expand Down
Loading

0 comments on commit a50e58d

Please sign in to comment.