Skip to content

Commit 71f52d5

Browse files
eamonnmcmanusgoogle-java-format Team
authored andcommitted
Maintain a start position in CharStream instead of using repeated tailing.
Constructing smaller and smaller substrings implies quadratic runtime. While this is unlikely to make much difference on typically-sized Javadoc comments, the alternative is just as clear. PiperOrigin-RevId: 884432763
1 parent 273ddcf commit 71f52d5

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,42 +27,45 @@
2727
* characters from tryConsume? -- but it is convenient for the lexer.
2828
*/
2929
final class CharStream {
30-
String remaining;
31-
int toConsume;
30+
private final String input;
31+
private int start;
32+
private int tokenEnd = -1; // Negative value means no token, and will cause an exception if used.
3233

3334
CharStream(String input) {
34-
this.remaining = checkNotNull(input);
35+
this.input = checkNotNull(input);
3536
}
3637

3738
boolean tryConsume(String expected) {
38-
if (!remaining.startsWith(expected)) {
39+
if (!input.startsWith(expected, start)) {
3940
return false;
4041
}
41-
toConsume = expected.length();
42+
tokenEnd = start + expected.length();
4243
return true;
4344
}
4445

45-
/*
46+
/**
47+
* Tries to consume characters from the current position that match the given pattern.
48+
*
4649
* @param pattern the pattern to search for, which must be anchored to match only at position 0
4750
*/
4851
boolean tryConsumeRegex(Pattern pattern) {
49-
Matcher matcher = pattern.matcher(remaining);
52+
Matcher matcher = pattern.matcher(input).region(start, input.length());
5053
if (!matcher.find()) {
5154
return false;
5255
}
53-
checkArgument(matcher.start() == 0);
54-
toConsume = matcher.end();
56+
checkArgument(matcher.start() == start);
57+
tokenEnd = matcher.end();
5558
return true;
5659
}
5760

5861
String readAndResetRecorded() {
59-
String result = remaining.substring(0, toConsume);
60-
remaining = remaining.substring(toConsume);
61-
toConsume = 0; // TODO(cpovirk): Set this to a bogus value here and in the constructor.
62+
String result = input.substring(start, tokenEnd);
63+
start = tokenEnd;
64+
tokenEnd = -1;
6265
return result;
6366
}
6467

6568
boolean isExhausted() {
66-
return remaining.isEmpty();
69+
return start == input.length();
6770
}
6871
}

0 commit comments

Comments
 (0)