[llvm] [NFC][LLVM][ADT] Simplify `StringRef` case insensitive compare (PR #147994)
Rahul Joshi via llvm-commits
llvm-commits at lists.llvm.org
Thu Jul 10 09:23:33 PDT 2025
https://github.com/jurahul created https://github.com/llvm/llvm-project/pull/147994
Change `ascii_strncasecmp` to use a range for loop and use StringRef parameters.
>From f9020f44b0bc0ebbdd505ef4f69c6675b8347017 Mon Sep 17 00:00:00 2001
From: Rahul Joshi <rjoshi at nvidia.com>
Date: Thu, 10 Jul 2025 09:20:07 -0700
Subject: [PATCH] [NFC][LLVM][ADT] Simplify `StringRef` case insensitive
compare
Change `ascii_strncasecmp` to use a range for loop and use
StringRef parameters.
---
llvm/lib/Support/StringRef.cpp | 17 ++++++++---------
1 file changed, 8 insertions(+), 9 deletions(-)
diff --git a/llvm/lib/Support/StringRef.cpp b/llvm/lib/Support/StringRef.cpp
index 96829bd062a78..dc758785e40d5 100644
--- a/llvm/lib/Support/StringRef.cpp
+++ b/llvm/lib/Support/StringRef.cpp
@@ -24,10 +24,10 @@ constexpr size_t StringRef::npos;
// strncasecmp() is not available on non-POSIX systems, so define an
// alternative function here.
-static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
- for (size_t I = 0; I < Length; ++I) {
- unsigned char LHC = toLower(LHS[I]);
- unsigned char RHC = toLower(RHS[I]);
+static int ascii_strncasecmp(StringRef LHS, StringRef RHS) {
+ for (auto [LC, RC] : zip_equal(LHS, RHS)) {
+ unsigned char LHC = toLower(LC);
+ unsigned char RHC = toLower(RC);
if (LHC != RHC)
return LHC < RHC ? -1 : 1;
}
@@ -35,8 +35,8 @@ static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
}
int StringRef::compare_insensitive(StringRef RHS) const {
- if (int Res =
- ascii_strncasecmp(data(), RHS.data(), std::min(size(), RHS.size())))
+ size_t Min = std::min(size(), RHS.size());
+ if (int Res = ascii_strncasecmp(take_front(Min), RHS.take_front(Min)))
return Res;
if (size() == RHS.size())
return 0;
@@ -45,13 +45,12 @@ int StringRef::compare_insensitive(StringRef RHS) const {
bool StringRef::starts_with_insensitive(StringRef Prefix) const {
return size() >= Prefix.size() &&
- ascii_strncasecmp(data(), Prefix.data(), Prefix.size()) == 0;
+ ascii_strncasecmp(take_front(Prefix.size()), Prefix) == 0;
}
bool StringRef::ends_with_insensitive(StringRef Suffix) const {
return size() >= Suffix.size() &&
- ascii_strncasecmp(end() - Suffix.size(), Suffix.data(),
- Suffix.size()) == 0;
+ ascii_strncasecmp(take_back(Suffix.size()), Suffix) == 0;
}
size_t StringRef::find_insensitive(char C, size_t From) const {
More information about the llvm-commits
mailing list