Add generic support for hashing StringRef objects using the new hashing library.
authorChandler Carruth <chandlerc@gmail.com>
Sun, 4 Mar 2012 10:55:27 +0000 (10:55 +0000)
committerChandler Carruth <chandlerc@gmail.com>
Sun, 4 Mar 2012 10:55:27 +0000 (10:55 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@152003 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/ADT/StringRef.h
lib/Support/StringRef.cpp
unittests/ADT/StringRefTest.cpp

index 53ebe6a2af3942dbf2962913e5082b4915f97f37..a2bb7fe5fb9d8fbc30a72cc241dfaf7798cfba75 100644 (file)
@@ -19,6 +19,7 @@ namespace llvm {
   template<typename T>
   class SmallVectorImpl;
   class APInt;
+  class hash_code;
 
   /// StringRef - Represent a constant reference to a string, i.e. a character
   /// array and a length, which need not be null terminated.
@@ -490,6 +491,9 @@ namespace llvm {
 
   /// @}
 
+  /// \brief Compute a hash_code for a StringRef.
+  hash_code hash_value(StringRef S);
+
   // StringRefs can be treated like a POD type.
   template <typename T> struct isPodLike;
   template <> struct isPodLike<StringRef> { static const bool value = true; };
index 44e732540351e14287ec5857d40b2328643d1a44..1c28bf879e064aa63b524a313e36dfe077056cc8 100644 (file)
@@ -10,6 +10,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/edit_distance.h"
 #include <bitset>
 
@@ -447,3 +448,9 @@ bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
 
   return false;
 }
+
+
+// Implementation of StringRef hashing.
+hash_code llvm::hash_value(StringRef S) {
+  return hash_combine_range(S.begin(), S.end());
+}
index d91084381ec304881cf59ac8fe89ed1d87644ef5..b2f6fdcce0382cb2d038dbca2d00e5c6a4dd9a81 100644 (file)
@@ -9,6 +9,7 @@
 
 #include "gtest/gtest.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
@@ -291,4 +292,22 @@ TEST(StringRefTest, Misc) {
   EXPECT_EQ("hello", OS.str());
 }
 
+TEST(StringRefTest, Hashing) {
+  EXPECT_EQ(hash_value(std::string()), hash_value(StringRef()));
+  EXPECT_EQ(hash_value(std::string()), hash_value(StringRef("")));
+  std::string S = "hello world";
+  hash_code H = hash_value(S);
+  EXPECT_EQ(H, hash_value(StringRef("hello world")));
+  EXPECT_EQ(H, hash_value(StringRef(S)));
+  EXPECT_NE(H, hash_value(StringRef("hello worl")));
+  EXPECT_EQ(hash_value(std::string("hello worl")),
+            hash_value(StringRef("hello worl")));
+  EXPECT_NE(H, hash_value(StringRef("hello world ")));
+  EXPECT_EQ(hash_value(std::string("hello world ")),
+            hash_value(StringRef("hello world ")));
+  EXPECT_EQ(H, hash_value(StringRef("hello world\0")));
+  EXPECT_NE(hash_value(std::string("ello worl")),
+            hash_value(StringRef("hello world").slice(1, -1)));
+}
+
 } // end anonymous namespace