Skip to content

Commit

Permalink
Make StartsWith and EndsWith constexpr.
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Abseil Team authored and copybara-github committed Dec 2, 2024
1 parent a04ef10 commit 6757696
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions absl/strings/match.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,32 @@ inline bool StrContains(absl::string_view haystack, char needle) noexcept {
// StartsWith()
//
// Returns whether a given string `text` begins with `prefix`.
inline bool StartsWith(absl::string_view text,
absl::string_view prefix) noexcept {
return prefix.empty() ||
(text.size() >= prefix.size() &&
memcmp(text.data(), prefix.data(), prefix.size()) == 0);
inline constexpr bool StartsWith(absl::string_view text,
absl::string_view prefix) noexcept {
if (prefix.empty()) {
return true;
}
if (text.size() < prefix.size()) {
return false;
}
absl::string_view possible_match = text.substr(0, prefix.size());

return possible_match == prefix;
}

// EndsWith()
//
// Returns whether a given string `text` ends with `suffix`.
inline bool EndsWith(absl::string_view text,
absl::string_view suffix) noexcept {
return suffix.empty() ||
(text.size() >= suffix.size() &&
memcmp(text.data() + (text.size() - suffix.size()), suffix.data(),
suffix.size()) == 0);
inline constexpr bool EndsWith(absl::string_view text,
absl::string_view suffix) noexcept {
if (suffix.empty()) {
return true;
}
if (text.size() < suffix.size()) {
return false;
}
absl::string_view possible_match = text.substr(text.size() - suffix.size());
return possible_match == suffix;
}
// StrContainsIgnoreCase()
//
Expand Down

0 comments on commit 6757696

Please sign in to comment.