Skip to content

Commit

Permalink
Substring.Match.contentEquals() as cheaper toString().equals()
Browse files Browse the repository at this point in the history
  • Loading branch information
fluentfuture committed Dec 7, 2023
1 parent e1b0009 commit d545762
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions mug/src/main/java/com/google/mu/util/Substring.java
Original file line number Diff line number Diff line change
Expand Up @@ -2511,6 +2511,16 @@ public int index() {
return startIndex;
}

/**
* Equivalent to {@code toString().equals(str)} but without copying the characters into a
* temporary string.
*
* @since 7.1
*/
public boolean contentEquals(String str) {
return str.length() == length() && context.startsWith(str, startIndex);
}

/**
* Returns true if this match starts with the given {@code prefix}.
*
Expand Down
15 changes: 15 additions & 0 deletions mug/src/test/java/com/google/mu/util/SubstringTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3802,6 +3802,21 @@ public void splitAfterDelimiter() {
.isEmpty();
}

@Test
public void match_contentEquals_false() {
Substring.Match match = first("bar").in("foobarbaz").get();
assertThat(match.contentEquals("barb")).isFalse();
assertThat(match.contentEquals("obar")).isFalse();
assertThat(match.contentEquals("ba")).isFalse();
assertThat(match.contentEquals("ar")).isFalse();
}

@Test
public void match_contentEquals_true() {
Substring.Match match = first("bar").in("foobarbaz").get();
assertThat(match.contentEquals("bar")).isTrue();
}

@Test
public void match_startsWith_false() {
Substring.Match match = first("bar").in("foobarbaz").get();
Expand Down

0 comments on commit d545762

Please sign in to comment.