Skip to content

Commit 6757696

Browse files
Abseil Teamcopybara-github
authored andcommitted
Make StartsWith and EndsWith constexpr.
This required rewriting StartsWith and EndsWith to not use memcmp and just create a string_view for the substring instead which can then be compared with operator==. PiperOrigin-RevId: 702095989 Change-Id: I73474dd2e9a7fbbde563baf39e7cedd4fc2357e7
1 parent a04ef10 commit 6757696

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

absl/strings/match.h

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,22 +55,32 @@ inline bool StrContains(absl::string_view haystack, char needle) noexcept {
5555
// StartsWith()
5656
//
5757
// Returns whether a given string `text` begins with `prefix`.
58-
inline bool StartsWith(absl::string_view text,
59-
absl::string_view prefix) noexcept {
60-
return prefix.empty() ||
61-
(text.size() >= prefix.size() &&
62-
memcmp(text.data(), prefix.data(), prefix.size()) == 0);
58+
inline constexpr bool StartsWith(absl::string_view text,
59+
absl::string_view prefix) noexcept {
60+
if (prefix.empty()) {
61+
return true;
62+
}
63+
if (text.size() < prefix.size()) {
64+
return false;
65+
}
66+
absl::string_view possible_match = text.substr(0, prefix.size());
67+
68+
return possible_match == prefix;
6369
}
6470

6571
// EndsWith()
6672
//
6773
// Returns whether a given string `text` ends with `suffix`.
68-
inline bool EndsWith(absl::string_view text,
69-
absl::string_view suffix) noexcept {
70-
return suffix.empty() ||
71-
(text.size() >= suffix.size() &&
72-
memcmp(text.data() + (text.size() - suffix.size()), suffix.data(),
73-
suffix.size()) == 0);
74+
inline constexpr bool EndsWith(absl::string_view text,
75+
absl::string_view suffix) noexcept {
76+
if (suffix.empty()) {
77+
return true;
78+
}
79+
if (text.size() < suffix.size()) {
80+
return false;
81+
}
82+
absl::string_view possible_match = text.substr(text.size() - suffix.size());
83+
return possible_match == suffix;
7484
}
7585
// StrContainsIgnoreCase()
7686
//

0 commit comments

Comments
 (0)