Skip to content

Commit

Permalink
Use new String#indexOf overload for Starlark's stringFind
Browse files Browse the repository at this point in the history
Since Java 21, the internal `indexOf` method on String that accepts start and end position is available as public API.

Closes bazelbuild#24333.

PiperOrigin-RevId: 697001722
Change-Id: I274b2ffd7a6d925531e1261f04bec5942d70fdf2
  • Loading branch information
fmeum authored and copybara-github committed Nov 15, 2024
1 parent b406bdc commit 1c9f1dd
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/main/java/net/starlark/java/eval/StringModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -532,15 +532,12 @@ private static int stringFind(boolean forward, String self, String sub, Object s
long indices = substringIndices(self, start, end);
int startpos = lo(indices);
int endpos = hi(indices);
// Unfortunately Java forces us to allocate here in the general case, even
// though String has a private indexOf method that accepts indices.
// The common cases of a search of the full string or a forward search with
// a custom start position do not require allocations.
if (forward && endpos == self.length()) {
return self.indexOf(sub, startpos);
if (forward) {
return self.indexOf(sub, startpos, endpos);
}
String substr = self.substring(startpos, endpos);
int subpos = forward ? substr.indexOf(sub) : substr.lastIndexOf(sub);
// String#lastIndexOf can't be used to implement rfind() because it only
// confines the start position of the substring, not the entire substring.
int subpos = self.substring(startpos, endpos).lastIndexOf(sub);
return subpos < 0
? subpos //
: subpos + startpos;
Expand Down

0 comments on commit 1c9f1dd

Please sign in to comment.