From d545762e334f7589e5c1c77d174589c60ce0af39 Mon Sep 17 00:00:00 2001 From: Ben Yu Date: Wed, 6 Dec 2023 18:59:01 -0800 Subject: [PATCH] Substring.Match.contentEquals() as cheaper toString().equals() --- .../main/java/com/google/mu/util/Substring.java | 10 ++++++++++ .../java/com/google/mu/util/SubstringTest.java | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/mug/src/main/java/com/google/mu/util/Substring.java b/mug/src/main/java/com/google/mu/util/Substring.java index 04c3ba07f4..bd2809c198 100644 --- a/mug/src/main/java/com/google/mu/util/Substring.java +++ b/mug/src/main/java/com/google/mu/util/Substring.java @@ -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}. * diff --git a/mug/src/test/java/com/google/mu/util/SubstringTest.java b/mug/src/test/java/com/google/mu/util/SubstringTest.java index 4b6529a691..8e9b31c83a 100644 --- a/mug/src/test/java/com/google/mu/util/SubstringTest.java +++ b/mug/src/test/java/com/google/mu/util/SubstringTest.java @@ -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();