[llvm] [ADT] Reimplement operator==(StringRef (PR #91139)

Kazu Hirata via llvm-commits llvm-commits at lists.llvm.org
Sun May 5 13:41:14 PDT 2024


https://github.com/kazutakahirata updated https://github.com/llvm/llvm-project/pull/91139

>From 217679639986b73a2c4c528635d4c59805945820 Mon Sep 17 00:00:00 2001
From: Kazu Hirata <kazu at google.com>
Date: Fri, 3 May 2024 22:40:49 -0700
Subject: [PATCH 1/2] [ADT] Reimplement operator==(StringRef, StringRef) (NFC)

I'm planning to deprecate and eventually remove StringRef::equals in
favor of operator==.  This patch reimplements operator== without using
StringRef::equals.

I'm not sure if there is a good way to make StringRef::compareMemory
available to operator==, which is not a member function.  "friend"
works to some extent but breaks corner cases, which is why I've chosen
to "inline" compareMemory.
---
 llvm/include/llvm/ADT/StringRef.h | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index 04496c76e07201..1424a526e678fc 100644
--- a/llvm/include/llvm/ADT/StringRef.h
+++ b/llvm/include/llvm/ADT/StringRef.h
@@ -871,7 +871,11 @@ namespace llvm {
   /// @{
 
   inline bool operator==(StringRef LHS, StringRef RHS) {
-    return LHS.equals(RHS);
+    if (LHS.size() != RHS.size())
+      return 0;
+    if (LHS.empty())
+      return 1;
+    return ::memcmp(LHS.data(), RHS.data(), LHS.size()) == 0;
   }
 
   inline bool operator!=(StringRef LHS, StringRef RHS) { return !(LHS == RHS); }

>From d996220c8ed909498c4f6f376365640635ec9418 Mon Sep 17 00:00:00 2001
From: Kazu Hirata <kazu at google.com>
Date: Sun, 5 May 2024 13:38:53 -0700
Subject: [PATCH 2/2] Use false and true instead of 0 and 1, respectively.

---
 llvm/include/llvm/ADT/StringRef.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index 1424a526e678fc..8ed8e424cfe13c 100644
--- a/llvm/include/llvm/ADT/StringRef.h
+++ b/llvm/include/llvm/ADT/StringRef.h
@@ -872,9 +872,9 @@ namespace llvm {
 
   inline bool operator==(StringRef LHS, StringRef RHS) {
     if (LHS.size() != RHS.size())
-      return 0;
+      return false;
     if (LHS.empty())
-      return 1;
+      return true;
     return ::memcmp(LHS.data(), RHS.data(), LHS.size()) == 0;
   }
 



More information about the llvm-commits mailing list